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(logs): render logs tool calls as cards in PostHog AI (#96733)

Frank Hamandf417c007a5c1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 999b3d2437c8..f3a2ca7004f1 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8188,6 +8188,14 @@ snapshots:
hash: v1.k794b7964.4d75bf1926fdf1fdebad47ad4fd07f4035634bca040c9aeb0fd58e18adaa4fb4.3sBwvXuvVbhUPQY3T9JG4G3LwQL6Tvv_a22YYhQJifo
scenes-app-marketing-analytics-cell-actions--source-cell-action-unmapped--light:
hash: v1.k794b7964.c15b997111d34fb17ad2dd192b97c01d0a7ab3a320c5edf9a3e20b0b63a4ff9b.UHxcXJdZkFGXRnzIMFWO99QMD_gZm0V47g8f1j4OFS0
+ scenes-app-max-ai-logs-query-tool--no-matches--dark:
+ hash: v1.k794b7964.223044926f42a8e3a756412aa03a691dd04f5a8d8654db7a325f2260917b9430.UgpMyQFFGVINJikUpS89VD4EG2z7fj76DMrOffodGGI
+ scenes-app-max-ai-logs-query-tool--no-matches--light:
+ hash: v1.k794b7964.3e04c92daba0b5f213ecd35cd4e5a5eb797b24dc69a9e3c3c0bd7b27a4cef9f9.wquRkSMZF2Iud1apiDPYDzUaoxLYDHzpJhwkwU2B3ns
+ scenes-app-max-ai-logs-query-tool--with-rows--dark:
+ hash: v1.k794b7964.223044926f42a8e3a756412aa03a691dd04f5a8d8654db7a325f2260917b9430.cKHx53lUFCmAJnbAXBckDzQnwcxJ_hxsH-GgKgR-3Qg
+ scenes-app-max-ai-logs-query-tool--with-rows--light:
+ hash: v1.k794b7964.3e04c92daba0b5f213ecd35cd4e5a5eb797b24dc69a9e3c3c0bd7b27a4cef9f9.14ZWrizkHZvyik-SHsQC-lHUDhm-wvlxz25f_9eHfgc
scenes-app-max-ai-replay-vision-scan-widget--finished--dark:
hash: v1.k794b7964.1223f99370d58d32715cc85f7dcee08b5edf77d9b93095b81474c76eb3138f2f.GJOY2COZjRyTv8DY54QNd7uUJ4H7DxTz-8TdiWq3yc8
scenes-app-max-ai-replay-vision-scan-widget--finished--light:
diff --git a/frontend/src/scenes/bootApp.ts b/frontend/src/scenes/bootApp.ts
index 4153ac94e7c4..f4eb7b901159 100644
--- a/frontend/src/scenes/bootApp.ts
+++ b/frontend/src/scenes/bootApp.ts
@@ -1,5 +1,7 @@
import { registerNotebookLinkDrag } from 'scenes/notebooks/AddToNotebook/registerNotebookLinkDrag'
+import { registerLogsToolRenderers } from 'products/logs/frontend/agentTools/registerLogsToolRenderers'
+
import { initKea } from '../initKea'
import { loadPostHogJS } from '../loadPostHogJS'
@@ -29,6 +31,9 @@ export function bootApp(): void {
// Link resolves its drag-to-notebook behavior through a seam so bundles without
// notebooks (toolbar, exporter) don't ship them; the app opts in here
registerNotebookLinkDrag()
+ // A logs tool card must resolve in any thread, including one opened before the lazy Logs
+ // scene has loaded, so the app claims the logs tool names here instead of that scene
+ registerLogsToolRenderers()
const idle =
typeof window.requestIdleCallback === 'function'
diff --git a/products/logs/frontend/agentTools/LogsQueryToolWidget.stories.tsx b/products/logs/frontend/agentTools/LogsQueryToolWidget.stories.tsx
new file mode 100644
index 000000000000..b469cfdde2a3
--- /dev/null
+++ b/products/logs/frontend/agentTools/LogsQueryToolWidget.stories.tsx
@@ -0,0 +1,54 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import type { ToolCallMessage } from 'products/posthog_ai/frontend/api/types'
+
+import { LogsQueryToolWidget } from './LogsQueryToolWidget'
+
+const meta: Meta<typeof LogsQueryToolWidget> = {
+ title: 'Scenes-App/Max AI/Logs query tool',
+ component: LogsQueryToolWidget,
+ parameters: {
+ layout: 'padded',
+ testOptions: { waitForLoadersToDisappear: false },
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof LogsQueryToolWidget>
+
+function message(results: Record<string, unknown>[]): ToolCallMessage {
+ return {
+ id: 'call-1',
+ resolvedKey: 'query-logs',
+ rawServerName: 'posthog',
+ rawToolName: 'exec',
+ rawInput: {},
+ innerInput: {
+ query: {
+ serviceNames: ['api-gateway'],
+ severityLevels: ['warn', 'error'],
+ dateRange: { date_from: '-1h' },
+ },
+ },
+ rawOutput: { results },
+ content: [],
+ status: 'completed',
+ }
+}
+
+const ROWS: Record<string, unknown>[] = [
+ { severity_text: 'error', body: 'upstream connect timeout after 5000ms', timestamp: '2026-09-08T10:00:03Z' },
+ { severity_text: 'warn', body: 'retry 2/3 for GET /v1/orders', timestamp: '2026-09-08T10:00:02Z' },
+ { severity_text: 'error', body: 'circuit breaker open for checkout', timestamp: '2026-09-08T10:00:01Z' },
+ { severity_text: 'info', body: 'request served in 12ms', timestamp: '2026-09-08T10:00:00Z' },
+]
+
+export const WithRows: Story = {
+ render: () => <LogsQueryToolWidget message={message(ROWS)} isLastInGroup displayName="Query logs" turnComplete />,
+ name: 'Completed with rows',
+}
+
+export const NoMatches: Story = {
+ render: () => <LogsQueryToolWidget message={message([])} isLastInGroup displayName="Query logs" turnComplete />,
+ name: 'No matching logs',
+}
diff --git a/products/logs/frontend/agentTools/LogsQueryToolWidget.tsx b/products/logs/frontend/agentTools/LogsQueryToolWidget.tsx
new file mode 100644
index 000000000000..00e07a3422eb
--- /dev/null
+++ b/products/logs/frontend/agentTools/LogsQueryToolWidget.tsx
@@ -0,0 +1,65 @@
+import { dayjs } from 'lib/dayjs'
+
+import { LogMessage } from '~/queries/schema/schema-general'
+
+import { GenericMcpToolRenderer, ToolActivity } from 'products/posthog_ai/frontend/api/tools'
+import type { ToolRendererProps } from 'products/posthog_ai/frontend/api/tools'
+
+import { LogTag } from '../components/LogTag'
+import { describeLogsQuery, extractLogRows, LogRowSummary } from './logsQueryToolOutput'
+
+// The thread stays scannable, so the body lists a bounded window and names the remainder.
+const MAX_ROWS = 15
+
+function formatTimestamp(timestamp: string): string {
+ const parsed = dayjs(timestamp)
+ return parsed.isValid() ? parsed.format('MMM D HH:mm:ss') : timestamp
+}
+
+function LogRowsBody({ rows }: { rows: LogRowSummary[] }): JSX.Element {
+ if (rows.length === 0) {
+ return <div className="text-muted">No logs matched this query.</div>
+ }
+
+ const shown = rows.slice(0, MAX_ROWS)
+ return (
+ <div className="flex flex-col gap-1">
+ {shown.map((row, index) => (
+ <div key={index} className="flex items-baseline gap-2">
+ <LogTag level={row.severityText as LogMessage['severity_text']} />
+ <span className="text-muted text-xs font-mono shrink-0">{formatTimestamp(row.timestamp)}</span>
+ <span className="text-xs font-mono truncate flex-1">{row.body}</span>
+ </div>
+ ))}
+ {rows.length > MAX_ROWS && (
+ <div className="text-muted text-xs">+{rows.length - MAX_ROWS} more not shown</div>
+ )}
+ </div>
+ )
+}
+
+/**
+ * Result card for the `query-logs` tool: renders the returned log rows as a compact, severity-tagged
+ * list in the collapsible body. Falls back to the generic card for a pending call or an output with no
+ * `results` array.
+ */
+export function LogsQueryToolWidget(props: ToolRendererProps): JSX.Element {
+ const { message, icon, displayName, turnComplete, turnCancelled } = props
+ const rows = message.status === 'completed' ? extractLogRows(message) : null
+
+ if (!rows) {
+ return <GenericMcpToolRenderer {...props} />
+ }
+
+ return (
+ <ToolActivity
+ message={message}
+ icon={icon}
+ title={displayName ?? 'Query logs'}
+ subtitle={describeLogsQuery(message)}
+ body={<LogRowsBody rows={rows} />}
+ turnComplete={turnComplete}
+ turnCancelled={turnCancelled}
+ />
+ )
+}
diff --git a/products/logs/frontend/agentTools/logsQueryToolOutput.test.ts b/products/logs/frontend/agentTools/logsQueryToolOutput.test.ts
new file mode 100644
index 000000000000..c86db57f4859
--- /dev/null
+++ b/products/logs/frontend/agentTools/logsQueryToolOutput.test.ts
@@ -0,0 +1,79 @@
+import type { ToolCallMessage } from 'products/posthog_ai/frontend/api/types'
+
+import { describeLogsQuery, extractLogRows } from './logsQueryToolOutput'
+
+function toolMessage(rawOutput: unknown, innerInput?: Record<string, unknown>): ToolCallMessage {
+ return {
+ id: 'call-1',
+ resolvedKey: 'query-logs',
+ rawServerName: 'posthog',
+ rawToolName: 'exec',
+ rawInput: {},
+ innerInput,
+ rawOutput,
+ content: [],
+ status: 'completed',
+ }
+}
+
+describe('logsQueryToolOutput', () => {
+ describe('extractLogRows', () => {
+ it('maps returned rows to severity, body, and timestamp', () => {
+ const rows = extractLogRows(
+ toolMessage({
+ results: [
+ { severity_text: 'error', body: 'connection refused', timestamp: '2026-09-08T10:00:00Z' },
+ { severity_text: 'info', body: 'request served', timestamp: '2026-09-08T10:00:01Z' },
+ ],
+ })
+ )
+
+ expect(rows).toEqual([
+ { severityText: 'error', body: 'connection refused', timestamp: '2026-09-08T10:00:00Z' },
+ { severityText: 'info', body: 'request served', timestamp: '2026-09-08T10:00:01Z' },
+ ])
+ })
+
+ it('returns an empty array when the query matched no rows', () => {
+ expect(extractLogRows(toolMessage({ results: [] }))).toEqual([])
+ })
+
+ it('returns null when the output has no results array', () => {
+ expect(extractLogRows(toolMessage({ count: 3 }))).toBeNull()
+ expect(extractLogRows(toolMessage({ results: 'nope' }))).toBeNull()
+ })
+
+ it('defaults missing row fields to empty strings', () => {
+ const rows = extractLogRows(toolMessage({ results: [{ severity_text: 'warn' }] }))
+ expect(rows).toEqual([{ severityText: 'warn', body: '', timestamp: '' }])
+ })
+ })
+
+ describe('describeLogsQuery', () => {
+ it('summarizes services, severities, search, and date range from query args', () => {
+ const subtitle = describeLogsQuery(
+ toolMessage(
+ {},
+ {
+ query: {
+ serviceNames: ['api-gateway'],
+ severityLevels: ['error', 'fatal'],
+ searchTerm: 'timeout',
+ dateRange: { date_from: '-6h' },
+ },
+ }
+ )
+ )
+ expect(subtitle).toBe('api-gateway · error, fatal · search: timeout · -6h')
+ })
+
+ it('reads args that are not nested under a query object', () => {
+ expect(describeLogsQuery(toolMessage({}, { serviceNames: ['web'] }))).toBe('web')
+ })
+
+ it('returns undefined when there is nothing to describe', () => {
+ expect(describeLogsQuery(toolMessage({}, { query: {} }))).toBeUndefined()
+ expect(describeLogsQuery(toolMessage({}, undefined))).toBeUndefined()
+ })
+ })
+})
diff --git a/products/logs/frontend/agentTools/logsQueryToolOutput.ts b/products/logs/frontend/agentTools/logsQueryToolOutput.ts
new file mode 100644
index 000000000000..0eea30e85bae
--- /dev/null
+++ b/products/logs/frontend/agentTools/logsQueryToolOutput.ts
@@ -0,0 +1,63 @@
+import { asRecord, parseToolOutputRecord } from 'products/posthog_ai/frontend/api/tools'
+import type { ToolCallMessage } from 'products/posthog_ai/frontend/api/types'
+
+export interface LogRowSummary {
+ severityText: string
+ body: string
+ timestamp: string
+}
+
+function asString(value: unknown): string {
+ return typeof value === 'string' ? value : ''
+}
+
+function stringList(value: unknown): string[] {
+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []
+}
+
+/**
+ * Pull the returned log rows out of a `query-logs` tool result. Returns an array (possibly empty when
+ * the query matched nothing) or null when the output has no `results` array to render — in which case
+ * the widget falls back to the generic card rather than showing an empty rows panel.
+ */
+export function extractLogRows(message: ToolCallMessage): LogRowSummary[] | null {
+ const output = parseToolOutputRecord(message)
+ const results = output?.results
+ if (!Array.isArray(results)) {
+ return null
+ }
+ return results
+ .map((row) => asRecord(row))
+ .filter((row): row is Record<string, unknown> => row !== null)
+ .map((row) => ({
+ severityText: asString(row.severity_text),
+ body: asString(row.body),
+ timestamp: asString(row.timestamp),
+ }))
+}
+
+/**
+ * A one-line summary of what the query-logs call asked for, drawn from the tool's own input args, for
+ * the card subtitle. The args are raw agent JSON, so every field is read defensively.
+ */
+export function describeLogsQuery(message: ToolCallMessage): string | undefined {
+ const input = asRecord(message.innerInput)
+ const query = asRecord(input?.query) ?? input
+ if (!query) {
+ return undefined
+ }
+
+ const services = stringList(query.serviceNames)
+ const severities = stringList(query.severityLevels)
+ const search = asString(query.searchTerm)
+ const dateFrom = asString(asRecord(query.dateRange)?.date_from)
+
+ const parts = [
+ services.length > 0 ? services.join(', ') : '',
+ severities.length > 0 ? severities.join(', ') : '',
+ search ? `search: ${search}` : '',
+ dateFrom,
+ ].filter(Boolean)
+
+ return parts.length > 0 ? parts.join(' · ') : undefined
+}
diff --git a/products/logs/frontend/agentTools/registerLogsToolRenderers.test.ts b/products/logs/frontend/agentTools/registerLogsToolRenderers.test.ts
new file mode 100644
index 000000000000..0785dd114a55
--- /dev/null
+++ b/products/logs/frontend/agentTools/registerLogsToolRenderers.test.ts
@@ -0,0 +1,35 @@
+import fs from 'fs'
+import path from 'path'
+
+import { toolRegistry } from 'products/posthog_ai/frontend/api/tools'
+
+import { registerLogsToolRenderers } from './registerLogsToolRenderers'
+
+// Every logs tool the MCP codegen emits, so a tool added to the catalog without a registry entry
+// fails here instead of shipping the generic wrench card. Read off the generated file rather than
+// imported, to keep the services/mcp graph out of a frontend test.
+function generatedLogsToolNames(): string[] {
+ const generated = path.resolve(__dirname, '../../../../services/mcp/src/tools/generated/logs.ts')
+ const source = fs.readFileSync(generated, 'utf-8')
+ const names = [...source.matchAll(/name: '([a-z0-9-]+)'/g)].map((m) => m[1])
+ if (names.length === 0) {
+ throw new Error(`No tool names found in ${generated} — the codegen output moved or changed shape`)
+ }
+ return [...new Set(names)].sort()
+}
+
+describe('registerLogsToolRenderers', () => {
+ beforeAll(() => {
+ registerLogsToolRenderers()
+ })
+
+ it.each(generatedLogsToolNames())('claims %s in the shared registry', (key) => {
+ expect(toolRegistry.lookup(key)).not.toBeNull()
+ })
+
+ it('gives query-logs the custom card and leaves the rest on the generic one', () => {
+ expect(toolRegistry.lookup('query-logs')?.Renderer).not.toBeUndefined()
+ expect(toolRegistry.lookup('logs-patterns')?.Renderer).toBeUndefined()
+ expect(toolRegistry.lookup('logs-patterns')?.displayName).toEqual('Log patterns')
+ })
+})
diff --git a/products/logs/frontend/agentTools/registerLogsToolRenderers.tsx b/products/logs/frontend/agentTools/registerLogsToolRenderers.tsx
new file mode 100644
index 000000000000..4a266bba6bf7
--- /dev/null
+++ b/products/logs/frontend/agentTools/registerLogsToolRenderers.tsx
@@ -0,0 +1,62 @@
+import { IconBell, IconList, IconPulse, IconSearch, IconServer, IconStack, IconWarning } from '@posthog/icons'
+
+import { lazyWithRetry } from 'lib/utils/retryImport'
+
+import { registerToolRenderers, type ToolRegistryEntry } from 'products/posthog_ai/frontend/api/tools'
+
+// The card pulls its chunk on first use, so registering the whole family stays a strings-and-icons cost.
+const LogsQueryRenderer = lazyWithRetry(() =>
+ import('./LogsQueryToolWidget').then((m) => ({ default: m.LogsQueryToolWidget }))
+)
+
+// Friendly header (name + icon) for a logs tool call, without a bespoke result card. A no-Renderer
+// entry keeps its displayName and icon on the generic card (see `lookupToolRenderer`), so the whole
+// logs tool family reads as intentional logs actions in a thread even where only query-logs draws a
+// custom card. `requiresPostHogOrigin` so a user-installed MCP tool with a colliding bare name does
+// not borrow the logs branding.
+function labelled(keys: string[], displayName: string, icon: JSX.Element): ToolRegistryEntry[] {
+ return keys.map((key) => ({ key, displayName, icon, requiresPostHogOrigin: true }))
+}
+
+/**
+ * Claim the logs tool names in the shared registry. Called from `bootApp` rather than run at module
+ * load: a thread renders tool cards wherever it is opened, including an `/ai/{id}` link followed
+ * before the lazy Logs scene has ever loaded, so registering from the scene entrypoint would leave
+ * those calls on the generic wrench card.
+ */
+export function registerLogsToolRenderers(): void {
+ registerToolRenderers([
+ // The flagship: renders the returned log rows as a compact severity-tagged list.
+ {
+ key: 'query-logs',
+ displayName: 'Query logs',
+ icon: <IconSearch />,
+ Renderer: LogsQueryRenderer,
+ requiresPostHogOrigin: true,
+ },
+ ...labelled(['logs-services-create'], 'Logs services', <IconServer />),
+ ...labelled(['logs-patterns', 'logs-patterns-diff'], 'Log patterns', <IconStack />),
+ ...labelled(['logs-count', 'logs-count-ranges', 'logs-sparkline-query'], 'Count logs', <IconPulse />),
+ ...labelled(
+ ['logs-attributes-list', 'logs-attribute-values-list', 'logs-facet-values-create'],
+ 'Log attributes',
+ <IconList />
+ ),
+ ...labelled(['logs-anomalies-scan', 'logs-anomalies-series-bands'], 'Log anomalies', <IconWarning />),
+ ...labelled(
+ [
+ 'logs-alerts-list',
+ 'logs-alerts-retrieve',
+ 'logs-alerts-create',
+ 'logs-alerts-partial-update',
+ 'logs-alerts-destroy',
+ 'logs-alerts-simulate-create',
+ 'logs-alerts-events-list',
+ 'logs-alerts-destinations-create',
+ 'logs-alerts-destinations-delete-create',
+ ],
+ 'Log alert',
+ <IconBell />
+ ),
+ ])
+}
diff --git a/products/posthog_ai/frontend/api/tools.ts b/products/posthog_ai/frontend/api/tools.ts
index 0a06140bb9f0..ee76fc533cd6 100644
--- a/products/posthog_ai/frontend/api/tools.ts
+++ b/products/posthog_ai/frontend/api/tools.ts
@@ -6,6 +6,7 @@ export type {
ToolRegistry,
} from '../components/tool/toolRegistry'
export { getPermissionRequestToolInput, resolveToolCall } from '../utils/toolResolver'
+export { parseToolOutputRecord, asRecord } from '../components/tool/parseToolOutput'
export { GenericMcpToolRenderer } from '../components/tool/GenericMcpToolRenderer'
export { DataToolRow } from '../components/tool/DataToolRow'
export { ToolActivity } from '../components/tool/ToolActivity'
diff --git a/products/posthog_ai/frontend/components/tool/parseToolOutput.ts b/products/posthog_ai/frontend/components/tool/parseToolOutput.ts
new file mode 100644
index 000000000000..7acc0989e78c
--- /dev/null
+++ b/products/posthog_ai/frontend/components/tool/parseToolOutput.ts
@@ -0,0 +1,91 @@
+import { decode } from '@toon-format/toon'
+
+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
+
+import { parseExecCall, parseExecCommand } from './posthogExecDisplay'
+import { getAllText } from './toolContentUtils'
+
+/**
+ * Generic tool-output parsing, kept free of the entity-specific extractors so a product widget can
+ * parse a tool's result through the `api/tools` facade without pulling the recordings / error-tracking
+ * conversion deps that `widgets/extractors.ts` carries.
+ */
+
+export function asRecord(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null
+}
+
+function parseJsonRecord(text: string): Record<string, unknown> | null {
+ try {
+ return asRecord(JSON.parse(text))
+ } catch {
+ return null
+ }
+}
+
+function parseToonRecord(text: string): Record<string, unknown> | null {
+ // TOON decode is lenient — JSON text doesn't throw, it mangles into a garbage record — so
+ // anything that reads as JSON syntax must never reach it.
+ if (/^[[{]/.test(text)) {
+ return null
+ }
+ try {
+ return asRecord(decode(text))
+ } catch {
+ return 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 caller falls back to the generic card.
+ * An MCP result envelope is unwrapped first, preferring its structured content because the text can be
+ * an optimized summary without the entity fields.
+ */
+export function parseToolOutputRecord(message: ToolCallMessage): Record<string, unknown> | null {
+ const rawOutput = unwrapToolOutput(message.rawOutput)
+ const direct = asRecord(rawOutput)
+ if (direct) {
+ return direct
+ }
+ if (typeof rawOutput !== 'string') {
+ return null
+ }
+ const text = rawOutput.trim()
+ if (!text) {
+ return null
+ }
+ const command = typeof message.rawInput.command === 'string' ? message.rawInput.command : ''
+ const { verb, rest } = parseExecCommand(command)
+ const forceJson = verb === 'call' && parseExecCall(rest).forceJson
+ const attempts = forceJson ? [parseJsonRecord, parseToonRecord] : [parseToonRecord, parseJsonRecord]
+ for (const attempt of attempts) {
+ const record = attempt(text)
+ // decode('') and JSON '{}' both yield {}, which carries nothing a widget can render.
+ if (record && Object.keys(record).length > 0) {
+ return record
+ }
+ }
+ return null
+}
diff --git a/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsx
index 906c6a990059..d9cf813490ed 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsx
+++ b/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsx
@@ -7,8 +7,8 @@ import { urls } from 'scenes/urls'
import { MessageTemplate } from '../../../messages/MessageTemplate'
import { DataToolRow } from '../DataToolRow'
import { GenericMcpToolRenderer } from '../GenericMcpToolRenderer'
+import { parseToolOutputRecord } from '../parseToolOutput'
import type { ToolRendererProps } from '../toolRegistry'
-import { parseToolOutputRecord } from './extractors'
/** The notebook fields the widget renders, pulled from the REST payload. */
export interface NotebookExtraction {
diff --git a/products/posthog_ai/frontend/components/tool/widgets/extractors.ts b/products/posthog_ai/frontend/components/tool/widgets/extractors.ts
index b4974fae4ebb..a57ddfb90169 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/extractors.ts
+++ b/products/posthog_ai/frontend/components/tool/widgets/extractors.ts
@@ -1,5 +1,3 @@
-import { decode } from '@toon-format/toon'
-
import { recordingsQueryToUniversalFilters } from 'scenes/session-recordings/filters/recordingsQueryConversions'
import { MaxErrorTrackingSearchResponse } from '~/queries/schema/schema-assistant-error-tracking'
@@ -16,89 +14,14 @@ import { RecordingUniversalFilters } from '~/types'
import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
-import { parseExecCall, parseExecCommand } from '../posthogExecDisplay'
-import { getAllText } from '../toolContentUtils'
+import { asRecord, parseToolOutputRecord } from '../parseToolOutput'
/**
* Shared shape extractors for the sandbox MCP tool renderer widgets. Each turns a flattened
* `ToolCallMessage` (built by `runStreamLogic` from ACP frames) into the props the atomic
- * `messages/*` widgets expect.
+ * `messages/*` widgets expect. Generic output parsing lives in `../parseToolOutput`.
*/
-function asRecord(value: unknown): Record<string, unknown> | null {
- return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null
-}
-
-function parseJsonRecord(text: string): Record<string, unknown> | null {
- try {
- return asRecord(JSON.parse(text))
- } catch {
- return null
- }
-}
-
-function parseToonRecord(text: string): Record<string, unknown> | null {
- // TOON decode is lenient — JSON text doesn't throw, it mangles into a garbage record — so
- // anything that reads as JSON syntax must never reach it.
- if (/^[[{]/.test(text)) {
- return null
- }
- try {
- return asRecord(decode(text))
- } catch {
- return 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
-}
-
-/**
- * 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 rawOutput = unwrapToolOutput(message.rawOutput)
- const direct = asRecord(rawOutput)
- if (direct) {
- return direct
- }
- if (typeof rawOutput !== 'string') {
- return null
- }
- const text = rawOutput.trim()
- if (!text) {
- return null
- }
- const command = typeof message.rawInput.command === 'string' ? message.rawInput.command : ''
- const { verb, rest } = parseExecCommand(command)
- const forceJson = verb === 'call' && parseExecCall(rest).forceJson
- const attempts = forceJson ? [parseJsonRecord, parseToonRecord] : [parseToonRecord, parseJsonRecord]
- for (const attempt of attempts) {
- const record = attempt(text)
- // decode('') and JSON '{}' both yield {}, which carries nothing a widget can render.
- if (record && Object.keys(record).length > 0) {
- return record
- }
- }
- return null
-}
-
function asString(value: unknown): string | undefined {
return typeof value === 'string' ? value : undefined
}