: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
fix(phai): render widgets from mcp result envelopes (#97229)
Georgiy Tarasovf823f940adc7
diff --git a/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.test.tsx b/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.test.tsxindex 075265fa16ce..45c5050fc0a7 100644--- a/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.test.tsx+++ b/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.test.tsx@@ -52,6 +52,14 @@ describe('CreateNotebookWidget', () => {version: 1,},],+ ['short_id with empty content', { short_id: 'aBcDe123', content: [] }],+ [+ 'short_id with node list content',+ {+ short_id: 'aBcDe123',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Sample notebook' }] }],+ },+ ],['notebook_id', { notebook_id: 'aBcDe123' }],])('reads the short id from %s, with the title and the _posthogUrl enrichment', (_field, payload) => {const notebook = extractNotebook(diff --git a/products/posthog_ai/frontend/components/tool/widgets/extractors.test.ts b/products/posthog_ai/frontend/components/tool/widgets/extractors.test.tsindex 1ea685cef186..37c3681650a3 100644--- a/products/posthog_ai/frontend/components/tool/widgets/extractors.test.ts+++ b/products/posthog_ai/frontend/components/tool/widgets/extractors.test.ts@@ -30,13 +30,40 @@ function toolMessage(describe('mcp tool adapter extractors', () => {describe('extractVisualizationArtifact', () => {- it('classifies a REST insight payload with short_id as a saved insight', () => {- const artifact = extractVisualizationArtifact(- toolMessage({ short_id: 'abc12345', name: 'Signups', query: { kind: 'TrendsQuery' } })- )+ const savedInsight = { short_id: 'abc12345', name: 'Signups', query: { kind: 'TrendsQuery' } }++ it.each([+ ['direct payload', savedInsight],+ [+ 'MCP structured content',+ {+ structuredContent: savedInsight,+ content: [{ type: 'text', text: '{"query":{"kind":"FunnelsQuery"}}' }],+ isError: false,+ },+ ],+ ['MCP JSON text', { content: [{ type: 'text', text: JSON.stringify(savedInsight) }], isError: false }],+ [+ 'MCP JSON text without optional fields',+ { content: [{ type: 'text', text: JSON.stringify(savedInsight) }] },+ ],+ [+ 'MCP TOON text with no structured content',+ {+ structuredContent: null,+ content: [+ { type: 'image', data: 'unused', mimeType: 'image/png' },+ { type: 'text', text: 'short_id: abc12345\nname: Signups\nquery:\n kind: TrendsQuery' },+ ],+ isError: false,+ },+ ],+ ])('classifies a saved insight from %s', (_format, rawOutput) => {+ const artifact = extractVisualizationArtifact(toolMessage(rawOutput))expect(artifact?.envelope.source).toBe(ArtifactSource.Insight)expect(artifact?.envelope.artifact_id).toBe('abc12345')expect(artifact?.content.name).toBe('Signups')+ expect(artifact?.content.query).toEqual(savedInsight.query)})it('classifies a query-only output as ephemeral', () => {@@ -45,9 +72,15 @@ describe('mcp tool adapter extractors', () => {expect(artifact?.envelope.artifact_id).toBe('call-1')})- it('returns null when the output has no query', () => {- expect(extractVisualizationArtifact(toolMessage({ id: 1, name: 'No query here' }))).toBeNull()- expect(extractVisualizationArtifact(toolMessage(undefined))).toBeNull()+ it.each([+ undefined,+ { id: 1, name: 'No query here' },+ { content: [] },+ { content: [null, { type: 'image', data: 'unused', mimeType: 'image/png' }] },+ { content: [{ type: 'text', text: 'No insight found' }] },+ { structuredContent: savedInsight, isError: true },+ ])('returns null for missing, malformed, or failed insight output: %j', (rawOutput) => {+ expect(extractVisualizationArtifact(toolMessage(rawOutput))).toBeNull()})})diff --git a/products/posthog_ai/frontend/components/tool/widgets/extractors.ts b/products/posthog_ai/frontend/components/tool/widgets/extractors.tsindex a28c39e22d2e..b4974fae4ebb 100644--- a/products/posthog_ai/frontend/components/tool/widgets/extractors.ts+++ b/products/posthog_ai/frontend/components/tool/widgets/extractors.ts@@ -17,6 +17,7 @@ import { RecordingUniversalFilters } from '~/types'import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'import { parseExecCall, parseExecCommand } from '../posthogExecDisplay'+import { getAllText } from '../toolContentUtils'/*** Shared shape extractors for the sandbox MCP tool renderer widgets. Each turns a flattened@@ -49,21 +50,38 @@ function parseToonRecord(text: string): Record<string, unknown> | null {}}+function unwrapToolOutput(rawOutput: unknown): unknown {+ const envelope = asRecord(rawOutput)+ if (envelope?.isError === true) {+ return null+ }+ const structuredContent = asRecord(envelope?.structuredContent)+ if (structuredContent) {+ return structuredContent+ }+ // Entity payloads can also have a content array, so only unwrap the MCP envelope's top-level shape.+ if (+ !envelope ||+ !Object.keys(envelope).every((key) => ['content', 'structuredContent', 'isError', '_meta'].includes(key))+ ) {+ return rawOutput+ }+ return Array.isArray(envelope.content) ? getAllText(envelope.content).join('\n') : rawOutput+}+/**- * Best-effort record from a tool call's `rawOutput`. Objects pass through; strings are parsed per the- * exec `call` output contract: `--json` means the server responded with `JSON.stringify`, otherwise- * TOON (`services/mcp/src/lib/response.ts`). The off-order format is still tried as a fallback, and- * anything unparseable (or empty) resolves to null so the widget falls back to the generic card.+ * Prefer structured content because the text can be an optimized summary without the entity fields.*/export function parseToolOutputRecord(message: ToolCallMessage): Record<string, unknown> | null {- const direct = asRecord(message.rawOutput)+ const rawOutput = unwrapToolOutput(message.rawOutput)+ const direct = asRecord(rawOutput)if (direct) {return direct}- if (typeof message.rawOutput !== 'string') {+ if (typeof rawOutput !== 'string') {return null}- const text = message.rawOutput.trim()+ const text = rawOutput.trim()if (!text) {return null}