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): preload render-ui app data for the claude desktop code tab (#127251)

Richard Solomou41e693b1d765
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
index d2663946c1c1..2473590b6c92 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -331,6 +331,8 @@ An explicit request declaration takes precedence over stored session support.
The server builds the `render-ui` schema from the full catalog of read-only tools with UI apps.
The schema stays the same across accounts; execution checks the tools available to the current account.
The server rejects direct `render-ui` calls without UI support, even if the client has a cached tool list that includes it.
+A `render-ui` call runs the same tool call the app would make for its data, through the normal dispatch path, and returns that data on the app-only `_meta["com.posthog.mcp/app_data"]` key.
+The app draws the first view from that data, so it still renders on hosts that reject an app's own `tools/call`. The app calls the server itself only when the preload failed or took longer than 15 seconds (the app treats a result that takes 20 seconds as lost), and for later actions such as drill-downs.
This check does not change mode selection. Cursor still defaults to tools mode, and an explicit mode override still takes precedence.
## Claude web and desktop exec schema budget
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index f50cf385d6bc..a71d802f8759 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -1,4 +1,4 @@
-import type { ListToolsResult } from '@modelcontextprotocol/sdk/types.js'
+import type { CallToolResult, ListToolsResult } from '@modelcontextprotocol/sdk/types.js'
import type { PreparedToolCall } from '@posthog/mcp-analytics'
@@ -41,6 +41,7 @@ import {
import { getPostHogClient } from '@/lib/posthog'
import { sanitizeErrorToken } from '@/lib/posthog/analytics'
import { isPrivateScoutTrialTool } from '@/lib/tool-privacy'
+import type { UiAppKey } from '@/resources/ui-apps.generated'
import {
createExecTool,
describeApiValidationError,
@@ -64,6 +65,7 @@ import { skillAnalyticsProperties, skillLookupMissProperties } from '@/tools/ski
import { type BuiltInSkillHint, formatSkillLookupMiss, type SkillLookupMissKind } from '@/tools/skills/notFound'
import { getToolDefinitions, getToolIngestedData } from '@/tools/toolDefinitions'
import type { Context, Tool, ZodObjectAny } from '@/tools/types'
+import { readRenderUiData, renderUiDataRequest } from '@/ui-apps/apps/render-ui-data'
import {
getModelMissingReason,
@@ -1088,6 +1090,36 @@ export class ToolExecutor {
}
}
+ /**
+ * Runs the call the render-ui app would make for its data, through the normal dispatch so
+ * scopes, validation and per-tool metrics apply. Any failure, or a preload slower than
+ * `RENDER_UI_PRELOAD_TIMEOUT_MS`, leaves the app to fetch.
+ */
+ private async loadRenderUiAppData(
+ toolName: string,
+ toolInput: Record<string, unknown>,
+ appKey: UiAppKey,
+ state: ResolvedState,
+ analyticsMeta: ToolCallAnalyticsMeta
+ ): Promise<unknown> {
+ const request = renderUiDataRequest(toolName, toolInput, appKey)
+ const preload = this.dispatchToolCall(request.name, { arguments: request.arguments }, state, analyticsMeta)
+ .then((result) => {
+ const data = readRenderUiData(result as CallToolResult, appKey)
+ return data.isError ? undefined : (data.structuredContent ?? undefined)
+ })
+ .catch(() => undefined)
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const timeout = new Promise<undefined>((resolve) => {
+ timer = setTimeout(() => resolve(undefined), RENDER_UI_PRELOAD_TIMEOUT_MS)
+ })
+ try {
+ return await Promise.race([preload, timeout])
+ } finally {
+ clearTimeout(timer)
+ }
+ }
+
private async callRenderUiTool(
params: Record<string, unknown> | undefined,
state: ResolvedState,
@@ -1096,7 +1128,9 @@ export class ToolExecutor {
const renderUiTool = createRenderUiTool(
state.allTools,
state.context,
- getEffectiveMCPClientIdentity(state.requestContext, state.sessionContext).mcpClientName
+ getEffectiveMCPClientIdentity(state.requestContext, state.sessionContext).mcpClientName,
+ (toolName, toolInput, appKey) =>
+ this.loadRenderUiAppData(toolName, toolInput, appKey, state, analyticsMeta ?? {})
)
if (!renderUiTool) {
return {
@@ -1259,6 +1293,10 @@ function resolveToolErrorClassification(error: unknown): ToolErrorClassification
// the bound external servers get when they pass `error` to the SDK.
const MAX_ERROR_MESSAGE_LENGTH = 2048
+// Below the render-ui app's result watchdog (`DEFAULT_WAIT_TIMEOUT_MS`, 20s), so a slow
+// query returns the render directive in time and the app fetches the data itself.
+const RENDER_UI_PRELOAD_TIMEOUT_MS = 15_000
+
/**
* Collapses array indexes in a DRF attr path (`actions__2__inputs__email`) to
* `N` so one leaf failure mode groups to one value regardless of where in the
diff --git a/services/mcp/src/lib/client-detection.ts b/services/mcp/src/lib/client-detection.ts
index 0a4a2d0685ab..049c9eb4a3a3 100644
--- a/services/mcp/src/lib/client-detection.ts
+++ b/services/mcp/src/lib/client-detection.ts
@@ -215,11 +215,6 @@ export const ANTHROPIC_UI_HOST_USER_AGENT_FRAGMENTS = ANTHROPIC_USER_AGENT_FRAGM
// render UI.
export const OPENAI_RENDER_UI_CLIENT_NAMES = ['openai-mcp'] as const
-// Claude desktop's Code tab sends `claude-code/<version> (claude-desktop, ...)`.
-// The terminal CLI sends the same product token without `claude-desktop`.
-export const CLAUDE_CODE_USER_AGENT_PRODUCTS = ['claude-code'] as const
-export const CLAUDE_DESKTOP_USER_AGENT_FRAGMENTS = ['claude-desktop'] as const
-
export type ClientCapabilities = {
// MCP `initialize` response includes an `instructions` field that most
// clients inject into the model's system prompt. Codex discards it, so
@@ -336,20 +331,9 @@ export class MCPClientProfile {
}
isRenderUiHost(): boolean {
- // The Code tab in Claude desktop declares the MCP Apps extension, but its host
- // rejects every app `callServerTool` with JSON-RPC -32603. The `render-ui` app
- // then cannot load its data and shows only an error state.
- // ponytail: this blocks every desktop Code build, including a future fixed one.
- // Remove the check when a desktop Code build forwards app tool calls.
- if (
- matchesProductName(this.userAgent, CLAUDE_CODE_USER_AGENT_PRODUCTS) &&
- matchesAnyFragment(this.userAgent, CLAUDE_DESKTOP_USER_AGENT_FRAGMENTS)
- ) {
- return false
- }
- // Any other client that declares the MCP Apps extension states its own support,
- // so the declaration wins over name detection in both directions. Clients that
- // omit the extension fall back to the hosts known to render `render-ui`.
+ // A client that declares the MCP Apps extension states its own support, so the
+ // declaration wins over name detection in both directions. Clients that omit the
+ // extension fall back to the hosts known to render `render-ui`.
if (this.uiSupported !== undefined) {
return this.uiSupported
}
diff --git a/services/mcp/src/tools/render-ui.ts b/services/mcp/src/tools/render-ui.ts
index 991cb994c095..18d0e9114914 100644
--- a/services/mcp/src/tools/render-ui.ts
+++ b/services/mcp/src/tools/render-ui.ts
@@ -6,6 +6,7 @@ import { markExecPayload, type ToolResultPayload } from '@/lib/build-tool-result
import { DISPATCHABLE_APP_KEYS, RENDER_UI_RESOURCE_URI, URI_MAP, type UiAppKey } from '@/resources/ui-apps.generated'
import RENDER_UI_EXPLAIN_CHART from '@/templates/render-ui-explain-chart.md'
import RENDER_UI_PROMPT from '@/templates/render-ui-prompt.md'
+import { APP_DATA_META_KEY } from '@/ui-apps/types'
import { type Context, type Tool, type ZodObjectAny } from './types'
@@ -65,17 +66,25 @@ export function makeRenderUiSchema(
type RenderUiSchema = ReturnType<typeof makeRenderUiSchema>
+export type RenderUiAppDataLoader = (
+ toolName: string,
+ toolInput: Record<string, unknown>,
+ appKey: UiAppKey
+) => Promise<unknown>
+
/**
* Builds the `render-ui` umbrella tool. Returns `null` when no tool in `allTools`
* has a renderable UI app (a `z.enum` needs at least one value, and there is
- * nothing to render anyway). Unlike the per-entity tools, this one does not run
- * the inner tool: it emits a render directive (`{ tool_name, tool_input, app_key }`
- * + the render-ui resourceUri) and the UI app fetches its own data.
+ * nothing to render anyway). It emits a render directive (`{ tool_name, tool_input,
+ * app_key }` + the render-ui resourceUri) for the model, and the data from
+ * `loadAppData` on the app-only `_meta` key. The UI app fetches the data itself when
+ * none was preloaded.
*/
export function createRenderUiTool(
allTools: Tool<ZodObjectAny>[],
context: Context,
- mcpClientName?: string
+ mcpClientName?: string,
+ loadAppData?: RenderUiAppDataLoader
): Tool<RenderUiSchema> | null {
const renderableNames = getRenderableToolNames(allTools)
if (renderableNames.length === 0) {
@@ -112,10 +121,10 @@ export function createRenderUiTool(
}
const toolInput = params.tool_input ?? {}
- // `render-ui` only emits a render directive — it never executes the inner tool,
- // so the inner tool is deliberately not counted in per-tool call metrics. The
- // umbrella call itself is tracked under `render-ui` by the executor.
- const distinctId = await context.getDistinctId()
+ const [distinctId, appData] = await Promise.all([
+ context.getDistinctId(),
+ loadAppData?.(tool.name, toolInput, appKey),
+ ])
const payload: ToolResultPayload = {
content: [
@@ -139,6 +148,7 @@ export function createRenderUiTool(
_meta: {
ui: { resourceUri: RENDER_UI_RESOURCE_URI },
[RESOURCE_URI_META_KEY]: RENDER_UI_RESOURCE_URI,
+ ...(appData === undefined ? {} : { [APP_DATA_META_KEY]: appData }),
},
}
return markExecPayload(payload)
diff --git a/services/mcp/src/ui-apps/apps/render-ui-data.ts b/services/mcp/src/ui-apps/apps/render-ui-data.ts
index 7d79259970b1..10b0c1eb59ce 100644
--- a/services/mcp/src/ui-apps/apps/render-ui-data.ts
+++ b/services/mcp/src/ui-apps/apps/render-ui-data.ts
@@ -1,4 +1,5 @@
import type { App } from '@modelcontextprotocol/ext-apps'
+import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
import type { UiAppKey } from '../../resources/ui-apps.generated'
import { APP_DATA_META_KEY } from '../types'
@@ -8,19 +9,24 @@ interface RenderUiDataResult {
isError?: boolean
}
-export async function loadRenderUiData(
- app: Pick<App, 'callServerTool'>,
+export interface RenderUiDataRequest {
+ name: string
+ arguments: Record<string, unknown>
+}
+
+/** The `tools/call` that fetches a visualization's data; the server preloads with the same call. */
+export function renderUiDataRequest(
toolName: string,
input: Record<string, unknown>,
appKey: UiAppKey
-): Promise<RenderUiDataResult> {
- const useExec = appKey === 'query-results'
- const result = await app.callServerTool(
- useExec
- ? { name: 'exec', arguments: { command: `call --json ${toolName} ${JSON.stringify(input)}` } }
- : { name: toolName, arguments: input }
- )
- if (!useExec || result.isError) {
+): RenderUiDataRequest {
+ return appKey === 'query-results'
+ ? { name: 'exec', arguments: { command: `call --json ${toolName} ${JSON.stringify(input)}` } }
+ : { name: toolName, arguments: input }
+}
+
+export function readRenderUiData(result: CallToolResult, appKey: UiAppKey): RenderUiDataResult {
+ if (appKey !== 'query-results' || result.isError) {
return result
}
const data = result.structuredContent ?? result._meta?.[APP_DATA_META_KEY]
@@ -30,3 +36,17 @@ export async function loadRenderUiData(
const text = result.content.find((item) => item.type === 'text')?.text
return { structuredContent: text === undefined ? undefined : JSON.parse(text) }
}
+
+export async function loadRenderUiData(
+ app: Pick<App, 'callServerTool'>,
+ toolName: string,
+ input: Record<string, unknown>,
+ appKey: UiAppKey,
+ resultMeta?: Record<string, unknown> | null
+): Promise<RenderUiDataResult> {
+ const preloaded = resultMeta?.[APP_DATA_META_KEY]
+ if (preloaded !== undefined && preloaded !== null) {
+ return { structuredContent: preloaded }
+ }
+ return readRenderUiData(await app.callServerTool(renderUiDataRequest(toolName, input, appKey)), appKey)
+}
diff --git a/services/mcp/src/ui-apps/apps/render-ui.tsx b/services/mcp/src/ui-apps/apps/render-ui.tsx
index 08b02fddd629..ca0f31c19bd1 100644
--- a/services/mcp/src/ui-apps/apps/render-ui.tsx
+++ b/services/mcp/src/ui-apps/apps/render-ui.tsx
@@ -14,9 +14,9 @@ import { loadRenderUiData } from './render-ui-data'
/**
* Envelope emitted by the `render-ui` server tool. It carries the tool to render
- * and its input — never the data itself. This app fetches the data via
- * `callServerTool` (the same path the list apps use for drill-down) and mounts
- * the matching view from the generated dispatch registry.
+ * and its input, never the data itself. The data arrives preloaded on the result's
+ * app-only `_meta`, or the app fetches it via `callServerTool`, then mounts the
+ * matching view from the generated dispatch registry.
*/
interface RenderUiEnvelope {
tool_name: string
@@ -27,17 +27,21 @@ interface RenderUiEnvelope {
function RenderUiApp(): JSX.Element {
return (
<AppWrapper<RenderUiEnvelope> appName="PostHog Render UI">
- {({ data, app, openLink }) => <RenderUiContent envelope={data!} app={app} openLink={openLink} />}
+ {({ data, resultMeta, app, openLink }) => (
+ <RenderUiContent envelope={data!} resultMeta={resultMeta} app={app} openLink={openLink} />
+ )}
</AppWrapper>
)
}
function RenderUiContent({
envelope,
+ resultMeta,
app,
openLink,
}: {
envelope: RenderUiEnvelope
+ resultMeta: Record<string, unknown> | null
app: App | null
openLink: (url: string) => void
}): JSX.Element {
@@ -65,7 +69,7 @@ function RenderUiContent({
let cancelled = false
setData(null)
setError(null)
- loadRenderUiData(app, toolName, JSON.parse(toolInputJson) as Record<string, unknown>, appKey)
+ loadRenderUiData(app, toolName, JSON.parse(toolInputJson) as Record<string, unknown>, appKey, resultMeta)
.then((result) => {
if (cancelled) {
return
@@ -91,7 +95,7 @@ function RenderUiContent({
return () => {
cancelled = true
}
- }, [app, toolName, toolInputJson, appKey])
+ }, [app, toolName, toolInputJson, appKey, resultMeta])
const render = RENDER_DISPATCH[envelope.app_key]
const failureReason = render ? error?.reason : 'no_visualization'
diff --git a/services/mcp/src/ui-apps/hooks/useToolResult.ts b/services/mcp/src/ui-apps/hooks/useToolResult.ts
index f9f219ce4158..75b9cdde4d57 100644
--- a/services/mcp/src/ui-apps/hooks/useToolResult.ts
+++ b/services/mcp/src/ui-apps/hooks/useToolResult.ts
@@ -77,6 +77,8 @@ export interface ContainerDimensions {
export interface UseToolResultReturn<T> {
/** The parsed tool result data, or null if not yet received */
data: T | null
+ /** The tool result's `_meta`, or null if not yet received */
+ resultMeta: Record<string, unknown> | null
/** Whether the app is connected to the host */
isConnected: boolean
/** Connection or parsing error, if any */
@@ -186,6 +188,7 @@ export function useToolResult<T = unknown>({
waitTimeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
}: UseToolResultOptions): UseToolResultReturn<T> {
const [data, setData] = useState<T | null>(null)
+ const [resultMeta, setResultMeta] = useState<Record<string, unknown> | null>(null)
const [parseError, setParseError] = useState<Error | null>(null)
const [isCancelled, setIsCancelled] = useState(false)
const [timedOutPhase, setTimedOutPhase] = useState<Exclude<WaitPhase, 'settled'> | null>(null)
@@ -263,6 +266,7 @@ export function useToolResult<T = unknown>({
})
if (parsed !== null) {
+ setResultMeta(meta ?? null)
setData(parsed)
setParseError(null)
} else {
@@ -369,6 +373,7 @@ export function useToolResult<T = unknown>({
return {
data,
+ resultMeta,
isConnected,
error,
isCancelled,
diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.ts
index 02fbeeee4771..16150ac32a45 100644
--- a/services/mcp/tests/hono/tool-executor.test.ts
+++ b/services/mcp/tests/hono/tool-executor.test.ts
@@ -26,6 +26,7 @@ import { makeSkillFile, SkillCatalog } from '@/skills/skill-catalog'
import { GENERATED_TOOL_MAP } from '@/tools/generated'
import { getToolDefinition, getToolDefinitions } from '@/tools/toolDefinitions'
import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY } from '@/tools/types'
+import { APP_DATA_META_KEY } from '@/ui-apps/types'
import { makeToolExecutorState, mockApi } from '../shared/test-utils'
@@ -838,6 +839,105 @@ describe('ToolExecutor', () => {
expect(result.content[0].text).toContain('not found')
})
+ // Some hosts (Claude Code 2.1.308+) never forward the app's own `tools/call`, so the
+ // first view must draw from data the render-ui result already carries.
+ describe('preloaded app data', () => {
+ let getToolByNameSpy: MockInstance | undefined
+
+ afterEach(() => {
+ getToolByNameSpy?.mockRestore()
+ getToolByNameSpy = undefined
+ })
+
+ function stubInnerTool(handler: () => Promise<unknown>): void {
+ getToolByNameSpy = vi.spyOn(catalog, 'getToolByName').mockReturnValue({
+ build() {
+ return this.base
+ },
+ base: { schema: z.object({ surveyId: z.string() }), handler, _meta: uiAppTool._meta },
+ } as any)
+ }
+
+ async function renderSurvey(): Promise<any> {
+ const state = makeToolExecutorState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })
+ return executor.handleToolCall(
+ { name: 'render-ui', arguments: { tool_name: 'survey-get', tool_input: { surveyId: 'abc' } } },
+ state
+ )
+ }
+
+ it('carries the data the app would fetch on app-only _meta', async () => {
+ stubInnerTool(async () => ({ id: 'abc', name: 'NPS' }))
+
+ const result = await renderSurvey()
+
+ expect(result._meta[APP_DATA_META_KEY]).toMatchObject({ id: 'abc', name: 'NPS' })
+ expect(result.structuredContent).not.toHaveProperty('name')
+ })
+
+ it('preloads query charts through exec as JSON, like the app does', async () => {
+ const data = { results: [{ label: '$pageview', data: [3] }] }
+ // Exec runs the tools on the state's roster, so the stub carries a schema and handler.
+ const queryTool = {
+ name: 'query-trends',
+ annotations: { readOnlyHint: true },
+ _meta: { ui: { resourceUri: URI_MAP['query-results'] } },
+ schema: z.object({}),
+ handler: async () => data,
+ }
+ const state = makeToolExecutorState([queryTool], { useSingleExec: true, renderUiEnabled: true })
+
+ const result = (await executor.handleToolCall(
+ { name: 'render-ui', arguments: { tool_name: 'query-trends', tool_input: {} } },
+ state
+ )) as any
+
+ expect(result._meta[APP_DATA_META_KEY]).toEqual(data)
+ })
+
+ it('preloads through a normal tool call, so input validation still applies', async () => {
+ const handler = vi.fn(async () => ({ id: 'abc' }))
+ stubInnerTool(handler)
+ const state = makeToolExecutorState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })
+
+ const result = (await executor.handleToolCall(
+ { name: 'render-ui', arguments: { tool_name: 'survey-get', tool_input: { surveyId: 123 } } },
+ state
+ )) as any
+
+ expect(handler).not.toHaveBeenCalled()
+ expect(result.isError).toBeFalsy()
+ expect(result._meta).not.toHaveProperty(APP_DATA_META_KEY)
+ })
+
+ it('still renders, leaving the app to fetch, when the preload fails', async () => {
+ stubInnerTool(async () => {
+ throw new Error('boom')
+ })
+
+ const result = await renderSurvey()
+
+ expect(result.isError).toBeFalsy()
+ expect(result.structuredContent.tool_name).toBe('survey-get')
+ expect(result._meta).not.toHaveProperty(APP_DATA_META_KEY)
+ })
+
+ it('stops waiting for a slow preload before the app gives up on the result', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ try {
+ stubInnerTool(() => new Promise(() => {}))
+
+ const pending = renderSurvey()
+ await vi.advanceTimersByTimeAsync(15_000)
+ const result = await pending
+
+ expect(result._meta).not.toHaveProperty(APP_DATA_META_KEY)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+ })
+
it('rejects a cached render-ui choice that is not allowed for the current account', async () => {
const state = makeToolExecutorState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })
diff --git a/services/mcp/tests/unit/client-detection.test.ts b/services/mcp/tests/unit/client-detection.test.ts
index 889352d16a43..669d32318b1a 100644
--- a/services/mcp/tests/unit/client-detection.test.ts
+++ b/services/mcp/tests/unit/client-detection.test.ts
@@ -400,12 +400,18 @@ describe('MCPClientProfile', () => {
// Claude Code's pooled initialize body also says `Anthropic/ClaudeAI`.
{ clientName: 'Anthropic/ClaudeAI' },
{ clientName: 'Anthropic/ClaudeAI', vendorClient: 'ClaudeCode' },
- // Claude desktop's Code tab declares MCP Apps support but cannot load app data.
- { userAgent: 'claude-code/2.1.309 (claude-desktop, agent-sdk/0.3.309)', uiSupported: true },
])('returns false for %j', (input) => {
expect(new MCPClientProfile(input).isRenderUiHost()).toBe(false)
})
+ it('follows the MCP Apps declaration from the Claude desktop Code tab', () => {
+ const profile = new MCPClientProfile({
+ userAgent: 'claude-code/2.1.309 (claude-desktop, agent-sdk/0.3.309)',
+ uiSupported: true,
+ })
+ expect(profile.isRenderUiHost()).toBe(true)
+ })
+
it('Claude Code stays a coding agent and is not a UI host', () => {
const profile = new MCPClientProfile({ clientName: 'Anthropic/ClaudeAI', vendorClient: 'ClaudeCode' })
expect(profile.isCliModeEnabled()).toBe(true)
diff --git a/services/mcp/tests/unit/render-ui-data.test.ts b/services/mcp/tests/unit/render-ui-data.test.ts
index ba4da55f0aae..7a404d028364 100644
--- a/services/mcp/tests/unit/render-ui-data.test.ts
+++ b/services/mcp/tests/unit/render-ui-data.test.ts
@@ -5,6 +5,25 @@ import { loadRenderUiData } from '@/ui-apps/apps/render-ui-data'
import { APP_DATA_META_KEY } from '@/ui-apps/types'
describe('render-ui data loading', () => {
+ it.each([
+ { appKey: 'survey' as const, toolName: 'survey-get' },
+ { appKey: 'query-results' as const, toolName: 'query-trends' },
+ ])('draws $appKey from preloaded data without calling the server', async ({ appKey, toolName }) => {
+ const callServerTool = vi.fn().mockRejectedValue(new Error('MCP error -32603'))
+ const meta = { [APP_DATA_META_KEY]: { results: [] } }
+
+ expect(await loadRenderUiData({ callServerTool }, toolName, {}, appKey, meta)).toEqual({
+ structuredContent: { results: [] },
+ })
+ expect(callServerTool).not.toHaveBeenCalled()
+ })
+
+ it('fetches from the server when the result carried no preloaded data', async () => {
+ const result = { structuredContent: { id: 'example' }, content: [] }
+ const callServerTool = vi.fn().mockResolvedValue(result)
+ expect(await loadRenderUiData({ callServerTool }, 'survey-get', {}, 'survey', {})).toBe(result)
+ })
+
it.each(['query-trends', 'insight-query'])(
'loads %s through the advertised exec tool as JSON',
async (toolName) => {
diff --git a/services/mcp/tests/unit/render-ui.test.ts b/services/mcp/tests/unit/render-ui.test.ts
index 6a139d2cba16..b6ed09d9b573 100644
--- a/services/mcp/tests/unit/render-ui.test.ts
+++ b/services/mcp/tests/unit/render-ui.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import { z } from 'zod'
import { toMcpInputSchema } from '@/hono/tool-catalog'
@@ -6,6 +6,7 @@ import { isToolCallPayload, type ToolResultPayload } from '@/lib/build-tool-resu
import { RENDER_UI_RESOURCE_URI, URI_MAP } from '@/resources/ui-apps.generated'
import { createRenderUiTool, getRenderableToolNames, RENDER_UI_TOOL_NAME } from '@/tools/render-ui'
import { type Context, type Tool, type ZodObjectAny } from '@/tools/types'
+import { APP_DATA_META_KEY } from '@/ui-apps/types'
const mockContext = {
getDistinctId: async () => 'test-distinct-id',
@@ -124,7 +125,27 @@ describe('render-ui tool', () => {
expect((result.structuredContent as Record<string, unknown>).tool_input).toEqual({})
})
- it('does not execute the inner tool — it only emits a render directive', async () => {
+ it('carries preloaded data on app-only _meta and keeps it out of the model-visible result', async () => {
+ const data = { id: 'abc', name: 'NPS' }
+ const loadAppData = vi.fn().mockResolvedValue(data)
+ const tool = createRenderUiTool([surveyTool], mockContext, undefined, loadAppData)!
+ const result = (await tool.handler(mockContext, {
+ tool_name: 'survey-get',
+ tool_input: { surveyId: 'abc' },
+ })) as ToolResultPayload
+
+ expect(loadAppData).toHaveBeenCalledExactlyOnceWith('survey-get', { surveyId: 'abc' }, 'survey')
+ expect(result._meta?.[APP_DATA_META_KEY]).toEqual(data)
+ expect(JSON.stringify([result.content, result.structuredContent])).not.toContain('NPS')
+ })
+
+ it('leaves the app to fetch its own data when nothing was preloaded', async () => {
+ const tool = createRenderUiTool([surveyTool], mockContext, undefined, async () => undefined)!
+ const result = (await tool.handler(mockContext, { tool_name: 'survey-get' })) as ToolResultPayload
+ expect(result._meta).not.toHaveProperty(APP_DATA_META_KEY)
+ })
+
+ it('never runs the inner tool handler itself', async () => {
let innerCalled = false
const spyTool = makeTool('survey-get', URI_MAP['survey'])
spyTool.handler = async () => {