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): stop UI apps rendering blank when the tool result never lands (#95512)

posthog[bot]96a99fc99614
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c19b4d558902..a8237c6172a0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4942,6 +4942,10 @@ snapshots:
hash: v1.k794b7964.8d7b111f362b6382b7ab0f8b2faa9896a414b3410378070a6da3fff8df8c4617.X8hju5T08Nzt0NX65InDdmyuCNi6g111Jd27Mk7_OOU
mcp-apps-ai-observability--single-model--light:
hash: v1.k794b7964.d9666eafee0eb265527f39de0189f04df01fc001ae7ff2d8f30e7f4eb8bf78b8.tKK0r3f4eUdwxXF1CNsBMdifJyq5jKOGjlgBgjGq9oI
+ mcp-apps-app-states--loading--light:
+ hash: v1.k794b7964.808d990515fe588731d2986ab719a071f0125a7f8cb8e68efbef88deabb2a47a.86Huz6TbAd6glstvcl_q_Fjbqq4kUnzMPIMO8KZTx9I
+ mcp-apps-app-states--no-results--light:
+ hash: v1.k794b7964.ec1850d251b28c2a7cdcfc9af5ae0bfd8815409ef910496dc5be187c7fc71a3f.6oJ3kFtDZfJsymE8sN667fRtzQkLKKHwXjCdzbqsCHA
mcp-apps-cohorts--calculating--light:
hash: v1.k794b7964.ccc89a2389eb15f76a817d88dd26ff03f20210f23eed40183436261a92504399.pXD51hUgUtFpzTJd-iaVQJ5d1SRr2Ifr_1geD9qwPwY
mcp-apps-cohorts--dynamic--light:
diff --git a/services/mcp/CONTRIBUTING.md b/services/mcp/CONTRIBUTING.md
index 49a342622006..9aaa3bb96791 100644
--- a/services/mcp/CONTRIBUTING.md
+++ b/services/mcp/CONTRIBUTING.md
@@ -207,6 +207,18 @@ The visualization system is designed to be extractable to a standalone `@posthog
**Other**:
- **PostHogLink** - "View in PostHog" button
+- **PostHogLogo** - Logo mark shared by the app resolution states
+- **AppErrorState** / **AppLoadingState** - The states an app shows before, or instead of, content
+
+### Stories
+
+Storybook compiles these stories from the `common/storybook` workspace, which cannot resolve this package's own dependencies.
+A story may therefore only import components that never reach `@modelcontextprotocol/ext-apps`.
+The visualizers and the resolution states above are safe; `AppWrapper` and `useToolResult` are not.
+Keep presentational components in their own module rather than importing them from an SDK-coupled one.
+
+The Storybook dev server resolves the SDK anyway, so it renders such a story happily and only the production build fails.
+Verify with `pnpm --filter=@posthog/storybook build` rather than `start`.
### Theming
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index 77e6f4c1f52b..ed29e5ef76d7 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -79,11 +79,10 @@ interface ExecMetricState {
*
* MCP gives the executor no way to prove that a call came from the app, so this reads
* connection state instead of call provenance. In tools mode the model calls tools
- * directly, which makes the two indistinguishable, so suppression still applies there and
- * a UI app loaded that way still gets nothing. To fix that case, pass `forceUiDataToMeta`
- * and `includeUiResponseMeta` together, which moves the app payload to `_meta` instead of
- * widening what the model reads. `buildToolResultPayload` writes that payload only when
- * both flags are set.
+ * directly, which makes the two indistinguishable, so suppression still applies there.
+ * A UI app loaded that way still renders, because `buildToolResultPayload` moves the app
+ * payload to the app-only `_meta` key whenever it suppresses `structuredContent` for a
+ * tool that has a UI resource, without widening what the model reads.
*/
function shouldSuppressStructuredContent(args: {
isCliModeEnabled: boolean
diff --git a/services/mcp/src/lib/build-tool-result.ts b/services/mcp/src/lib/build-tool-result.ts
index 60b7a944272d..e96a116171f1 100644
--- a/services/mcp/src/lib/build-tool-result.ts
+++ b/services/mcp/src/lib/build-tool-result.ts
@@ -215,12 +215,18 @@ 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>
+ }
+ // `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. This does not
+ // depend on `includeUiResponseMeta`, because a host that registers the tools
+ // directly already knows the resource URI from `tools/list` and still mounts the
+ // app, so withholding the payload here leaves that app with nothing to draw.
+ if (suppressStructuredContent && hasUiResource) {
+ payload._meta = {
+ ...payload._meta,
+ [APP_DATA_META_KEY]: structuredContent as Record<string, unknown>,
}
}
// `-prepare` tools have no UI resource, so UI apps driving a confirmed action
diff --git a/services/mcp/src/ui-apps/analytics/posthog.ts b/services/mcp/src/ui-apps/analytics/posthog.ts
index ad3407762f0d..e63d567520f1 100644
--- a/services/mcp/src/ui-apps/analytics/posthog.ts
+++ b/services/mcp/src/ui-apps/analytics/posthog.ts
@@ -41,9 +41,20 @@ export function initPostHog(appName: string, appVersion: string): void {
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(),
})
}
+function newInstanceId(): string {
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
+ return crypto.randomUUID()
+ }
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
+}
+
/**
* Identify the user with their PostHog distinct ID from the MCP server.
*/
@@ -118,11 +129,26 @@ export function captureToolInput(params: { toolName?: string | undefined; hasArg
*/
export function captureToolResult(params: {
hasStructuredContent?: boolean | undefined
+ hasAppData?: boolean | undefined
contentLength?: number | undefined
+ rendered?: boolean | undefined
}): void {
capture('mcp_ui_app_tool_result', {
has_structured_content: params.hasStructuredContent,
+ has_app_data: params.hasAppData,
content_length: params.contentLength,
+ rendered: params.rendered,
+ })
+}
+
+/**
+ * Capture the app giving up on the host, which is the only signal that a person saw
+ * a failed render instead of a chart.
+ */
+export function captureWaitTimeout(params: { phase: string; timeoutMs: number }): void {
+ capture('mcp_ui_app_wait_timeout', {
+ phase: params.phase,
+ timeout_ms: params.timeoutMs,
})
}
diff --git a/services/mcp/src/ui-apps/apps/debug.tsx b/services/mcp/src/ui-apps/apps/debug.tsx
index 780cd020228c..d45684b79196 100644
--- a/services/mcp/src/ui-apps/apps/debug.tsx
+++ b/services/mcp/src/ui-apps/apps/debug.tsx
@@ -40,7 +40,8 @@ import {
TooltipTrigger,
} from '@posthog/quill'
-import { AppErrorState, AppLoadingState } from '../components/AppWrapper'
+import { AppErrorState } from '../components/AppErrorState'
+import { AppLoadingState } from '../components/AppLoadingState'
import { useToolResult } from '../hooks/useToolResult'
import type { UseToolResultReturn } from '../hooks/useToolResult'
@@ -682,7 +683,9 @@ function ShowcaseTab(): JSX.Element {
// -- App --
function DebugApp(): JSX.Element {
- const toolResult = useToolResult<unknown>({ appName: 'MCP Apps Debug' })
+ // This view exists to watch host traffic, so it waits indefinitely instead of
+ // reporting a timeout over the raw state it is there to show.
+ const toolResult = useToolResult<unknown>({ appName: 'MCP Apps Debug', waitTimeoutMs: 0 })
const hostMessages = useHostMessageLog()
const debugState = useDebugTabState(toolResult.app, hostMessages.length)
@@ -718,7 +721,7 @@ function DebugApp(): JSX.Element {
<AppLoadingState />
</TabsContent>
<TabsContent value="error">
- <AppErrorState message="Something went wrong" />
+ <AppErrorState message="This app didn't get any results. Re-run the tool to try again." />
</TabsContent>
</Tabs>
</div>
diff --git a/services/mcp/src/ui-apps/apps/render-ui.tsx b/services/mcp/src/ui-apps/apps/render-ui.tsx
index 5e03bf49b022..bdab8bb871ac 100644
--- a/services/mcp/src/ui-apps/apps/render-ui.tsx
+++ b/services/mcp/src/ui-apps/apps/render-ui.tsx
@@ -5,7 +5,9 @@ import { useEffect, useState } from 'react'
import { createRoot } from 'react-dom/client'
import type { UiAppKey } from '../../resources/ui-apps.generated'
-import { AppErrorState, AppLoadingState, AppWrapper } from '../components/AppWrapper'
+import { AppErrorState } from '../components/AppErrorState'
+import { AppLoadingState } from '../components/AppLoadingState'
+import { AppWrapper } from '../components/AppWrapper'
import { RENDER_DISPATCH } from '../generated/render-dispatch.generated'
/**
diff --git a/services/mcp/src/ui-apps/components/AppErrorState.tsx b/services/mcp/src/ui-apps/components/AppErrorState.tsx
new file mode 100644
index 000000000000..39033bbef022
--- /dev/null
+++ b/services/mcp/src/ui-apps/components/AppErrorState.tsx
@@ -0,0 +1,16 @@
+import { type ReactElement, useEffect } from 'react'
+
+import { PostHogLogo } from './PostHogLogo'
+
+export function AppErrorState({ message }: { message: string }): ReactElement {
+ useEffect(() => {
+ console.error('[PostHog MCP App] AppErrorState:', message)
+ }, [message])
+
+ return (
+ <div className="flex flex-col items-center justify-center gap-3 h-[200px] px-4">
+ <PostHogLogo size={40} />
+ <span className="text-xs text-center text-destructive-foreground">{message}</span>
+ </div>
+ )
+}
diff --git a/services/mcp/src/ui-apps/components/AppLoadingState.tsx b/services/mcp/src/ui-apps/components/AppLoadingState.tsx
new file mode 100644
index 000000000000..ed938fa57236
--- /dev/null
+++ b/services/mcp/src/ui-apps/components/AppLoadingState.tsx
@@ -0,0 +1,13 @@
+import type { ReactElement } from 'react'
+
+import { PostHogLogo } from './PostHogLogo'
+
+export function AppLoadingState(): ReactElement {
+ return (
+ <div className="flex flex-col items-center justify-center h-[200px]">
+ <div className="[animation:loading__pulse_2s_ease-in-out_infinite]">
+ <PostHogLogo size={40} />
+ </div>
+ </div>
+ )
+}
diff --git a/services/mcp/src/ui-apps/components/AppStates.stories.tsx b/services/mcp/src/ui-apps/components/AppStates.stories.tsx
new file mode 100644
index 000000000000..5fccf680d266
--- /dev/null
+++ b/services/mcp/src/ui-apps/components/AppStates.stories.tsx
@@ -0,0 +1,37 @@
+import type { Meta, StoryFn, StoryObj } from '@storybook/react'
+import type { ReactElement } from 'react'
+
+import { McpThemeDecorator } from '@posthog/mcp-ui/storybook/decorator'
+
+import { AppErrorState } from './AppErrorState'
+import { AppLoadingState } from './AppLoadingState'
+
+// An app renders in whatever width the host gives its iframe, which a side panel can
+// squeeze to a few hundred pixels, so let the story follow the viewport.
+const HostWidth = (Story: StoryFn): ReactElement => (
+ <div className="w-full">
+ <Story />
+ </div>
+)
+
+const meta: Meta = {
+ title: 'MCP Apps/App states',
+ decorators: [McpThemeDecorator, HostWidth],
+ parameters: {
+ testOptions: {
+ skipDarkMode: true,
+ },
+ },
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+export const Loading: Story = {
+ render: () => <AppLoadingState />,
+}
+
+export const NoResults: Story = {
+ render: () => <AppErrorState message="This app didn't get any results. Re-run the tool to try again." />,
+ name: 'No results',
+}
diff --git a/services/mcp/src/ui-apps/components/AppWrapper.tsx b/services/mcp/src/ui-apps/components/AppWrapper.tsx
index 15c56cc3ddae..d315179477ce 100644
--- a/services/mcp/src/ui-apps/components/AppWrapper.tsx
+++ b/services/mcp/src/ui-apps/components/AppWrapper.tsx
@@ -5,61 +5,12 @@ import { type ReactElement, type ReactNode, useCallback, useEffect, useState } f
import { Button } from '@posthog/quill'
import { useToolResult, type UseToolResultOptions, type UseToolResultReturn } from '../hooks/useToolResult'
+import { PostHogLogo } from './PostHogLogo'
export interface AppWrapperProps<T> extends UseToolResultOptions {
children: (result: UseToolResultReturn<T>) => ReactNode
}
-function PostHogLogo({ size = 16 }: { size?: number }): ReactElement {
- return (
- <svg width={size} height={size} viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
- <path
- d="M8.35523 16.1353C8.14021 16.5654 7.52647 16.5654 7.31142 16.1353L6.79714 15.1068C6.715 14.9425 6.715 14.7491 6.79714 14.5849L7.31142 13.5563C7.52647 13.1262 8.14021 13.1262 8.35523 13.5563L8.86953 14.5849C8.95163 14.7491 8.95163 14.9425 8.86953 15.1068L8.35523 16.1353ZM8.35523 21.9687C8.14021 22.3988 7.52647 22.3988 7.31142 21.9687L6.79714 20.9401C6.715 20.7758 6.715 20.5825 6.79714 20.4182L7.31142 19.3897C7.52647 18.9596 8.14021 18.9596 8.35523 19.3897L8.86953 20.4182C8.95163 20.5825 8.95163 20.7758 8.86953 20.9401L8.35523 21.9687Z"
- fill="#1D4AFF"
- />
- <path
- d="M2 19.7545C2 19.2347 2.62852 18.9743 2.99611 19.3419L5.67055 22.0164C6.03815 22.384 5.7778 23.0125 5.25796 23.0125H2.58351C2.26125 23.0125 2 22.7512 2 22.429V19.7545ZM2 16.9375C2 17.0922 2.06148 17.2407 2.17091 17.3501L7.66243 22.8416C7.77186 22.951 7.92028 23.0125 8.07502 23.0125H11.0913C11.6111 23.0125 11.8715 22.384 11.5039 22.0164L2.99611 13.5086C2.62852 13.141 2 13.4013 2 13.9212V16.9375V16.9375ZM2 11.1041C2 11.2589 2.06148 11.4073 2.17091 11.5167L13.4958 22.8416C13.6052 22.951 13.7536 23.0125 13.9084 23.0125H16.9246C17.4445 23.0125 17.7048 22.384 17.3372 22.0164L2.99611 7.67526C2.62853 7.30767 2 7.56801 2 8.08786V11.1041V11.1041ZM7.83333 11.1041C7.83333 11.2589 7.89484 11.4073 8.00424 11.5167L18.5039 22.0164C18.8715 22.384 19.5 22.1236 19.5 21.6038V18.5875C19.5 18.4328 19.4385 18.2843 19.3291 18.1749L8.82944 7.67525C8.46183 7.30767 7.83333 7.56801 7.83333 8.08786V11.1041ZM14.6628 7.67526C14.2952 7.30767 13.6667 7.56801 13.6667 8.08786V11.1041C13.6667 11.2589 13.7282 11.4073 13.8376 11.5167L18.5039 16.183C18.8715 16.5507 19.5 16.2903 19.5 15.7704V12.7542C19.5 12.5994 19.4385 12.451 19.3291 12.3416L14.6628 7.67526V7.67526Z"
- fill="#F9BD2B"
- />
- <path
- d="M26.8136 19.8261L21.3212 14.3337C20.9536 13.966 20.3251 14.2264 20.3251 14.7463V22.429C20.3251 22.7512 20.5863 23.0125 20.9086 23.0125H29.4165C29.7388 23.0125 30 22.7512 30 22.429V21.7293C30 21.4071 29.7377 21.1497 29.4181 21.1081C28.4374 20.9804 27.52 20.5325 26.8136 19.8261ZM23.125 21.1458C22.6099 21.1458 22.1917 20.7277 22.1917 20.2125C22.1917 19.6973 22.6099 19.2791 23.125 19.2791C23.6403 19.2791 24.0584 19.6973 24.0584 20.2125C24.0584 20.7277 23.6403 21.1458 23.125 21.1458Z"
- fill="black"
- />
- <path
- d="M2 22.429C2 22.7512 2.26125 23.0125 2.58351 23.0125H5.25796C5.7778 23.0125 6.03815 22.384 5.67056 22.0164L2.99611 19.3419C2.62852 18.9743 2 19.2347 2 19.7545V22.429V22.429ZM7.83333 12.5125L2.99611 7.67526C2.62852 7.30767 2 7.56801 2 8.08786V11.1041C2 11.2589 2.06148 11.4073 2.17091 11.5167L7.83333 17.1791V12.5125ZM2.99611 13.5086C2.62852 13.141 2 13.4013 2 13.9212V16.9375C2 17.0922 2.06148 17.2406 2.17091 17.3501L7.83333 23.0125V18.3458L2.99611 13.5086V13.5086Z"
- fill="#1D4AFF"
- />
- <path
- d="M13.6667 12.7542C13.6667 12.5994 13.6052 12.451 13.4958 12.3416L8.82944 7.67526C8.46189 7.30767 7.83334 7.56801 7.83334 8.08786V11.1041C7.83334 11.2589 7.89484 11.4073 8.00424 11.5167L13.6667 17.1791V12.7542V12.7542ZM7.83334 23.0125H11.0913C11.6111 23.0125 11.8715 22.384 11.5039 22.0164L7.83334 18.3458V23.0125ZM7.83334 12.5125V16.9375C7.83334 17.0922 7.89484 17.2406 8.00424 17.3501L13.6667 23.0125V18.5875C13.6667 18.4328 13.6052 18.2843 13.4958 18.1749L7.83334 12.5125Z"
- fill="#F54E00"
- />
- </svg>
- )
-}
-
-export function AppErrorState({ message }: { message: string }): ReactElement {
- useEffect(() => {
- console.error('[PostHog MCP App] AppErrorState:', message)
- }, [message])
-
- return (
- <div className="flex flex-col items-center justify-center gap-3 h-[200px]">
- <PostHogLogo size={40} />
- <span className="text-xs text-destructive-foreground">{message}</span>
- </div>
- )
-}
-
-export function AppLoadingState(): ReactElement {
- return (
- <div className="flex flex-col items-center justify-center h-[200px]">
- <div className="[animation:loading__pulse_2s_ease-in-out_infinite]">
- <PostHogLogo size={40} />
- </div>
- </div>
- )
-}
-
function ExpandButton({
app,
onDisplayModeChanged,
@@ -143,7 +94,7 @@ export function AppWrapper<T>({ children, ...options }: AppWrapperProps<T>): Rea
return (
<div
- className="mx-auto flex w-full max-w-[960px] flex-col items-center justify-center gap-3"
+ className="mx-auto flex w-full max-w-[960px] flex-col items-center justify-center gap-3 px-4"
style={{
...rootStyle,
...(containerDimensions?.height == null ? { minHeight: 200 } : {}),
@@ -152,8 +103,12 @@ export function AppWrapper<T>({ children, ...options }: AppWrapperProps<T>): Rea
<div className={showError ? '' : '[animation:loading__pulse_4s_ease-in-out_infinite]'}>
<PostHogLogo size={40} />
</div>
- {isCancelled && <span className="text-xs text-muted-foreground">Tool call was cancelled</span>}
- {error && !isCancelled && <span className="text-xs text-destructive-foreground">{error.message}</span>}
+ {isCancelled && (
+ <span className="text-xs text-center text-muted-foreground">Tool call was cancelled</span>
+ )}
+ {error && !isCancelled && (
+ <span className="text-xs text-center text-destructive-foreground">{error.message}</span>
+ )}
</div>
)
}
diff --git a/services/mcp/src/ui-apps/components/PostHogLogo.tsx b/services/mcp/src/ui-apps/components/PostHogLogo.tsx
new file mode 100644
index 000000000000..937d4be09523
--- /dev/null
+++ b/services/mcp/src/ui-apps/components/PostHogLogo.tsx
@@ -0,0 +1,28 @@
+import type { ReactElement } from 'react'
+
+export function PostHogLogo({ size = 16 }: { size?: number }): ReactElement {
+ return (
+ <svg width={size} height={size} viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M8.35523 16.1353C8.14021 16.5654 7.52647 16.5654 7.31142 16.1353L6.79714 15.1068C6.715 14.9425 6.715 14.7491 6.79714 14.5849L7.31142 13.5563C7.52647 13.1262 8.14021 13.1262 8.35523 13.5563L8.86953 14.5849C8.95163 14.7491 8.95163 14.9425 8.86953 15.1068L8.35523 16.1353ZM8.35523 21.9687C8.14021 22.3988 7.52647 22.3988 7.31142 21.9687L6.79714 20.9401C6.715 20.7758 6.715 20.5825 6.79714 20.4182L7.31142 19.3897C7.52647 18.9596 8.14021 18.9596 8.35523 19.3897L8.86953 20.4182C8.95163 20.5825 8.95163 20.7758 8.86953 20.9401L8.35523 21.9687Z"
+ fill="#1D4AFF"
+ />
+ <path
+ d="M2 19.7545C2 19.2347 2.62852 18.9743 2.99611 19.3419L5.67055 22.0164C6.03815 22.384 5.7778 23.0125 5.25796 23.0125H2.58351C2.26125 23.0125 2 22.7512 2 22.429V19.7545ZM2 16.9375C2 17.0922 2.06148 17.2407 2.17091 17.3501L7.66243 22.8416C7.77186 22.951 7.92028 23.0125 8.07502 23.0125H11.0913C11.6111 23.0125 11.8715 22.384 11.5039 22.0164L2.99611 13.5086C2.62852 13.141 2 13.4013 2 13.9212V16.9375V16.9375ZM2 11.1041C2 11.2589 2.06148 11.4073 2.17091 11.5167L13.4958 22.8416C13.6052 22.951 13.7536 23.0125 13.9084 23.0125H16.9246C17.4445 23.0125 17.7048 22.384 17.3372 22.0164L2.99611 7.67526C2.62853 7.30767 2 7.56801 2 8.08786V11.1041V11.1041ZM7.83333 11.1041C7.83333 11.2589 7.89484 11.4073 8.00424 11.5167L18.5039 22.0164C18.8715 22.384 19.5 22.1236 19.5 21.6038V18.5875C19.5 18.4328 19.4385 18.2843 19.3291 18.1749L8.82944 7.67525C8.46183 7.30767 7.83333 7.56801 7.83333 8.08786V11.1041ZM14.6628 7.67526C14.2952 7.30767 13.6667 7.56801 13.6667 8.08786V11.1041C13.6667 11.2589 13.7282 11.4073 13.8376 11.5167L18.5039 16.183C18.8715 16.5507 19.5 16.2903 19.5 15.7704V12.7542C19.5 12.5994 19.4385 12.451 19.3291 12.3416L14.6628 7.67526V7.67526Z"
+ fill="#F9BD2B"
+ />
+ <path
+ d="M26.8136 19.8261L21.3212 14.3337C20.9536 13.966 20.3251 14.2264 20.3251 14.7463V22.429C20.3251 22.7512 20.5863 23.0125 20.9086 23.0125H29.4165C29.7388 23.0125 30 22.7512 30 22.429V21.7293C30 21.4071 29.7377 21.1497 29.4181 21.1081C28.4374 20.9804 27.52 20.5325 26.8136 19.8261ZM23.125 21.1458C22.6099 21.1458 22.1917 20.7277 22.1917 20.2125C22.1917 19.6973 22.6099 19.2791 23.125 19.2791C23.6403 19.2791 24.0584 19.6973 24.0584 20.2125C24.0584 20.7277 23.6403 21.1458 23.125 21.1458Z"
+ fill="black"
+ />
+ <path
+ d="M2 22.429C2 22.7512 2.26125 23.0125 2.58351 23.0125H5.25796C5.7778 23.0125 6.03815 22.384 5.67056 22.0164L2.99611 19.3419C2.62852 18.9743 2 19.2347 2 19.7545V22.429V22.429ZM7.83333 12.5125L2.99611 7.67526C2.62852 7.30767 2 7.56801 2 8.08786V11.1041C2 11.2589 2.06148 11.4073 2.17091 11.5167L7.83333 17.1791V12.5125ZM2.99611 13.5086C2.62852 13.141 2 13.4013 2 13.9212V16.9375C2 17.0922 2.06148 17.2406 2.17091 17.3501L7.83333 23.0125V18.3458L2.99611 13.5086V13.5086Z"
+ fill="#1D4AFF"
+ />
+ <path
+ d="M13.6667 12.7542C13.6667 12.5994 13.6052 12.451 13.4958 12.3416L8.82944 7.67526C8.46189 7.30767 7.83334 7.56801 7.83334 8.08786V11.1041C7.83334 11.2589 7.89484 11.4073 8.00424 11.5167L13.6667 17.1791V12.7542V12.7542ZM7.83334 23.0125H11.0913C11.6111 23.0125 11.8715 22.384 11.5039 22.0164L7.83334 18.3458V23.0125ZM7.83334 12.5125V16.9375C7.83334 17.0922 7.89484 17.2406 8.00424 17.3501L13.6667 23.0125V18.5875C13.6667 18.4328 13.6052 18.2843 13.4958 18.1749L7.83334 12.5125Z"
+ fill="#F54E00"
+ />
+ </svg>
+ )
+}
diff --git a/services/mcp/src/ui-apps/hooks/useToolResult.ts b/services/mcp/src/ui-apps/hooks/useToolResult.ts
index 636ddc7eeefa..fc4948a68f11 100644
--- a/services/mcp/src/ui-apps/hooks/useToolResult.ts
+++ b/services/mcp/src/ui-apps/hooks/useToolResult.ts
@@ -30,7 +30,7 @@
* ```
*/
import { type App, useApp, useHostStyles } from '@modelcontextprotocol/ext-apps/react'
-import { useCallback, useEffect, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
capture,
@@ -41,16 +41,30 @@ import {
captureToolCancelled,
captureToolInput,
captureToolResult,
+ captureWaitTimeout,
identifyUser,
initPostHog,
} from '../analytics/posthog'
import { APP_DATA_META_KEY, extractAnalytics } from '../types'
+/**
+ * How long the app waits for the host before it reports a failure instead of a
+ * loading state. The host normally pushes the tool result within milliseconds of
+ * the connection handshake, so this budget only expires when a notification never
+ * arrives. A result that lands after the budget still clears the error and renders.
+ */
+export const DEFAULT_WAIT_TIMEOUT_MS = 20_000
+
export interface UseToolResultOptions {
/** App name shown to the host */
appName: string
/** App version */
appVersion?: string
+ /**
+ * How long to wait for the host to connect, and then for it to deliver a tool
+ * result, before surfacing an error. Set to 0 to wait indefinitely.
+ */
+ waitTimeoutMs?: number
}
export interface ContainerDimensions {
@@ -81,11 +95,41 @@ export interface UseToolResultReturn<T> {
refreshContainerDimensions: () => void
}
+/** What the app is waiting for, which decides whether a watchdog is armed. */
+export type WaitPhase = 'connecting' | 'awaiting-result' | 'settled'
+
+export interface WaitPhaseInput {
+ isConnected: boolean
+ hasData: boolean
+ isCancelled: boolean
+ /** A connection or parse failure the app can already report on its own. */
+ hasError: boolean
+}
+
+/**
+ * Decide what the app is still waiting for. `settled` covers every state the app
+ * can already draw, including failures, so the watchdog never fires on top of an
+ * error the app is showing.
+ */
+export function resolveWaitPhase({ isConnected, hasData, isCancelled, hasError }: WaitPhaseInput): WaitPhase {
+ if (hasData || isCancelled || hasError) {
+ return 'settled'
+ }
+ return isConnected ? 'awaiting-result' : 'connecting'
+}
+
+const WAIT_TIMEOUT_MESSAGES: Record<Exclude<WaitPhase, 'settled'>, string> = {
+ connecting: "Couldn't load this app. Re-run the tool to try again.",
+ 'awaiting-result': "This app didn't get any results. Re-run the tool to try again.",
+}
+
+const PARSE_ERROR_MESSAGE = "Couldn't read the results for this app. Re-run the tool to try again."
+
/**
* Parse tool result content, preferring structuredContent over the `_meta`
* fallback. Never falls back to text content.
*/
-function parseToolResultContent<T>(structuredContent: unknown, meta?: unknown): T | null {
+export 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
@@ -137,10 +181,12 @@ function log(...args: any[]): void {
export function useToolResult<T = unknown>({
appName,
appVersion = '1.0.0',
+ waitTimeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
}: UseToolResultOptions): UseToolResultReturn<T> {
const [data, setData] = useState<T | null>(null)
const [parseError, setParseError] = useState<Error | null>(null)
const [isCancelled, setIsCancelled] = useState(false)
+ const [timedOutPhase, setTimedOutPhase] = useState<Exclude<WaitPhase, 'settled'> | null>(null)
const [containerDimensions, setContainerDimensions] = useState<ContainerDimensions | null>(null)
const hasLoggedConnection = useRef(false)
@@ -203,16 +249,21 @@ export function useToolResult<T = unknown>({
identifyUser(analytics.distinctId, analytics.toolName)
}
+ // `hasAppData` and `rendered` separate a healthy result that rode the
+ // `_meta` channel from one the app could not draw at all, which
+ // `hasStructuredContent` alone cannot tell apart.
captureToolResult({
hasStructuredContent: !!params.structuredContent,
+ hasAppData: meta?.[APP_DATA_META_KEY] !== undefined && meta[APP_DATA_META_KEY] !== null,
contentLength: params.content?.length,
+ rendered: parsed !== null,
})
if (parsed !== null) {
setData(parsed)
setParseError(null)
} else {
- const err = new Error('Unable to parse tool result')
+ const err = new Error(PARSE_ERROR_MESSAGE)
console.error('[PostHog MCP App UI] Parse error:', err)
setParseError(err)
}
@@ -275,8 +326,43 @@ export function useToolResult<T = unknown>({
setContainerDimensions(extractContainerDimensions(ctx as unknown as Record<string, unknown>))
}, [app])
- // Combine connection and parse errors
- const error = connectionError || parseError
+ const waitPhase = resolveWaitPhase({
+ isConnected,
+ hasData: data !== null,
+ isCancelled,
+ hasError: connectionError !== null || parseError !== null,
+ })
+
+ // Without this watchdog a notification that never arrives leaves the app in its
+ // loading state forever, which reads as a broken render rather than a failure the
+ // person can retry.
+ useEffect(() => {
+ if (timedOutPhase !== null) {
+ // A late connection or a late result moves the app out of the phase that
+ // timed out, so drop the error and let the app draw what it now has.
+ if (timedOutPhase !== waitPhase) {
+ setTimedOutPhase(null)
+ }
+ return
+ }
+ if (waitPhase === 'settled' || waitTimeoutMs <= 0) {
+ return
+ }
+ const timer = setTimeout(() => {
+ log('Timed out waiting for the host', { waitPhase, waitTimeoutMs })
+ setTimedOutPhase(waitPhase)
+ captureWaitTimeout({ phase: waitPhase, timeoutMs: waitTimeoutMs })
+ }, waitTimeoutMs)
+ return () => clearTimeout(timer)
+ }, [waitPhase, timedOutPhase, waitTimeoutMs])
+
+ const timeoutError = useMemo(
+ () => (timedOutPhase === null ? null : new Error(WAIT_TIMEOUT_MESSAGES[timedOutPhase])),
+ [timedOutPhase]
+ )
+
+ // Combine connection, parse, and timeout errors
+ const error = connectionError || parseError || timeoutError
return {
data,
diff --git a/services/mcp/tests/unit/build-tool-result.test.ts b/services/mcp/tests/unit/build-tool-result.test.ts
index a7a6545d7a1e..9fd73eb9b620 100644
--- a/services/mcp/tests/unit/build-tool-result.test.ts
+++ b/services/mcp/tests/unit/build-tool-result.test.ts
@@ -72,6 +72,10 @@ describe('buildToolResultPayload — query-trends for Claude Code', () => {
// No structuredContent: Claude Code would otherwise prefer it over text,
// defeating the purpose of the formatted_results override.
expect(payload).not.toHaveProperty('structuredContent')
+ // A host that registers the tools directly still mounts the UI app from the
+ // resource URI it read in `tools/list`. Without this the app has no data at all
+ // and renders its failure state instead of the chart.
+ expect(payload._meta?.[APP_DATA_META_KEY]).toMatchObject({ results: expect.any(Array) })
})
it('keeps structuredContent when suppression is false', () => {
diff --git a/services/mcp/tests/unit/use-tool-result.test.ts b/services/mcp/tests/unit/use-tool-result.test.ts
new file mode 100644
index 000000000000..3469956525ca
--- /dev/null
+++ b/services/mcp/tests/unit/use-tool-result.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest'
+
+import { parseToolResultContent, resolveWaitPhase } from '@/ui-apps/hooks/useToolResult'
+import { APP_DATA_META_KEY } from '@/ui-apps/types'
+
+describe('useToolResult', () => {
+ // `buildToolResultPayload` drops top-level `structuredContent` whenever a compact
+ // formatted table takes its place for the model, so for that whole class of tools the
+ // `_meta` channel is the only copy of the data the app can draw.
+ describe('parseToolResultContent', () => {
+ it.each([
+ ['structuredContent when the host forwards it', { results: [1] }, undefined, { results: [1] }],
+ [
+ 'the _meta channel when structuredContent is suppressed',
+ undefined,
+ { [APP_DATA_META_KEY]: { results: [2] } },
+ { results: [2] },
+ ],
+ [
+ 'structuredContent in preference to the _meta channel',
+ { results: [1] },
+ { [APP_DATA_META_KEY]: { results: [2] } },
+ { results: [1] },
+ ],
+ ['nothing when neither channel carries data', undefined, { ui: { resourceUri: 'ui://x' } }, null],
+ ['nothing when the host forwards no _meta at all', undefined, undefined, null],
+ ])('reads %s', (_name, structuredContent, meta, expected) => {
+ expect(parseToolResultContent(structuredContent, meta)).toEqual(expected)
+ })
+ })
+
+ // The watchdog turns an undelivered notification into a retryable error. It must stay
+ // off in every state the app can already draw, or a working render gets a timeout
+ // error stacked on top of it.
+ describe('resolveWaitPhase', () => {
+ const waiting = { isConnected: false, hasData: false, isCancelled: false, hasError: false }
+
+ it.each([
+ ['before the host connects', waiting, 'connecting'],
+ ['after connecting, before a result arrives', { ...waiting, isConnected: true }, 'awaiting-result'],
+ ['once a result renders', { ...waiting, isConnected: true, hasData: true }, 'settled'],
+ ['once the tool call is cancelled', { ...waiting, isConnected: true, isCancelled: true }, 'settled'],
+ ['once the app has an error to show', { ...waiting, hasError: true }, 'settled'],
+ ])('is %s', (_name, input, expected) => {
+ expect(resolveWaitPhase(input)).toBe(expected)
+ })
+ })
+})