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.

fix(mcp): suppress structuredContent for inline-exec UI-app hosts (#69030)

Georgiy Tarasovaad4d13840ba
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index a79bd4fbc86c..96a2ed98015a 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -410,7 +410,8 @@ export class ToolExecutor {
commandReference,
clientContext.mcpConsumer,
trackInnerCall,
- state.scopeGatedTools
+ state.scopeGatedTools,
+ { isInlineExecUiHost: state.clientProfile.isInlineExecUiHost() }
)
return {
diff --git a/services/mcp/src/lib/build-tool-result.ts b/services/mcp/src/lib/build-tool-result.ts
index b1e44a713243..46f2b791e250 100644
--- a/services/mcp/src/lib/build-tool-result.ts
+++ b/services/mcp/src/lib/build-tool-result.ts
@@ -3,7 +3,7 @@ import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'
import { estimateTokens } from '@/lib/estimate-tokens'
import { formatResponse } from '@/lib/response'
import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, POSTHOG_META_KEY } from '@/tools/types'
-import type { AnalyticsMetadata, WithAnalytics } from '@/ui-apps/types'
+import { APP_DATA_META_KEY, type AnalyticsMetadata, type WithAnalytics } from '@/ui-apps/types'
export interface ToolResultMeta {
ui?: { resourceUri?: string }
@@ -21,6 +21,15 @@ export interface BuildToolResultOptions {
params: unknown
/** Whether formatted-result text should win over structuredContent for this client profile. */
suppressStructuredContentForFormattedResults?: boolean | undefined
+ /**
+ * For inline-exec UI-app hosts (PostHog Code, 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.
+ */
+ forceUiDataToMeta?: boolean | undefined
/** PostHog distinctId for analytics metadata (only read when a UI resource is present). */
distinctId?: string | undefined
/**
@@ -98,6 +107,7 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResult
toolName,
params,
suppressStructuredContentForFormattedResults,
+ forceUiDataToMeta,
distinctId,
includeUiResponseMeta,
} = opts
@@ -142,8 +152,12 @@ 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.
const suppressStructuredContent =
- formattedResults !== undefined && !callerWantsJson && !!suppressStructuredContentForFormattedResults
+ !callerWantsJson &&
+ (!!forceUiDataToMeta || (formattedResults !== undefined && !!suppressStructuredContentForFormattedResults))
const payload: ToolResultPayload = {
content: [{ type: 'text', text }],
@@ -156,6 +170,13 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResult
ui: { resourceUri },
[RESOURCE_URI_META_KEY]: resourceUri,
}
+ // `structuredContent` was dropped so the model reads the compact formatted
+ // table, but the UI app still needs the data to render. `_meta` is host-
+ // and app-only (never surfaced to the model), so carry the app payload here
+ // and let `useToolResult` hydrate from it. See APP_DATA_META_KEY.
+ if (suppressStructuredContent && hasUiResource) {
+ payload._meta[APP_DATA_META_KEY] = structuredContent as Record<string, unknown>
+ }
}
return payload
}
diff --git a/services/mcp/src/lib/client-detection.ts b/services/mcp/src/lib/client-detection.ts
index ea67ddedb4a1..cfa6f2ba8a5f 100644
--- a/services/mcp/src/lib/client-detection.ts
+++ b/services/mcp/src/lib/client-detection.ts
@@ -174,6 +174,12 @@ export const VIBE_CODING_OAUTH_CLIENT_NAME_FRAGMENTS = ['lovable', 'replit', 'no
// misclassify Claude Code as a UI host.
export const ANTHROPIC_UI_HOST_VENDOR_FRAGMENTS = ['claudeai'] as const
+// Anthropic coding-agent surfaces that render MCP UI apps inline through the
+// single-exec `exec` tool. `ClaudeCode` and `Cowork` render UI apps on the exec
+// response itself (unlike `ClaudeAI`, which uses the separate `render-ui` tool),
+// so they get the same treatment as the PostHog Code consumer.
+export const INLINE_EXEC_UI_APP_VENDOR_FRAGMENTS = ['claudecode', 'cowork'] as const
+
// User-Agent Anthropic clients send when they connect without the
// `x-anthropic-client` header (Claude.ai web/desktop and internal Anthropic
// tooling). It's a generic Anthropic signal — Claude Code and Cowork can send it
@@ -273,8 +279,10 @@ export class MCPClientProfile {
isClaudeUiHost(): boolean {
// The per-request vendor client (`x-anthropic-client`) is authoritative: it
// distinguishes the Claude surfaces that pool the same MCP transport —
- // `ClaudeAI` (web/desktop, a UI-Apps host) from `Cowork` and `ClaudeCode`,
- // which render no MCP-Apps UI. When it's present, trust it exclusively; only
+ // `ClaudeAI` (web/desktop, a UI-Apps host that renders via the separate
+ // `render-ui` tool) from `Cowork` and `ClaudeCode`, which render UI apps
+ // inline on the `exec` response instead (see `isInlineExecUiHost`) and so
+ // are not `render-ui` hosts. When it's present, trust it exclusively; only
// fall back to the `Claude-User` user-agent when the vendor header is absent.
// Otherwise a non-UI surface like Cowork — which can share the `Claude-User`
// user-agent with web/desktop — would be misclassified as a UI host.
@@ -284,6 +292,16 @@ export class MCPClientProfile {
return matchesAnyFragment(this.userAgent, ANTHROPIC_UI_HOST_USER_AGENT_FRAGMENTS)
}
+ isInlineExecUiHost(): boolean {
+ // Anthropic coding-agent surfaces that render MCP UI apps inline through the
+ // single-exec `exec` tool (Claude Code, Cowork) — as opposed to Claude.ai
+ // web/desktop, which renders via the separate `render-ui` tool. Like PostHog
+ // Code, these hosts surface `structuredContent` to the model, so the exec
+ // UI-app branch suppresses it and re-homes the app data onto `_meta`. The
+ // per-request vendor header (`ClaudeCode` / `Cowork`) is the reliable signal.
+ return matchesAnyFragment(this.vendorClient, INLINE_EXEC_UI_APP_VENDOR_FRAGMENTS)
+ }
+
get capabilities(): ClientCapabilities {
if (!this._capabilities) {
this._capabilities = this._resolveCapabilities()
diff --git a/services/mcp/src/templates/sections/cli-syntax.md b/services/mcp/src/templates/sections/cli-syntax.md
index a271537b6798..6f93a30eaa0b 100644
--- a/services/mcp/src/templates/sections/cli-syntax.md
+++ b/services/mcp/src/templates/sections/cli-syntax.md
@@ -5,7 +5,7 @@ tools — list available tool names
search <regex_pattern> — search tools by JavaScript regex (matches name, title, description)
info [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.
schema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)
-call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts. --confirm is required by the CLI for destructive tools.)
+call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of optimized output in supported tools. Use raw JSON for scripts. --confirm is required by the CLI for destructive tools.)
```
**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 24e95f0e4c18..39cb2737467c 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -48,6 +48,13 @@ export type ExecInnerCallTracker = (toolName: string, properties: ExecInnerCallP
export interface ExecToolOptions {
requireDestructiveConfirmation?: boolean
+ /**
+ * Client is an inline-exec UI-app host that renders MCP UI apps on the exec
+ * response (Claude Code, Cowork). Gets the same UI-app payload treatment as the
+ * PostHog Code consumer: structuredContent suppressed toward the model, app data
+ * re-homed onto `_meta`. Computed from the client profile at the call site.
+ */
+ isInlineExecUiHost?: boolean
}
function makeExecSchema(commandReference: string): z.ZodObject<{ command: z.ZodString }> {
@@ -184,6 +191,28 @@ export function formatInputValidationError(toolName: string, error: z.ZodError):
return `Invalid input for "${toolName}": ${[...new Set(parts)].join('; ')}`
}
+/** Whether the tool's input schema declares an `output_format` field. */
+function schemaHasOutputFormat(schema: ZodObjectAny): boolean {
+ return schema instanceof z.ZodObject && 'output_format' in schema.shape
+}
+
+/**
+ * Exec mode owns output encoding through the `--json` call flag, so tools must
+ * not also advertise their `output_format` input — an agent passing
+ * `output_format: "json"` would make the handler skip the server-side formatter
+ * only for exec to TOON-encode the raw result anyway. `call` folds the flag back
+ * into the field for tools that have it (see the `call` verb), so hiding it here
+ * loses no capability.
+ */
+function stripOutputFormatProperty(jsonSchema: Record<string, unknown>): Record<string, unknown> {
+ const properties = jsonSchema.properties as Record<string, unknown> | undefined
+ if (!properties || !('output_format' in properties)) {
+ return jsonSchema
+ }
+ const { output_format: _omitted, ...rest } = properties
+ return { ...jsonSchema, properties: rest }
+}
+
function findTool(tools: Tool<ZodObjectAny>[], name: string): Tool<ZodObjectAny> {
const tool = tools.find((t) => t.name === name)
if (!tool) {
@@ -306,7 +335,7 @@ export function createExecTool(
throw new Error('Usage: info [--json] <tool_name>')
}
const tool = findTool(allTools, infoArgs)
- const fullSchema = z.toJSONSchema(tool.schema)
+ const fullSchema = stripOutputFormatProperty(z.toJSONSchema(tool.schema) as Record<string, unknown>)
// YAML for the top shape, but inputSchema stays as a JSON
// string dumped inside the YAML — JSON Schema is conventionally
// JSON and converting it to YAML obscures `$ref`, `oneOf`, etc.
@@ -343,7 +372,9 @@ export function createExecTool(
}
const { verb: schemaToolName, rest: fieldPath } = parseCommand(rest)
const schemaTool = findTool(allTools, schemaToolName)
- const fullJsonSchema = z.toJSONSchema(schemaTool.schema) as Record<string, unknown>
+ const fullJsonSchema = stripOutputFormatProperty(
+ z.toJSONSchema(schemaTool.schema) as Record<string, unknown>
+ )
if (!fieldPath) {
// The bare `schema <tool>` view is always a summary. Any
@@ -406,7 +437,25 @@ export function createExecTool(
}
}
- const useJson = forceJson || tool._meta?.[POSTHOG_META_KEY]?.outputFormat === 'json'
+ // `output_format` is hidden from exec-mode schemas — `--json` owns output
+ // encoding. Honor a stray `output_format: "json"` as `--json` instead of
+ // letting the handler skip the formatter only for the result to be
+ // TOON-encoded anyway.
+ let strayOutputFormat: unknown
+ if ('output_format' in input) {
+ ;({ output_format: strayOutputFormat, ...input } = input)
+ }
+ const useJson =
+ forceJson ||
+ strayOutputFormat === 'json' ||
+ tool._meta?.[POSTHOG_META_KEY]?.outputFormat === 'json'
+ // Fold the flag back into the tool's own `output_format` field when it has
+ // one: formatter-toggle tools then skip the server-side formatter (clean raw
+ // JSON, no `__formatted_results_override` duplication), and tools where the
+ // field is a real backend param (dashboard-insights-run) keep full function.
+ if (useJson && schemaHasOutputFormat(tool.schema)) {
+ input.output_format = 'json'
+ }
// Same validation gate as the non-exec MCP path (`tool-executor.ts`) —
// otherwise bad input reaches the HTTP layer and builds URLs like
@@ -451,7 +500,8 @@ export function createExecTool(
// ride on the per-call response. Gated on the consumer because other
// single-exec callers (direct Claude Code, cline, Slack- and posthog_ai-launched
// runs, etc.) don't render UI apps — they should see plain text.
- if (tool._meta?.ui?.resourceUri && isPostHogCodeConsumer(mcpConsumer)) {
+ const isInlineUiAppHost = isPostHogCodeConsumer(mcpConsumer) || options.isInlineExecUiHost === true
+ if (tool._meta?.ui?.resourceUri && isInlineUiAppHost) {
const isStringResult = typeof result === 'string'
const distinctId = isStringResult ? undefined : await context.getDistinctId()
const payload = markExecPayload(
@@ -460,10 +510,13 @@ export function createExecTool(
toolMeta: tool._meta,
toolName: tool.name,
params: useJson ? { ...input, output_format: 'json' } : input,
- // Consumer is the UI-apps host; keep `structuredContent` for the UI.
- // Passing `false` bypasses coding-agent suppression in
- // `buildToolResultPayload` because this path explicitly wants it.
- suppressStructuredContentForFormattedResults: false,
+ // Inline-exec UI-app hosts (PostHog Code, 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.
+ forceUiDataToMeta: true,
distinctId,
includeUiResponseMeta: true,
})
diff --git a/services/mcp/src/ui-apps/hooks/useToolResult.ts b/services/mcp/src/ui-apps/hooks/useToolResult.ts
index 2886c76bdd51..636ddc7eeefa 100644
--- a/services/mcp/src/ui-apps/hooks/useToolResult.ts
+++ b/services/mcp/src/ui-apps/hooks/useToolResult.ts
@@ -44,7 +44,7 @@ import {
identifyUser,
initPostHog,
} from '../analytics/posthog'
-import { extractAnalytics } from '../types'
+import { APP_DATA_META_KEY, extractAnalytics } from '../types'
export interface UseToolResultOptions {
/** App name shown to the host */
@@ -82,14 +82,22 @@ export interface UseToolResultReturn<T> {
}
/**
- * Parse tool result content, preferring structuredContent over text parsing.
+ * Parse tool result content, preferring structuredContent over the `_meta`
+ * fallback. Never falls back to text content.
*/
-function parseToolResultContent<T>(structuredContent: unknown): T | null {
- // Always use structuredContent, never attempt to use text content
+function parseToolResultContent<T>(structuredContent: unknown, meta?: unknown): T | null {
+ // Prefer structuredContent when the host forwards it.
if (structuredContent !== undefined && structuredContent !== null) {
return structuredContent as T
}
+ // Coding-agent hosts suppress `structuredContent` so the model reads the
+ // compact text table; the app's data then rides on `_meta` instead.
+ const appData = (meta as Record<string, unknown> | undefined)?.[APP_DATA_META_KEY]
+ if (appData !== undefined && appData !== null) {
+ return appData as T
+ }
+
return null
}
@@ -186,7 +194,8 @@ export function useToolResult<T = unknown>({
// Register tool result handler
appInstance.ontoolresult = (params) => {
try {
- const parsed = parseToolResultContent<T>(params.structuredContent)
+ const meta = (params as { _meta?: Record<string, unknown> })._meta
+ const parsed = parseToolResultContent<T>(params.structuredContent, meta)
// Extract analytics metadata and identify the user
const analytics = extractAnalytics(parsed)
diff --git a/services/mcp/src/ui-apps/types.ts b/services/mcp/src/ui-apps/types.ts
index 7bb77120e8b8..94ceafa4d405 100644
--- a/services/mcp/src/ui-apps/types.ts
+++ b/services/mcp/src/ui-apps/types.ts
@@ -20,6 +20,16 @@ export interface AnalyticsMetadata {
toolName?: string
}
+/**
+ * Result `_meta` key that carries a UI app's data payload when the top-level
+ * `structuredContent` is suppressed from the model. Coding-agent hosts (e.g.
+ * PostHog Code) surface `structuredContent` to the model, so when a compact
+ * formatted table is returned we drop `structuredContent` to keep the model's
+ * context lean. The UI app still needs the data to render, and `_meta` is host-
+ * and app-only (never shown to the model), so the app hydrates from here.
+ */
+export const APP_DATA_META_KEY = 'com.posthog.mcp/app_data' as const
+
// ============================================================================
// Type utilities for tool results
// ============================================================================
diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.ts
index dbd27bc7326d..f9a628856e14 100644
--- a/services/mcp/tests/hono/tool-executor-intent.test.ts
+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts
@@ -52,6 +52,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
capabilities: { supportsInstructions: true },
isCliModeEnabled: vi.fn(() => false),
isClaudeUiHost: vi.fn(() => false),
+ isInlineExecUiHost: vi.fn(() => false),
} as any,
requestContext: {
sessionId: 'sess-1',
diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.ts
index 379e03c9029f..91312b48cb7c 100644
--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts
+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts
@@ -78,6 +78,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
capabilities: { supportsInstructions: true },
isCliModeEnabled: vi.fn(() => false),
isClaudeUiHost: vi.fn(() => false),
+ isInlineExecUiHost: vi.fn(() => false),
} as any,
requestContext: {
sessionId: 'sess-1',
diff --git a/services/mcp/tests/hono/tool-executor-tokens.test.ts b/services/mcp/tests/hono/tool-executor-tokens.test.ts
index 680b2ea19e34..98f377968bda 100644
--- a/services/mcp/tests/hono/tool-executor-tokens.test.ts
+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts
@@ -55,6 +55,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
capabilities: { supportsInstructions: true },
isCliModeEnabled: vi.fn(() => false),
isClaudeUiHost: vi.fn(() => false),
+ isInlineExecUiHost: vi.fn(() => false),
} as any,
requestContext: {
sessionId: 'sess-1',
diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.ts
index 056d443e08a5..376d21b72eb5 100644
--- a/services/mcp/tests/hono/tool-executor.test.ts
+++ b/services/mcp/tests/hono/tool-executor.test.ts
@@ -49,6 +49,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
capabilities: { supportsInstructions: true },
isCliModeEnabled: vi.fn(() => false),
isClaudeUiHost: vi.fn(() => false),
+ isInlineExecUiHost: vi.fn(() => false),
} as any,
requestContext: {
sessionId: 'sess-1',
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
index 33846bd801bd..12c73ac6f275 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
@@ -5,7 +5,7 @@ tools — list available tool names
search <regex_pattern> — search tools by JavaScript regex (matches name, title, description)
info [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.
schema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)
-call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts. --confirm is required by the CLI for destructive tools.)
+call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of optimized output in supported tools. Use raw JSON for scripts. --confirm is required by the CLI for destructive tools.)
```
**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.
diff --git a/services/mcp/tests/unit/client-detection.test.ts b/services/mcp/tests/unit/client-detection.test.ts
index 4d5039ce6924..d738bc79057c 100644
--- a/services/mcp/tests/unit/client-detection.test.ts
+++ b/services/mcp/tests/unit/client-detection.test.ts
@@ -448,6 +448,24 @@ describe('MCPClientProfile', () => {
})
})
+ describe('isInlineExecUiHost()', () => {
+ it.each([['ClaudeCode'], ['Cowork']])('is true for the %s vendor client', (vendorClient) => {
+ expect(new MCPClientProfile({ vendorClient }).isInlineExecUiHost()).toBe(true)
+ })
+
+ // Claude.ai renders via the separate render-ui tool, not the inline exec payload.
+ it.each([['ClaudeAI'], ['ClaudeDesign'], ['some-random-tool'], ['']])(
+ 'is false for the %s vendor client',
+ (vendorClient) => {
+ expect(new MCPClientProfile({ vendorClient }).isInlineExecUiHost()).toBe(false)
+ }
+ )
+
+ it('is false when no vendor client is set (the user-agent is not a fallback here)', () => {
+ expect(new MCPClientProfile({ userAgent: 'Claude-User' }).isInlineExecUiHost()).toBe(false)
+ })
+ })
+
describe('capabilities.supportsInstructions', () => {
it.each([['codex'], ['Codex'], ['CODEX'], ['codex-cli'], ['Codex CLI'], ['codex/1.2.3'], ['openai-codex']])(
'is false for Codex variant %s',
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index 5c3ac542cc38..bf6f82445a4b 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -18,6 +18,7 @@ import {
type Tool,
type ZodObjectAny,
} from '@/tools/types'
+import { APP_DATA_META_KEY } from '@/ui-apps/types'
function makeMockTool(overrides: Partial<Tool<ZodObjectAny>> = {}): Tool<ZodObjectAny> {
return {
@@ -41,8 +42,21 @@ const mockContext = {
getDistinctId: async () => 'test-distinct-id',
} as unknown as Context
-function createExec(tools: Tool<ZodObjectAny>[] = [makeMockTool()], mcpConsumer?: string): Tool<any> {
- return createExecTool(tools, mockContext, 'test description', 'test command reference', mcpConsumer)
+function createExec(
+ tools: Tool<ZodObjectAny>[] = [makeMockTool()],
+ mcpConsumer?: string,
+ options?: { isInlineExecUiHost?: boolean }
+): Tool<any> {
+ return createExecTool(
+ tools,
+ mockContext,
+ 'test description',
+ 'test command reference',
+ mcpConsumer,
+ undefined,
+ [],
+ options ?? {}
+ )
}
describe('exec tool', () => {
@@ -172,23 +186,28 @@ describe('exec tool', () => {
)
})
- it('propagates _meta.ui.resourceUri and structuredContent when the inner tool has a UI app and consumer is posthog-code', async () => {
+ it('propagates the UI resource URI and exec brand when the inner tool has a UI app and consumer is posthog-code', async () => {
const tool = makeMockTool({
_meta: { ui: { resourceUri: 'ui://posthog/mock-app.html' } },
})
const exec = createExec([tool], 'posthog-code')
const result = (await exec.handler(mockContext, { command: 'call mock-tool' })) as {
content: { type: string; text: string }[]
- structuredContent: { id: number; name: string; _analytics: { distinctId: string; toolName: string } }
+ structuredContent?: Record<string, unknown>
_meta: { ui: { resourceUri: string }; [key: string]: unknown }
__execBuiltPayload?: true
}
// Text content still includes the TOON-formatted result for model context
expect(result.content[0]!.text).toContain('id: 1')
- // structuredContent carries the raw object plus analytics for the UI app
- expect(result.structuredContent.id).toBe(1)
- expect(result.structuredContent._analytics).toEqual({
+ // structuredContent is dropped; the UI data (with analytics) rides on _meta.
+ expect(result.structuredContent).toBeUndefined()
+ const appData = result._meta[APP_DATA_META_KEY] as {
+ id: number
+ _analytics: { distinctId: string; toolName: string }
+ }
+ expect(appData.id).toBe(1)
+ expect(appData._analytics).toEqual({
distinctId: 'test-distinct-id',
toolName: 'mock-tool',
})
@@ -204,6 +223,68 @@ describe('exec tool', () => {
expect(result.__execBuiltPayload).toBe(true)
})
+ // Inline-exec UI-app hosts: PostHog Code (via consumer) plus Claude Code and
+ // Cowork (via the client-profile flag). All three surface structuredContent to
+ // the model, so it must be dropped and the UI data re-homed onto _meta.
+ it.each([
+ ['posthog-code consumer', 'posthog-code', undefined],
+ ['claude-code client', undefined, { isInlineExecUiHost: true }],
+ ['cowork client', undefined, { isInlineExecUiHost: true }],
+ ])(
+ 'suppresses structuredContent toward the model but re-homes UI data onto _meta for %s (with a formatted override)',
+ async (_label, consumer, options) => {
+ const tool = makeMockTool({
+ _meta: { ui: { resourceUri: 'ui://posthog/mock-app.html' } },
+ handler: async () => ({
+ results: [{ data: [1, 2, 3], count: 6 }],
+ _posthogUrl: 'http://localhost:8010/insights/new#q=...',
+ [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: 'Date|count\n2026-05-07|6',
+ }),
+ })
+ const exec = createExec([tool], consumer, options)
+ const result = (await exec.handler(mockContext, { command: 'call mock-tool' })) as {
+ content: { type: string; text: string }[]
+ structuredContent?: Record<string, unknown>
+ _meta: { ui: { resourceUri: string }; [key: string]: unknown }
+ }
+
+ // Model sees ONLY the compact table, not the raw results JSON.
+ expect(result.content[0]!.text).toBe('Date|count\n2026-05-07|6')
+ // 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.
+ const appData = result._meta[APP_DATA_META_KEY] as {
+ results: unknown
+ _analytics: { distinctId: string; toolName: string }
+ }
+ expect(appData.results).toEqual([{ data: [1, 2, 3], count: 6 }])
+ expect(appData._analytics).toEqual({ distinctId: 'test-distinct-id', toolName: 'mock-tool' })
+ expect(result._meta.ui.resourceUri).toBe('ui://posthog/mock-app.html')
+ }
+ )
+
+ it('re-homes UI data onto _meta and gives the model TOON text even when there is no formatted override', async () => {
+ const tool = makeMockTool({
+ _meta: { ui: { resourceUri: 'ui://posthog/mock-app.html' } },
+ handler: async () => ({
+ results: [{ data: [1, 2, 3], count: 6 }],
+ _posthogUrl: 'http://localhost:8010/insights/new#q=...',
+ }),
+ })
+ const exec = createExec([tool], 'posthog-code')
+ const result = (await exec.handler(mockContext, { command: 'call mock-tool' })) as {
+ content: { type: string; text: string }[]
+ structuredContent?: Record<string, unknown>
+ _meta: { [key: string]: unknown }
+ }
+
+ // Without a compact table the model reads TOON text, never verbose structuredContent.
+ expect(result.structuredContent).toBeUndefined()
+ 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 }])
+ })
+
// posthog_ai is sent as its own consumer for attribution but is NOT a UI-apps host.
it.each([[undefined], ['cline'], ['claude-code'], ['slack'], ['posthog_code'], ['posthog_ai']])(
'returns plain text (no UI payload) when consumer is %s even if the inner tool has a UI app',
@@ -427,6 +508,63 @@ describe('exec tool', () => {
})
})
+ describe('output_format suppression', () => {
+ // Mirrors the generated query wrappers / insight-query: `output_format`
+ // toggles whether the handler surfaces the server-side formatted table.
+ function makeFormatterTool(received: Record<string, unknown>[]): Tool<ZodObjectAny> {
+ return makeMockTool({
+ schema: z.object({
+ series: z.string().optional().describe('Query series'),
+ output_format: z.enum(['optimized', 'json']).default('optimized').optional(),
+ }),
+ handler: async (_ctx, params) => {
+ received.push(params as Record<string, unknown>)
+ const optimized = (params as { output_format?: string }).output_format !== 'json'
+ return {
+ results: [{ count: 6 }],
+ ...(optimized ? { [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: 'Date|count\n2026-05-07|6' } : {}),
+ }
+ },
+ })
+ }
+
+ it.each(['info mock-tool', 'schema mock-tool'])(
+ 'hides output_format from the schema rendered by "%s"',
+ async (command) => {
+ const exec = createExec([makeFormatterTool([])])
+ const result = (await exec.handler(mockContext, { command })) as string
+ expect(result).toContain('series')
+ expect(result).not.toContain('output_format')
+ }
+ )
+
+ it('returns raw JSON when output_format:"json" is passed in the call input', async () => {
+ const exec = createExec([makeFormatterTool([])])
+ const result = (await exec.handler(mockContext, {
+ command: 'call mock-tool {"output_format":"json"}',
+ })) as string
+ const parsed = JSON.parse(result)
+ expect(parsed.results).toEqual([{ count: 6 }])
+ expect(parsed[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toBeUndefined()
+ })
+
+ it('folds --json into the dispatched output_format so the handler skips the formatter', async () => {
+ const received: Record<string, unknown>[] = []
+ const exec = createExec([makeFormatterTool(received)])
+ const result = (await exec.handler(mockContext, { command: 'call --json mock-tool' })) as string
+ expect(received[0]!.output_format).toBe('json')
+ expect(JSON.parse(result).results).toEqual([{ count: 6 }])
+ })
+
+ it('still dispatches the schema default "optimized" so the formatted table wins by default', async () => {
+ const received: Record<string, unknown>[] = []
+ const exec = createExec([makeFormatterTool(received)])
+ const result = await exec.handler(mockContext, { command: 'call mock-tool' })
+ expect(received[0]!.output_format).toBe('optimized')
+ expect(result).toBe('Date|count\n2026-05-07|6')
+ })
+ })
+
describe('info command', () => {
it('returns YAML for the top shape with the input schema embedded as JSON', async () => {
const tool = makeMockTool({ schema: z.object({ name: z.string().describe('Person name') }) })