: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): stop mirroring UI-app results into text and structuredContent (#76922)
posthog[bot]db3d2420de2d
diff --git a/services/mcp/src/lib/build-tool-result.ts b/services/mcp/src/lib/build-tool-result.tsindex 3c31622a993f..02ae1a87bd86 100644--- a/services/mcp/src/lib/build-tool-result.ts+++ b/services/mcp/src/lib/build-tool-result.ts@@ -27,9 +27,8 @@ export interface BuildToolResultOptions {* formatted table is available, drop top-level `structuredContent` toward the model so* it reads the compact table instead of the verbose JSON, and re-home the app payload* onto `_meta` for the UI app (see APP_DATA_META_KEY). When there is NO formatted table- * there is nothing to protect — the model would read the full data either way — so we- * keep the app payload in the standard `structuredContent` field rather than duplicating- * it under a non-standard `_meta` key. Overridden by an explicit `output_format=json`.+ * the payload stays in the standard `structuredContent` field and the text channel gets+ * a pointer instead of a second copy of it. Overridden by an explicit `output_format`.*/forceUiDataToMeta?: boolean | undefined/** PostHog distinctId for analytics metadata (only read when a UI resource is present). */@@ -79,14 +78,26 @@ export function markExecPayload(payload: ToolResultPayload): ToolResultPayload {}/**- * Estimate output tokens from the text actually returned to the client — the- * serialized TOON/JSON/formatted string, not the raw handler object. TOON is- * materially smaller than JSON for tabular results, so measuring the raw object- * would over-count. `structuredContent` is deliberately excluded: it duplicates- * the text for UI tools, so counting it would double-bill those calls.+ * Placeholder that replaces the text content when the payload rides in+ * `structuredContent` alone (see `buildToolResultPayload`). Kept short and+ * literal so the model knows where to read the result from.+ */+export const STRUCTURED_CONTENT_ONLY_TEXT = "Full result is in this response's structuredContent field."++/**+ * Estimate output tokens from what the client actually receives — the serialized+ * TOON/JSON/formatted string, not the raw handler object. TOON is materially+ * smaller than JSON for tabular results, so measuring the raw object would+ * over-count. `structuredContent` is normally excluded because it duplicates the+ * text for UI tools; when the text is only the `STRUCTURED_CONTENT_ONLY_TEXT`+ * pointer it duplicates nothing, so the structured payload is what gets counted.*/export function estimateResponseTokens(response: ToolResultPayload): number {- return estimateTokens(response.content.map((part) => part.text).join(''))+ const text = response.content.map((part) => part.text).join('')+ if (response.structuredContent && text === STRUCTURED_CONTENT_ONLY_TEXT) {+ return estimateTokens(response.structuredContent)+ }+ return estimateTokens(text)}/**@@ -101,6 +112,9 @@ export function estimateResponseTokens(response: ToolResultPayload): number {* `structuredContent`. Coding agents surface `structuredContent` to the model in* preference to `content[].text`, so keeping it would hide the formatted table* behind raw JSON.+ * 3. Conversely, a UI tool with no `formattedResults` on an inline-exec UI host keeps+ * `structuredContent` and drops the mirrored text, so the payload reaches the agent+ * exactly once instead of once per channel.*/export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResultPayload {const {@@ -154,8 +168,6 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResult}}- const text = formattedResults ?? (useJson ? JSON.stringify(rawResult) : formatResponse(rawResult))-// Drop top-level structuredContent only when a compact formatted table exists to take// its place — otherwise the model would just read the full data as TOON text anyway, and// suppressing here only forces the app payload to be duplicated under a non-standard@@ -166,6 +178,19 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResultformattedResults !== undefined &&(!!forceUiDataToMeta || !!suppressStructuredContentForFormattedResults)+ // Inline-exec UI hosts surface BOTH `content[].text` and `structuredContent` to the+ // model. A UI tool with no compact formatted table has nothing smaller to offer the+ // text channel, so mirroring the payload there hands the agent a second full copy of+ // the same rows. Carry it once, in `structuredContent` — the field the UI app reads+ // from too — and leave a pointer in the text. `output_format` opts back into the+ // mirrored serialization for callers that parse the text channel.+ const structuredContentOnly =+ !!forceUiDataToMeta && hasUiResource && !isStringResult && !useJson && formattedResults === undefined++ const text = structuredContentOnly+ ? STRUCTURED_CONTENT_ONLY_TEXT+ : (formattedResults ?? (useJson ? JSON.stringify(rawResult) : formatResponse(rawResult)))+const payload: ToolResultPayload = {content: [{ type: 'text', text }],}diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 73a2a50be05b..4fa00aba2158 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -669,9 +669,9 @@ export function createExecTool(// the raw JSON. When such a table exists, re-home the UI app's data// onto `_meta` (see APP_DATA_META_KEY) so the model reads the compact// table and the chart still renders. When there is no formatted table,- // the model reads the full data as text either way — so the payload- // stays in the standard `structuredContent` field instead of being- // duplicated under `_meta`, and the app still hydrates from it.+ // the payload stays in the standard `structuredContent` field — which+ // both the model and the app read — and the text channel carries a+ // pointer rather than a second copy of the same rows.forceUiDataToMeta: true,distinctId,includeUiResponseMeta: true,diff --git a/services/mcp/tests/unit/build-tool-result.test.ts b/services/mcp/tests/unit/build-tool-result.test.tsindex f48bb450db43..a7a6545d7a1e 100644--- a/services/mcp/tests/unit/build-tool-result.test.ts+++ b/services/mcp/tests/unit/build-tool-result.test.ts@@ -1,6 +1,14 @@import { describe, expect, it } from 'vitest'-import { EXEC_BUILT_PAYLOAD, markExecPayload, buildToolResultPayload, isToolCallPayload } from '@/lib/build-tool-result'+import {+ EXEC_BUILT_PAYLOAD,+ STRUCTURED_CONTENT_ONLY_TEXT,+ estimateResponseTokens,+ markExecPayload,+ buildToolResultPayload,+ isToolCallPayload,+} from '@/lib/build-tool-result'+import { estimateTokens } from '@/lib/estimate-tokens'import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, POSTHOG_META_KEY } from '@/tools/types'import { APP_DATA_META_KEY } from '@/ui-apps/types'@@ -216,6 +224,80 @@ describe('buildToolResultPayload — inline-exec UI host (forceUiDataToMeta)', (// The UI resource URI is still exposed for single-exec clients.expect(payload._meta?.ui).toEqual({ resourceUri: 'ui://posthog/query-results.html' })})++ // Regression guard for the relapse report: after the payload moved back into+ // `structuredContent`, the text channel still carried a full TOON copy of it, so an+ // inline-exec UI host handed the agent the same rows twice. List and detail shapes+ // are the two the report flagged (`experiment-list`, `experiment-get`).+ it.each([+ [+ 'list',+ {+ count: 2,+ next: null,+ results: [+ { id: 387170, name: 'Onboarding copy', feature_flag_key: 'onboarding-copy' },+ { id: 387171, name: 'Pricing page', feature_flag_key: 'pricing-page' },+ ],+ },+ ],+ [+ 'detail',+ {+ id: 387170,+ name: 'Onboarding copy',+ feature_flag: { key: 'onboarding-copy', filters: { groups: [{ rollout_percentage: 100 }] } },+ metrics: [{ kind: 'ExperimentMetric', name: 'Signups' }],+ },+ ],+ ])('serializes a %s payload exactly once when there is no formatted table', (_shape, handlerResult) => {+ const payload = buildToolResultPayload({+ handlerResult,+ toolMeta: { ui: { resourceUri: 'ui://posthog/experiment-list.html' } },+ toolName: 'experiment-list',+ params: {},+ forceUiDataToMeta: true,+ includeUiResponseMeta: 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).not.toContain('Onboarding copy')+ expect(payload._meta?.[APP_DATA_META_KEY]).toBeUndefined()+ })++ it('counts the structured payload for token estimation when the text is only a pointer', () => {+ // The estimate feeds `$mcp_tool_call.output_tokens`; without this the whole+ // response would be billed as the one-line pointer.+ const payload = buildToolResultPayload({+ handlerResult: queryTrendsHandlerResult(/* withFormatted */ false),+ toolMeta: queryTrendsToolMeta,+ toolName: 'query-trends',+ params: {},+ forceUiDataToMeta: true,+ includeUiResponseMeta: true,+ distinctId: 'd',+ })++ expect(estimateResponseTokens(payload)).toBeGreaterThan(estimateTokens(STRUCTURED_CONTENT_ONLY_TEXT))+ })++ it('keeps the mirrored text when the caller asked for JSON output', () => {+ const payload = buildToolResultPayload({+ handlerResult: queryTrendsHandlerResult(/* withFormatted */ false),+ toolMeta: queryTrendsToolMeta,+ toolName: 'query-trends',+ params: { output_format: 'json' },+ forceUiDataToMeta: true,+ includeUiResponseMeta: true,+ distinctId: 'd',+ })++ expect(JSON.parse(payload.content[0]!.text)).toMatchObject({ results: expect.any(Array) })+ expect(payload.structuredContent).toMatchObject({ results: expect.any(Array) })+ })})describe('buildToolResultPayload — non-query use cases', () => {diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 5568674d2994..0ca510132162 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest'import { parse as parseYaml } from 'yaml'import { z } from 'zod'+import { STRUCTURED_CONTENT_ONLY_TEXT } from '@/lib/build-tool-result'import { PostHogApiError, ToolInputValidationError } from '@/lib/errors'import { estimateTokens } from '@/lib/estimate-tokens'import { buildQueryToolsBlock, buildToolDomainsCompact } from '@/lib/instructions'@@ -307,8 +308,8 @@ describe('exec tool', () => {__execBuiltPayload?: true}- // Text content still includes the TOON-formatted result for model context- expect(result.content[0]!.text).toContain('id: 1')+ // Text content points at structuredContent instead of repeating the result+ expect(result.content[0]!.text).toBe(STRUCTURED_CONTENT_ONLY_TEXT)// 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.@@ -374,7 +375,7 @@ describe('exec tool', () => {})- it('keeps UI data in structuredContent and gives the model TOON text when there is no formatted override', async () => {+ it('carries the payload once — in structuredContent — when there is no formatted override', async () => {const tool = makeMockTool({_meta: { ui: { resourceUri: 'ui://posthog/mock-app.html' } },handler: async () => ({@@ -389,10 +390,11 @@ describe('exec tool', () => {_meta: { [key: string]: unknown }}- // With no compact table there is nothing to protect: the model reads the data- // as TOON text, and the app payload stays in the standard structuredContent- // field rather than being duplicated under the non-standard `_meta` key.- expect(result.content[0]!.text).toContain('_posthogUrl')+ // 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).not.toContain('_posthogUrl')const structured = result.structuredContent as { results: unknown }expect(structured.results).toEqual([{ data: [1, 2, 3], count: 6 }])expect(result._meta[APP_DATA_META_KEY]).toBeUndefined()