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.

perf(mcp): avoid duplicating full results in UI-app response metadata (#75791)

posthog[bot]04c91f33a498
diff --git a/services/mcp/src/lib/build-tool-result.ts b/services/mcp/src/lib/build-tool-result.ts
index 717037a0e9e5..3c31622a993f 100644
--- a/services/mcp/src/lib/build-tool-result.ts
+++ b/services/mcp/src/lib/build-tool-result.ts
@@ -23,12 +23,13 @@ export interface BuildToolResultOptions {
/** Whether formatted-result text should win over structuredContent for this client profile. */
suppressStructuredContentForFormattedResults?: boolean | undefined
/**
- * For inline-exec UI-app hosts (PostHog Desktop, Claude Code, Cowork): always drop
- * top-level `structuredContent` toward the model and re-home the app payload onto
- * `_meta` instead — even when there's no formatted table (the model then reads the
- * TOON text). These hosts surface `structuredContent` to the model, so it must
- * never carry the raw results; the UI app hydrates from `_meta` (see APP_DATA_META_KEY).
- * Overridden by an explicit `output_format=json` from the caller.
+ * For inline-exec UI-app hosts (PostHog Desktop, Claude Code, Cowork): when a compact
+ * 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`.
*/
forceUiDataToMeta?: boolean | undefined
/** PostHog distinctId for analytics metadata (only read when a UI resource is present). */
@@ -155,12 +156,15 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResult
const text = formattedResults ?? (useJson ? JSON.stringify(rawResult) : formatResponse(rawResult))
- // Inline-exec UI-app hosts always drop top-level structuredContent (routed to
- // `_meta` below); other coding-agent clients only drop it when a formatted table
- // is available to take its place. An explicit `output_format=json` overrides both.
+ // 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
+ // `_meta` key (see below). With no formatted table we keep the standard structuredContent
+ // field, which UI apps and MCP hosts already prefer. `output_format=json` overrides both.
const suppressStructuredContent =
!callerWantsJson &&
- (!!forceUiDataToMeta || (formattedResults !== undefined && !!suppressStructuredContentForFormattedResults))
+ formattedResults !== undefined &&
+ (!!forceUiDataToMeta || !!suppressStructuredContentForFormattedResults)
const payload: ToolResultPayload = {
content: [{ type: 'text', text }],
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index df57878a61e0..73a2a50be05b 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -665,10 +665,13 @@ export function createExecTool(
params: useJson ? { ...input, output_format: 'json' } : input,
// Inline-exec UI-app hosts (PostHog Desktop, Claude Code, Cowork)
// surface `structuredContent` to the model in preference to the
- // text content, which would bury the compact formatted table
- // under the raw JSON. Always re-home the UI app's data onto
- // `_meta` (see APP_DATA_META_KEY) so the model reads the optimized
- // table (or the TOON text when unformatted) and the chart still renders.
+ // text content, which would bury a compact formatted table under
+ // 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.
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.ts
index 0530c3d70379..f48bb450db43 100644
--- a/services/mcp/tests/unit/build-tool-result.test.ts
+++ b/services/mcp/tests/unit/build-tool-result.test.ts
@@ -173,6 +173,51 @@ describe('buildToolResultPayload — query-trends for Claude Code', () => {
})
})
+// Inline-exec UI-app hosts (PostHog Desktop, Claude Code, Cowork) go through the exec
+// wrapper, which sets `forceUiDataToMeta` + `includeUiResponseMeta`. The app payload
+// should only move onto `_meta` when a compact formatted table takes structuredContent's
+// place for the model — otherwise it stays in the standard structuredContent field so it
+// isn't duplicated under a non-standard `_meta` key.
+describe('buildToolResultPayload — inline-exec UI host (forceUiDataToMeta)', () => {
+ it('suppresses structuredContent and re-homes the payload onto _meta when a formatted table exists', () => {
+ const payload = buildToolResultPayload({
+ handlerResult: queryTrendsHandlerResult(/* withFormatted */ true),
+ toolMeta: queryTrendsToolMeta,
+ toolName: 'query-trends',
+ params: {},
+ forceUiDataToMeta: true,
+ includeUiResponseMeta: true,
+ distinctId: 'd',
+ })
+
+ // Model reads the compact table, not the verbose JSON.
+ expect(payload.content[0]!.text).toBe(FORMATTED_TABLE)
+ 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) })
+ })
+
+ it('keeps the payload in structuredContent and never emits _meta app-data when there is no formatted table', () => {
+ // Regression guard for the duplicated-results report: without a compact table the
+ // model reads the data as text anyway, so re-homing it onto `_meta` only duplicates
+ // the full payload under a non-standard key. Keep it in structuredContent instead.
+ const payload = buildToolResultPayload({
+ handlerResult: queryTrendsHandlerResult(/* withFormatted */ false),
+ toolMeta: queryTrendsToolMeta,
+ toolName: 'query-trends',
+ params: {},
+ forceUiDataToMeta: true,
+ includeUiResponseMeta: true,
+ distinctId: 'd',
+ })
+
+ expect(payload.structuredContent).toMatchObject({ results: expect.any(Array) })
+ expect(payload._meta?.[APP_DATA_META_KEY]).toBeUndefined()
+ // The UI resource URI is still exposed for single-exec clients.
+ expect(payload._meta?.ui).toEqual({ resourceUri: 'ui://posthog/query-results.html' })
+ })
+})
+
describe('buildToolResultPayload — non-query use cases', () => {
it('preserves array handler results', () => {
const result = [{ id: 'template-1' }]
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index c3cacfeb8b4b..5568674d2994 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -295,7 +295,7 @@ describe('exec tool', () => {
)
})
- it('propagates the UI resource URI and exec brand when the inner tool has a UI app and consumer is posthog-code', async () => {
+ it('keeps UI data in structuredContent (not _meta) when the tool has no formatted table', async () => {
const tool = makeMockTool({
_meta: { ui: { resourceUri: 'ui://posthog/mock-app.html' } },
})
@@ -309,17 +309,19 @@ describe('exec tool', () => {
// Text content still includes the TOON-formatted result for model context
expect(result.content[0]!.text).toContain('id: 1')
- // structuredContent is dropped; the UI data (with analytics) rides on _meta.
- expect(result.structuredContent).toBeUndefined()
- const appData = result._meta[APP_DATA_META_KEY] as {
+ // 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.
+ const structured = result.structuredContent as {
id: number
_analytics: { distinctId: string; toolName: string }
}
- expect(appData.id).toBe(1)
- expect(appData._analytics).toEqual({
+ expect(structured.id).toBe(1)
+ expect(structured._analytics).toEqual({
distinctId: 'test-distinct-id',
toolName: 'mock-tool',
})
+ expect(result._meta[APP_DATA_META_KEY]).toBeUndefined()
// _meta on the response exposes the UI resource URI to clients that
// only see the `exec` tool registered (single-exec mode). Both the
// new nested key and the legacy flat key are emitted for
@@ -372,7 +374,7 @@ describe('exec tool', () => {
}
)
- it('re-homes UI data onto _meta and gives the model TOON text even when there is no formatted override', async () => {
+ it('keeps UI data in structuredContent and gives the model TOON text when there is no formatted override', async () => {
const tool = makeMockTool({
_meta: { ui: { resourceUri: 'ui://posthog/mock-app.html' } },
handler: async () => ({
@@ -387,11 +389,13 @@ describe('exec tool', () => {
_meta: { [key: string]: unknown }
}
- // Without a compact table the model reads TOON text, never verbose structuredContent.
- expect(result.structuredContent).toBeUndefined()
+ // 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')
- const appData = result._meta[APP_DATA_META_KEY] as { results: unknown }
- expect(appData.results).toEqual([{ data: [1, 2, 3], count: 6 }])
+ 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()
})
// posthog_ai is sent as its own consumer for attribution but is NOT a UI-apps host.