: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(mcp): load query visualizations through exec (#116069)
Georgiy Tarasov913e2f6fc88f
diff --git a/services/mcp/src/ui-apps/apps/render-ui-data.ts b/services/mcp/src/ui-apps/apps/render-ui-data.tsnew file mode 100644index 000000000000..7d79259970b1--- /dev/null+++ b/services/mcp/src/ui-apps/apps/render-ui-data.ts@@ -0,0 +1,32 @@+import type { App } from '@modelcontextprotocol/ext-apps'++import type { UiAppKey } from '../../resources/ui-apps.generated'+import { APP_DATA_META_KEY } from '../types'++interface RenderUiDataResult {+ structuredContent?: unknown+ isError?: boolean+}++export async function loadRenderUiData(+ app: Pick<App, 'callServerTool'>,+ toolName: string,+ input: Record<string, unknown>,+ appKey: UiAppKey+): Promise<RenderUiDataResult> {+ const useExec = appKey === 'query-results'+ const result = await app.callServerTool(+ useExec+ ? { name: 'exec', arguments: { command: `call --json ${toolName} ${JSON.stringify(input)}` } }+ : { name: toolName, arguments: input }+ )+ if (!useExec || result.isError) {+ return result+ }+ const data = result.structuredContent ?? result._meta?.[APP_DATA_META_KEY]+ if (data !== undefined) {+ return { structuredContent: data }+ }+ const text = result.content.find((item) => item.type === 'text')?.text+ return { structuredContent: text === undefined ? undefined : JSON.parse(text) }+}diff --git a/services/mcp/src/ui-apps/apps/render-ui.tsx b/services/mcp/src/ui-apps/apps/render-ui.tsxindex 4c92d2c5e27d..c77153fd147f 100644--- a/services/mcp/src/ui-apps/apps/render-ui.tsx+++ b/services/mcp/src/ui-apps/apps/render-ui.tsx@@ -10,6 +10,7 @@ import { AppErrorState } from '../components/AppErrorState'import { AppLoadingState } from '../components/AppLoadingState'import { AppWrapper } from '../components/AppWrapper'import { RENDER_DISPATCH } from '../generated/render-dispatch.generated'+import { loadRenderUiData } from './render-ui-data'/*** Envelope emitted by the `render-ui` server tool. It carries the tool to render@@ -46,6 +47,7 @@ function RenderUiContent({// Key the fetch on serialized values, not `envelope` identity — a parent// re-render with a fresh-but-equal envelope object must not refetch.const toolName = envelope.tool_name+ const appKey = envelope.app_keyconst toolInputJson = JSON.stringify(envelope.tool_input ?? {})useEffect(() => {capture('mcp_ui_app_render_requested', { rendered_tool_name: toolName, app_key: envelope.app_key })@@ -58,7 +60,7 @@ function RenderUiContent({let cancelled = falsesetData(null)setError(null)- app.callServerTool({ name: toolName, arguments: JSON.parse(toolInputJson) as Record<string, unknown> })+ loadRenderUiData(app, toolName, JSON.parse(toolInputJson) as Record<string, unknown>, appKey).then((result) => {if (cancelled) {return@@ -77,7 +79,7 @@ function RenderUiContent({return () => {cancelled = true}- }, [app, toolName, toolInputJson])+ }, [app, toolName, toolInputJson, appKey])const render = RENDER_DISPATCH[envelope.app_key]const failureReason = render ? error?.reason : 'no_visualization'diff --git a/services/mcp/tests/unit/render-ui-data.test.ts b/services/mcp/tests/unit/render-ui-data.test.tsnew file mode 100644index 000000000000..ba4da55f0aae--- /dev/null+++ b/services/mcp/tests/unit/render-ui-data.test.ts@@ -0,0 +1,59 @@+import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'+import { describe, expect, it, vi } from 'vitest'++import { loadRenderUiData } from '@/ui-apps/apps/render-ui-data'+import { APP_DATA_META_KEY } from '@/ui-apps/types'++describe('render-ui data loading', () => {+ it.each(['query-trends', 'insight-query'])(+ 'loads %s through the advertised exec tool as JSON',+ async (toolName) => {+ const data = { results: [{ data: [3] }] }+ const input = { event: 'a "quoted" event\nwith a newline' }+ const callServerTool = vi+ .fn()+ .mockResolvedValue({ content: [{ type: 'text', text: JSON.stringify(data) }] })++ expect(await loadRenderUiData({ callServerTool }, toolName, input, 'query-results')).toEqual({+ structuredContent: data,+ })+ expect(callServerTool).toHaveBeenCalledExactlyOnceWith({+ name: 'exec',+ arguments: { command: `call --json ${toolName} ${JSON.stringify(input)}` },+ })+ }+ )++ it.each<CallToolResult>([+ { content: [{ type: 'text', text: 'See structured content' }], structuredContent: { results: [] } },+ { content: [{ type: 'text', text: 'See app data' }], _meta: { [APP_DATA_META_KEY]: { results: [] } } },+ ])('accepts structured query results from inline app hosts: %j', async (result) => {+ const callServerTool = vi.fn().mockResolvedValue(result)+ expect(await loadRenderUiData({ callServerTool }, 'query-trends', {}, 'query-results')).toEqual({+ structuredContent: { results: [] },+ })+ })++ it('returns tool errors without trying to parse them as JSON', async () => {+ const result = { isError: true, content: [{ type: 'text', text: 'Query access denied' }] }+ const callServerTool = vi.fn().mockResolvedValue(result)+ expect(await loadRenderUiData({ callServerTool }, 'query-trends', {}, 'query-results')).toBe(result)+ })++ it('rejects non-JSON success text instead of treating it as chart data', async () => {+ const callServerTool = vi.fn().mockResolvedValue({ content: [{ type: 'text', text: 'Not JSON' }] })+ await expect(loadRenderUiData({ callServerTool }, 'query-trends', {}, 'query-results')).rejects.toThrow(+ SyntaxError+ )+ })++ it('keeps direct tool calls for other visualizations', async () => {+ const result = { structuredContent: { id: 'example' }, content: [] }+ const callServerTool = vi.fn().mockResolvedValue(result)+ expect(await loadRenderUiData({ callServerTool }, 'survey-get', { surveyId: 'example' }, 'survey')).toBe(result)+ expect(callServerTool).toHaveBeenCalledExactlyOnceWith({+ name: 'survey-get',+ arguments: { surveyId: 'example' },+ })+ })+})