: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 notes and app resilience for MCP UI apps (#96640)
Daniel Parkerc6f518417e59
diff --git a/services/mcp/src/lib/build-tool-result.ts b/services/mcp/src/lib/build-tool-result.tsindex 55dc9cfdf1b6..37b6b87af434 100644--- a/services/mcp/src/lib/build-tool-result.ts+++ b/services/mcp/src/lib/build-tool-result.ts@@ -43,6 +43,7 @@ export interface BuildToolResultOptions {* see `exec` registered, so the UI metadata has to ride on the per-call response.*/includeUiResponseMeta?: boolean+ includeRenderNote?: boolean}/**@@ -75,9 +76,21 @@ export function isToolCallPayload(value: unknown): value is ToolResultPayload {)}+interface BuiltResponseText {+ structuredContentOnly: boolean+ footers: string[]+}++const builtResponseText = new WeakMap<ToolResultPayload, BuiltResponseText>()+/** Stamp a payload as exec-built so `isToolCallPayload` recognizes it. */export function markExecPayload(payload: ToolResultPayload): ToolResultPayload {- return { ...payload, [EXEC_BUILT_PAYLOAD]: true }+ const marked: ToolResultPayload = { ...payload, [EXEC_BUILT_PAYLOAD]: true }+ const built = builtResponseText.get(payload)+ if (built) {+ builtResponseText.set(marked, built)+ }+ return marked}/**@@ -87,6 +100,9 @@ export function markExecPayload(payload: ToolResultPayload): ToolResultPayload {*/export const STRUCTURED_CONTENT_ONLY_TEXT = "Full result is in this response's structuredContent field."+export const UI_APP_RENDER_NOTE =+ 'The user already sees this result as an interactive view in the conversation. State your conclusion in text and do not repeat this data in your reply.'+/*** Estimate output tokens from what the client actually receives — the serialized* TOON/JSON/formatted string, not the raw handler object. TOON is materially@@ -96,11 +112,11 @@ export const STRUCTURED_CONTENT_ONLY_TEXT = "Full result is in this response's s* pointer it duplicates nothing, so the structured payload is what gets counted.*/export function estimateResponseTokens(response: ToolResultPayload): number {- const text = response.content.map((part) => part.text).join('')- if (response.structuredContent && text === STRUCTURED_CONTENT_ONLY_TEXT) {- return estimateTokens(response.structuredContent)+ const built = builtResponseText.get(response)+ if (response.structuredContent && built?.structuredContentOnly) {+ return estimateTokens(response.structuredContent) + estimateTokens(built.footers.join('\n\n'))}- return estimateTokens(text)+ return estimateTokens(response.content.map((part) => part.text).join(''))}/**@@ -132,6 +148,7 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResultincludeAppData,distinctId,includeUiResponseMeta,+ includeRenderNote,} = optsconst isStringResult = typeof handlerResult === 'string'@@ -197,26 +214,30 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResult!useJson &&formattedResults === undefined- let text = structuredContentOnly+ const body = structuredContentOnly? STRUCTURED_CONTENT_ONLY_TEXT: ((includeAppData && useJson ? undefined : formattedResults) ??(useJson ? JSON.stringify(rawResult) : formatResponse(rawResult)))- // Discovery hints ride the text channel as a footer, mirroring how error- // responses carry `getToolRecoveryHint`. Skipped when the caller asked for- // raw JSON (the text must stay machine-parseable) and when the text is only- // the structuredContent pointer (the model reads the structured field, and- // `estimateResponseTokens` keys off the exact pointer string).+ const footers: string[] = []+if (!isStringResult && !useJson && !structuredContentOnly && !isPrepareConfirmedActionResult(handlerResult)) {const discoveryHint = getDiscoveryHint({ toolName, handlerResult })if (discoveryHint) {- text = `${text}\n\n${discoveryHint}`+ footers.push(discoveryHint)}}+ if (includeRenderNote && hasUiResource && !useJson) {+ footers.push(UI_APP_RENDER_NOTE)+ }++ const text = [body, ...footers].join('\n\n')+const payload: ToolResultPayload = {content: [{ type: 'text', text }],}+ builtResponseText.set(payload, { structuredContentOnly, footers })if (hasUiResource && !suppressStructuredContent) {payload.structuredContent = structuredContent as Record<string, unknown>}diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 8bc8a4ae2c6b..00065d15858e 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -1772,6 +1772,7 @@ export function createExecTool(includeAppData,distinctId,includeUiResponseMeta: isInlineUiAppHost,+ includeRenderNote: isInlineUiAppHost,}))trackInnerCall?.(tool.name, {diff --git a/services/mcp/src/ui-apps/analytics/posthog.ts b/services/mcp/src/ui-apps/analytics/posthog.tsindex e63d567520f1..bdb73a9d6dfe 100644--- a/services/mcp/src/ui-apps/analytics/posthog.ts+++ b/services/mcp/src/ui-apps/analytics/posthog.ts@@ -37,15 +37,24 @@ export function initPostHog(appName: string, appVersion: string): void {}log('Initializing PostHog client', { token: POSTHOG_TOKEN, host: POSTHOG_HOST, appName, appVersion })- client = new PostHog(POSTHOG_TOKEN, { host: POSTHOG_HOST })- client.register({- $mcp_app_name: appName,- $mcp_app_version: appVersion,- // Stamped once per loaded app document. Host notifications currently arrive at- // twice the connection count, and this separates a host that delivers each- // notification twice from a host that mounts the app twice.- $mcp_app_instance_id: newInstanceId(),- })+ try {+ // posthog-js-lite reads localStorage during construction, which can fail in a sandboxed iframe.+ client = new PostHog(POSTHOG_TOKEN, { host: POSTHOG_HOST })+ } catch (error) {+ log('PostHog client initialization failed', error)+ client = null+ return+ }++ try {+ client.register({+ $mcp_app_name: appName,+ $mcp_app_version: appVersion,+ $mcp_app_instance_id: newInstanceId(),+ })+ } catch (error) {+ log('PostHog register failed', error)+ }}function newInstanceId(): string {diff --git a/services/mcp/tests/unit/build-tool-result.test.ts b/services/mcp/tests/unit/build-tool-result.test.tsindex 9fdc495391b1..9db75ef281a6 100644--- a/services/mcp/tests/unit/build-tool-result.test.ts+++ b/services/mcp/tests/unit/build-tool-result.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest'import {EXEC_BUILT_PAYLOAD,STRUCTURED_CONTENT_ONLY_TEXT,+ UI_APP_RENDER_NOTE,estimateResponseTokens,markExecPayload,buildToolResultPayload,@@ -240,11 +241,12 @@ describe('buildToolResultPayload — inline-exec UI host (forceUiDataToMeta)', (params: {},forceUiDataToMeta: true,includeUiResponseMeta: true,+ includeRenderNote: true,distinctId: 'd',})// Model reads the compact table, not the verbose JSON.- expect(payload.content[0]!.text).toBe(FORMATTED_TABLE)+ expect(payload.content[0]!.text).toBe(`${FORMATTED_TABLE}\n\n${UI_APP_RENDER_NOTE}`)expect(payload).not.toHaveProperty('structuredContent')// The UI app hydrates from _meta since structuredContent was dropped.expect(payload._meta?.[APP_DATA_META_KEY]).toMatchObject({ results: expect.any(Array) })@@ -303,12 +305,14 @@ describe('buildToolResultPayload — inline-exec UI host (forceUiDataToMeta)', (params: {},forceUiDataToMeta: true,includeUiResponseMeta: true,+ includeRenderNote: true,distinctId: 'd',})expect(payload.structuredContent).toMatchObject(handlerResult)// The text channel points at structuredContent instead of repeating it.- expect(payload.content).toEqual([{ type: 'text', text: STRUCTURED_CONTENT_ONLY_TEXT }])+ expect(payload.content[0]!.text).toContain(STRUCTURED_CONTENT_ONLY_TEXT)+ expect(payload.content[0]!.text).toContain(UI_APP_RENDER_NOTE)expect(payload.content[0]!.text).not.toContain('Onboarding copy')expect(payload._meta?.[APP_DATA_META_KEY]).toBeUndefined()})@@ -323,10 +327,13 @@ describe('buildToolResultPayload — inline-exec UI host (forceUiDataToMeta)', (params: {},forceUiDataToMeta: true,includeUiResponseMeta: true,+ includeRenderNote: true,distinctId: 'd',})- expect(estimateResponseTokens(payload)).toBeGreaterThan(estimateTokens(STRUCTURED_CONTENT_ONLY_TEXT))+ expect(estimateResponseTokens(payload)).toBe(+ estimateTokens(payload.structuredContent) + estimateTokens(UI_APP_RENDER_NOTE)+ )})it('keeps the mirrored text when the caller asked for JSON output', () => {diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex a81c845d5326..c90b64e47ec6 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'import { parse as parseYaml } from 'yaml'import { z } from 'zod'-import { STRUCTURED_CONTENT_ONLY_TEXT, type ToolResultPayload } from '@/lib/build-tool-result'+import { STRUCTURED_CONTENT_ONLY_TEXT, type ToolResultPayload, UI_APP_RENDER_NOTE } from '@/lib/build-tool-result'import { PostHogApiError, ToolInputValidationError } from '@/lib/errors'import { estimateTokens } from '@/lib/estimate-tokens'import { buildQueryToolsBlock, buildToolDomainsCompact } from '@/lib/instructions'@@ -489,8 +489,7 @@ describe('exec tool', () => {__execBuiltPayload?: true}- // Text content points at structuredContent instead of repeating the result- expect(result.content[0]!.text).toBe(STRUCTURED_CONTENT_ONLY_TEXT)+ expect(result.content[0]!.text).toBe(`${STRUCTURED_CONTENT_ONLY_TEXT}\n\n${UI_APP_RENDER_NOTE}`)// With no compact table to protect, the app payload stays in the standard// structuredContent field (with analytics) rather than being duplicated under// the non-standard `_meta` app-data key.@@ -542,7 +541,7 @@ describe('exec tool', () => {}// Model sees ONLY the compact table, not the raw results JSON.- expect(result.content[0]!.text).toBe('Date|count\n2026-05-07|6')+ expect(result.content[0]!.text).toBe(`Date|count\n2026-05-07|6\n\n${UI_APP_RENDER_NOTE}`)// Top-level structuredContent is dropped so coding agents don't surface it.expect(result.structuredContent).toBeUndefined()// The UI app's data (with analytics) rides on _meta instead.@@ -571,10 +570,7 @@ describe('exec tool', () => {_meta: { [key: string]: unknown }}- // With no compact table there is nothing smaller to put in the text channel, so- // the payload stays in the standard structuredContent field and the text carries- // a pointer — neither a second copy in text nor one under the `_meta` key.- expect(result.content[0]!.text).toBe(STRUCTURED_CONTENT_ONLY_TEXT)+ expect(result.content[0]!.text).toBe(`${STRUCTURED_CONTENT_ONLY_TEXT}\n\n${UI_APP_RENDER_NOTE}`)expect(result.content[0]!.text).not.toContain('_posthogUrl')const structured = result.structuredContent as { results: unknown }expect(structured.results).toEqual([{ data: [1, 2, 3], count: 6 }])diff --git a/services/mcp/tests/unit/ui-apps-analytics.test.ts b/services/mcp/tests/unit/ui-apps-analytics.test.tsnew file mode 100644index 000000000000..03f26e9005aa--- /dev/null+++ b/services/mcp/tests/unit/ui-apps-analytics.test.ts@@ -0,0 +1,79 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++const { analyticsMockState } = vi.hoisted(() => {+ const state = {+ constructThrows: false,+ registerThrows: false,+ instances: [] as Array<{ captures: string[]; register(options: Record<string, unknown>): void }>,+ }+ return { analyticsMockState: state }+})++vi.mock('posthog-js-lite', () => ({+ PostHog: class {+ captures: string[] = []++ constructor() {+ if (analyticsMockState.constructThrows) {+ throw new Error('SecurityError reading localStorage')+ }+ analyticsMockState.instances.push(this)+ }++ register(): void {+ if (analyticsMockState.registerThrows) {+ throw new Error('register failed')+ }+ }++ identify(): void {}++ capture(event: string): void {+ this.captures.push(event)+ }+ },+}))++beforeEach(() => {+ analyticsMockState.constructThrows = false+ analyticsMockState.registerThrows = false+ analyticsMockState.instances = []+ vi.resetModules()+ vi.unstubAllGlobals()+})++async function loadAnalytics(): Promise<typeof import('@/ui-apps/analytics/posthog')> {+ vi.stubGlobal('__POSTHOG_UI_APPS_TOKEN__', 'phc_test_token')+ return await import('@/ui-apps/analytics/posthog')+}++describe('ui-apps posthog analytics', () => {+ it('captures events after a successful initialization', async () => {+ const { initPostHog, captureAppConnected } = await loadAnalytics()++ initPostHog('app', '1.0.0')+ captureAppConnected()++ expect(analyticsMockState.instances).toHaveLength(1)+ expect(analyticsMockState.instances[0]?.captures).toContain('mcp_ui_app_connected')+ })++ it('keeps the app rendering when the client constructor throws (regression)', async () => {+ analyticsMockState.constructThrows = true+ const { initPostHog, captureAppConnected } = await loadAnalytics()++ expect(() => initPostHog('app', '1.0.0')).not.toThrow()+ expect(() => captureAppConnected()).not.toThrow()+ expect(analyticsMockState.instances).toHaveLength(0)+ })++ it('keeps a working client when register throws (regression)', async () => {+ analyticsMockState.registerThrows = true+ const { initPostHog, captureAppConnected } = await loadAnalytics()++ expect(() => initPostHog('app', '1.0.0')).not.toThrow()+ expect(() => captureAppConnected()).not.toThrow()+ expect(analyticsMockState.instances).toHaveLength(1)+ expect(analyticsMockState.instances[0]?.captures).toContain('mcp_ui_app_connected')+ })+})