: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): render query results through render-ui (#70482)
Georgiy Tarasov5269933266c0
diff --git a/.agents/skills/implementing-mcp-ui-apps/SKILL.md b/.agents/skills/implementing-mcp-ui-apps/SKILL.mdindex b419d4fc07de..58d52ae353d3 100644--- a/.agents/skills/implementing-mcp-ui-apps/SKILL.md+++ b/.agents/skills/implementing-mcp-ui-apps/SKILL.md@@ -265,7 +265,9 @@ ui_apps:For apps that need fully custom logic (e.g. `debug.tsx`, `query-results.tsx`).The generator does NOT create an entry point — you maintain it manually at-`services/mcp/src/ui-apps/apps/{key}.tsx`. Only the registry entry is generated.+`services/mcp/src/ui-apps/apps/{key}.tsx`. The registry entry is always generated.+If the custom app exposes a reusable view component, an optional `render_ui`+configuration also adds it to the `render-ui` umbrella tool.**Required fields:**@@ -275,6 +277,15 @@ The generator does NOT create an entry point — you maintain it manually at| `app_name` | Display name. Required because there's no convention to derive it from (custom apps may not follow naming patterns). || `description` | Short description. Required for the same reason. |+**Optional `render_ui` fields:**++| Field | Description |+| ------------------ | --------------------------------------------------------------------------------- |+| `component_import` | Import path for the reusable view component, relative to `src/ui-apps/generated`. |+| `view_component` | React component name that renders the tool result. |+| `view_prop` | Prop name that receives the tool result. |+| `data_type` | TypeScript type for the tool result. Omit when the component accepts `unknown`. |+**Example:**```yaml@@ -283,6 +294,10 @@ ui_apps:type: customapp_name: Query Resultsdescription: Interactive visualization for PostHog query results+ render_ui:+ component_import: ../components/Component+ view_component: Component+ view_prop: data```### Where the schemas live@@ -295,9 +310,9 @@ To add a new field to an app type:1. Add it to the relevant Zod schema (`DetailUiAppSchema`, `ListUiAppSchema`, or `CustomUiAppSchema`)with `.optional()` if it has a default-2. Add it to the matching `Resolved*` interface (`ResolvedDetailUiApp` or `ResolvedListUiApp`)-3. Add the default derivation in `resolveDetailApp()` or `resolveListApp()` in `generate-ui-apps.ts`-4. Use the resolved value in `generateDetailApp()` or `generateListApp()`+2. Add it to the matching `Resolved*` interface (`ResolvedDetailUiApp`, `ResolvedListUiApp`, or `ResolvedCustomUiApp`)+3. Add the default derivation in `resolveDetailApp()`, `resolveListApp()`, or `resolveCustomApp()` in `generate-ui-apps.ts`+4. Use the resolved value in the entry-point or dispatch generatorAll schemas use `.strict()` — unknown keys are rejected at build time, catching typos.diff --git a/services/mcp/CONTRIBUTING.md b/services/mcp/CONTRIBUTING.mdindex 77edde64c4ac..63dc233574a8 100644--- a/services/mcp/CONTRIBUTING.md+++ b/services/mcp/CONTRIBUTING.md@@ -304,7 +304,7 @@ pnpm run build # builds all appsFor apps that need fully custom logic (like `debug.tsx` or `query-results.tsx`):-1. **Add a `type: custom` entry** in the YAML to register the URI and app name:+1. **Add a `type: custom` entry** in the YAML to register the URI and app name. If the app has a reusable view component, add `render_ui` so the umbrella tool can render it too:```yamlui_apps:@@ -312,6 +312,10 @@ For apps that need fully custom logic (like `debug.tsx` or `query-results.tsx`):type: customapp_name: My Custom Appdescription: Custom visualization for X+ render_ui:+ component_import: ../components/MyCustomView+ view_component: MyCustomView+ view_prop: data```2. **Create the entry point** manually at `src/ui-apps/apps/my-custom-app.tsx`.diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex 88ccd5ec7db3..ca17ab3ef950 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -16,6 +16,10 @@ ui_apps:type: customapp_name: Query Resultsdescription: Interactive visualization for PostHog query results+ render_ui:+ component_import: ../components/Component+ view_component: Component+ view_prop: datarender-ui:type: customapp_name: PostHog Render UIdiff --git a/services/mcp/scripts/generate-ui-apps.ts b/services/mcp/scripts/generate-ui-apps.tsindex ad1ad97f287b..d4bfaa22e0fe 100644--- a/services/mcp/scripts/generate-ui-apps.ts+++ b/services/mcp/scripts/generate-ui-apps.ts@@ -24,6 +24,7 @@ import { MCP_ROOT_DIR, ROOT_DIR } from './utils'import {type CategoryConfig,CategoryConfigSchema,+ type ResolvedCustomUiApp,type ResolvedDetailUiApp,type ResolvedListUiApp,type UiAppConfig,@@ -115,6 +116,15 @@ function resolveListApp(}}+function resolveCustomApp(raw: Extract<UiAppConfig, { type: 'custom' }>): ResolvedCustomUiApp {+ return {+ type: 'custom',+ app_name: raw.app_name,+ description: raw.description,+ ...(raw.render_ui ? { render_ui: raw.render_ui } : {}),+ }+}+// ------------------------------------------------------------------// Entry point generators// ------------------------------------------------------------------@@ -230,12 +240,17 @@ if (container) {type DispatchApp =| { appKey: string; type: 'detail'; config: ResolvedDetailUiApp }| { appKey: string; type: 'list'; config: ResolvedListUiApp }+ | {+ appKey: string+ type: 'custom'+ config: ResolvedCustomUiApp & { render_ui: NonNullable<ResolvedCustomUiApp['render_ui']> }+ }/*** Generates the dispatch module consumed by the `render-ui` umbrella app. It maps- * each detail/list app key to a render function so `render-ui` can fetch a tool- * result and mount the matching view. Custom apps are excluded — they have no- * convention view component to dispatch to.+ * each app key with a reusable view to a render function so `render-ui` can fetch+ * a tool result and mount the matching view. Custom apps opt in by declaring+ * `render_ui` because their entry points have no convention view component.*/function generateDispatchModule(apps: DispatchApp[]): string {// Merge named imports per component_import path (multiple apps from the same@@ -250,10 +265,16 @@ function generateDispatchModule(apps: DispatchApp[]): string {if (app.type === 'detail') {addImport(app.config.component_import, `type ${app.config.data_type}`)addImport(app.config.component_import, app.config.view_component)- } else {+ } else if (app.type === 'list') {addImport(app.config.component_import, `type ${app.config.item_data_type}`)addImport(app.config.component_import, `type ${app.config.list_data_type}`)addImport(app.config.component_import, app.config.view_component)+ } else {+ const { component_import, data_type, view_component } = app.config.render_ui+ if (data_type) {+ addImport(component_import, `type ${data_type}`)+ }+ addImport(component_import, view_component)}}@@ -278,6 +299,11 @@ function generateDispatchModule(apps: DispatchApp[]): string {}return ` '${app.appKey}': ({ data }) => <${view_component} ${view_prop}={data as ${data_type}} />,`}+ if (app.type === 'custom') {+ const { data_type, view_component, view_prop } = app.config.render_ui+ const dataExpression = data_type ? `data as ${data_type}` : 'data'+ return ` '${app.appKey}': ({ data }) => <${view_component} ${view_prop}={${dataExpression}} />,`+ }const pascalName = kebabToPascal(app.appKey)return ` '${app.appKey}': ({ data, app }) => <${pascalName}Content data={data as ${app.config.list_data_type}} app={app} />,`})@@ -353,8 +379,8 @@ ${uriMapEntries},}/**- * App keys with a generated detail/list view that the \`render-ui\` umbrella tool- * can render. Excludes custom apps, which have no convention view component.+ * App keys with a reusable view that the \`render-ui\` umbrella tool can render.+ * Custom apps are included only when they explicitly configure \`render_ui\`.*/export const DISPATCHABLE_APP_KEYS: UiAppKey[] = [${dispatchableEntries},@@ -464,6 +490,14 @@ function main(): void {})} else {// type: custom — entry point is handwritten, appDir matches appKey directly+ const resolved = resolveCustomApp(appConfig)+ if (resolved.render_ui) {+ dispatchApps.push({+ appKey,+ type: 'custom',+ config: { ...resolved, render_ui: resolved.render_ui },+ })+ }registryEntries.push({appKey,appDir: appKey,@@ -551,6 +585,7 @@ export {generateListApp,generateRegistry,kebabToPascal,+ resolveCustomApp,resolveDetailApp,resolveListApp,toConstName,diff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.tsindex 58b7c53b10d6..d80fd209c641 100644--- a/services/mcp/scripts/yaml-config-schema.ts+++ b/services/mcp/scripts/yaml-config-schema.ts@@ -348,7 +348,7 @@ const ListUiAppSchema = z.strict()/**- * Custom UI app — handwritten entry point, only gets a registry entry.+ * Custom UI app — handwritten entry point with optional render-ui dispatch.** Use for apps that need fully custom logic (e.g. debug.tsx, query-results.tsx).* The generator does NOT create an entry point file — you maintain it manually at@@ -362,6 +362,20 @@ const CustomUiAppSchema = zapp_name: z.string(),/** Short description for the MCP resource. Required for custom apps. */description: z.string(),+ /** Reusable view component that lets the render-ui umbrella app mount this custom app. */+ render_ui: z+ .object({+ /** Import path for the reusable view component, relative to src/ui-apps/generated. */+ component_import: z.string(),+ /** React component name that renders the tool result. */+ view_component: z.string(),+ /** Prop name that receives the tool result. */+ view_prop: z.string(),+ /** TypeScript type for the tool result. Omit when the component accepts unknown. */+ data_type: z.string().optional(),+ })+ .strict()+ .optional(),}).strict()@@ -397,6 +411,19 @@ export interface ResolvedListUiApp {view_component: string}+/** Custom config, including an optional reusable view for render-ui dispatch. */+export interface ResolvedCustomUiApp {+ type: 'custom'+ app_name: string+ description: string+ render_ui?: {+ component_import: string+ view_component: string+ view_prop: string+ data_type?: string+ }+}+/*** Some MCP clients (notably Cursor) enforce a 60-character combined limit on* server_name + tool_name. With server name "posthog" (7 chars), tool namesdiff --git a/services/mcp/src/resources/ui-apps.generated.ts b/services/mcp/src/resources/ui-apps.generated.tsindex fedc5a383cda..869db2aad271 100644--- a/services/mcp/src/resources/ui-apps.generated.ts+++ b/services/mcp/src/resources/ui-apps.generated.ts@@ -100,8 +100,8 @@ export const URI_MAP: Record<UiAppKey, string> = {}/**- * App keys with a generated detail/list view that the `render-ui` umbrella tool- * can render. Excludes custom apps, which have no convention view component.+ * App keys with a reusable view that the `render-ui` umbrella tool can render.+ * Custom apps are included only when they explicitly configure `render_ui`.*/export const DISPATCHABLE_APP_KEYS: UiAppKey[] = ['action',@@ -121,6 +121,7 @@ export const DISPATCHABLE_APP_KEYS: UiAppKey[] = ['insight-actors','invite-email-preview','llm-costs',+ 'query-results','session-recording','session-summary','survey',diff --git a/services/mcp/src/tools/render-ui.ts b/services/mcp/src/tools/render-ui.tsindex 487741cbca16..7096164d799b 100644--- a/services/mcp/src/tools/render-ui.ts+++ b/services/mcp/src/tools/render-ui.ts@@ -29,7 +29,7 @@ function toDispatchableAppKey(tool: Tool<ZodObjectAny>): UiAppKey | undefined {}/**- * Names of the tools `render-ui` can render — those whose UI app has a generated view.+ * Names of the tools `render-ui` can render — those whose UI app exposes a reusable view.* Restricted to read-only tools: `render-ui` is annotated read-only, so it must not be a* back door for dispatching state-changing tools (e.g. `survey-launch`, `workflows-create`).*/diff --git a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsxindex aff7616603ee..044755e60a22 100644--- a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx+++ b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx@@ -56,6 +56,7 @@ import {} from 'products/workflows/mcp/apps'import type { UiAppKey } from '../../resources/ui-apps.generated'+import { Component } from '../components/Component'export interface RenderDispatchProps {data: unknown@@ -387,6 +388,7 @@ export const RENDER_DISPATCH: Partial<Record<UiAppKey, (props: RenderDispatchPro),'invite-email-preview': ({ data }) => <InviteEmailPreviewView data={data as InviteEmailPreviewData} />,'llm-costs': ({ data }) => <LLMCostsView data={data as LLMCostsData} />,+ 'query-results': ({ data }) => <Component data={data} />,'session-recording': ({ data }) => <SessionRecordingView recording={data as SessionRecordingData} />,'session-summary': ({ data }) => <SessionSummaryView data={data as SessionSummaryData} />,survey: ({ data }) => <SurveyView survey={data as SurveyData} />,diff --git a/services/mcp/tests/unit/render-ui.test.ts b/services/mcp/tests/unit/render-ui.test.tsindex b417d8ce267a..84c23d126e6d 100644--- a/services/mcp/tests/unit/render-ui.test.ts+++ b/services/mcp/tests/unit/render-ui.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest'import { z } from 'zod'+import { toMcpInputSchema } from '@/hono/tool-catalog'import { isToolCallPayload, type ToolResultPayload } from '@/lib/build-tool-result'import { RENDER_UI_RESOURCE_URI, URI_MAP } from '@/resources/ui-apps.generated'import { createRenderUiTool, getRenderableToolNames, RENDER_UI_TOOL_NAME } from '@/tools/render-ui'@@ -23,14 +24,18 @@ function makeTool(name: string, resourceUri?: string): Tool<ZodObjectAny> {}}-// A detail app (`survey`) is dispatchable; a custom app (`debug`) is not.+// Generated and opted-in custom apps are dispatchable; other custom apps are not.const surveyTool = makeTool('survey-get', URI_MAP['survey'])+const queryTrendsTool = makeTool('query-trends', URI_MAP['query-results'])const debugTool = makeTool('debug-tool', URI_MAP['debug'])const plainTool = makeTool('plain-tool')describe('render-ui tool', () => {- it('only counts tools whose UI app has a generated view as renderable', () => {- expect(getRenderableToolNames([surveyTool, debugTool, plainTool])).toEqual(['survey-get'])+ it('only counts tools whose UI app has a reusable view as renderable', () => {+ expect(getRenderableToolNames([surveyTool, queryTrendsTool, debugTool, plainTool])).toEqual([+ 'survey-get',+ 'query-trends',+ ])})it('excludes non-read-only tools so render-ui cannot dispatch mutating tools', () => {@@ -44,16 +49,49 @@ describe('render-ui tool', () => {})it('restricts tool_name to the renderable tools', () => {- const tool = createRenderUiTool([surveyTool, debugTool, plainTool], mockContext)+ const tool = createRenderUiTool([surveyTool, queryTrendsTool, debugTool, plainTool], mockContext)expect(tool).not.toBeNull()const schema = tool!.schemaexpect(schema.safeParse({ tool_name: 'survey-get', tool_input: { surveyId: 'abc' } }).success).toBe(true)- // Non-UI and custom-app tools are not valid enum members.+ expect(schema.safeParse({ tool_name: 'query-trends', tool_input: { kind: 'TrendsQuery' } }).success).toBe(true)+ // Non-UI and non-dispatchable custom-app tools are not valid enum members.expect(schema.safeParse({ tool_name: 'plain-tool' }).success).toBe(false)expect(schema.safeParse({ tool_name: 'debug-tool' }).success).toBe(false)})+ it('advertises the render-ui input schema', () => {+ const tool = createRenderUiTool([surveyTool, queryTrendsTool, debugTool, plainTool], mockContext)+ expect(tool).not.toBeNull()++ expect(toMcpInputSchema(tool!.schema)).toMatchInlineSnapshot(`+ {+ "properties": {+ "tool_input": {+ "additionalProperties": {},+ "description": "The generated input for that tool. The UI app uses it to fetch and render the visualization.",+ "propertyNames": {+ "type": "string",+ },+ "type": "object",+ },+ "tool_name": {+ "description": "A tool that has a UI app — its visualization will be rendered for the user.",+ "enum": [+ "survey-get",+ "query-trends",+ ],+ "type": "string",+ },+ },+ "required": [+ "tool_name",+ ],+ "type": "object",+ }+ `)+ })+it('emits a render directive payload with the envelope and render-ui resourceUri', async () => {const tool = createRenderUiTool([surveyTool, debugTool, plainTool], mockContext)!const result = (await tool.handler(mockContext, {diff --git a/services/mcp/tests/unit/ui-apps.test.ts b/services/mcp/tests/unit/ui-apps.test.tsindex ae4352b1e2ce..bc5207cbbe5a 100644--- a/services/mcp/tests/unit/ui-apps.test.ts+++ b/services/mcp/tests/unit/ui-apps.test.ts@@ -3,7 +3,12 @@ import { describe, expect, it, vi } from 'vitest'import { buildAppStubHtml } from '@/resources/ui-apps'import { DISPATCHABLE_APP_KEYS, UI_APPS, URI_MAP } from '@/resources/ui-apps.generated'-import { generateDispatchModule, resolveDetailApp, resolveListApp } from '../../scripts/generate-ui-apps'+import {+ generateDispatchModule,+ resolveCustomApp,+ resolveDetailApp,+ resolveListApp,+} from '../../scripts/generate-ui-apps'describe('ui-apps', () => {describe('buildAppStubHtml', () => {@@ -209,15 +214,30 @@ describe('ui-apps', () => {})describe('render-ui dispatch', () => {- it('DISPATCHABLE_APP_KEYS excludes custom apps', () => {+ it('DISPATCHABLE_APP_KEYS includes opted-in custom apps', () => {expect(DISPATCHABLE_APP_KEYS).toContain('survey')expect(DISPATCHABLE_APP_KEYS).toContain('survey-list')- for (const customKey of ['debug', 'query-results', 'render-ui', 'visual-review-snapshots']) {+ expect(DISPATCHABLE_APP_KEYS).toContain('query-results')+ for (const customKey of ['debug', 'render-ui', 'visual-review-snapshots']) {expect(DISPATCHABLE_APP_KEYS).not.toContain(customKey)}})- it('generates a dispatch entry per detail/list app and a Content component for list apps', () => {+ it('generates dispatch entries for reusable views and a Content component for list apps', () => {+ const queryResultsConfig = resolveCustomApp({+ type: 'custom',+ app_name: 'Query Results',+ description: 'Interactive query results',+ render_ui: {+ component_import: '../components/Component',+ view_component: 'Component',+ view_prop: 'data',+ },+ })+ if (!queryResultsConfig.render_ui) {+ throw new Error('Expected query results to configure render-ui dispatch')+ }+const code = generateDispatchModule([{appKey: 'survey',@@ -228,6 +248,11 @@ describe('ui-apps', () => {'products/surveys/mcp/apps'),},+ {+ appKey: 'query-results',+ type: 'custom',+ config: { ...queryResultsConfig, render_ui: queryResultsConfig.render_ui },+ },{appKey: 'survey-list',type: 'list',@@ -240,6 +265,8 @@ describe('ui-apps', () => {])expect(code).toContain("'survey': ({ data }) => <SurveyView survey={data as SurveyData} />")+ expect(code).toContain("import { Component } from '../components/Component'")+ expect(code).toContain("'query-results': ({ data }) => <Component data={data} />")expect(code).toContain("'survey-list': ({ data, app }) => <SurveyListContent data={data as SurveyListData} app={app} />")