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(desktop): forward MCP UI app data for Codex sessions (#96638)

Daniel Parkerc14ba0979a8f
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/mapping.test.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/mapping.test.ts
index a44aa3b927a1..a31459a621f1 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/mapping.test.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/mapping.test.ts
@@ -288,6 +288,7 @@ describe("mapAppServerNotification", () => {
sessionUpdate: "tool_call_update",
toolCallId: "spawn-1",
status: "completed",
+ _meta: { posthog: { toolName: "spawn_agent" } },
},
});
});
@@ -731,8 +732,51 @@ describe("mcpToolCall result rendering", () => {
content: [
{ type: "content", content: { type: "text", text: "42 rows" } },
],
+ _meta: {
+ posthog: {
+ toolName: "mcp__posthog__query",
+ mcp: { server: "posthog", tool: "query" },
+ },
+ },
+ rawOutput: { content: [{ type: "text", text: "42 rows" }] },
+ },
+ });
+ });
+
+ it("strips null optional fields from the raw MCP result", () => {
+ const result = mapAppServerNotification(
+ "s-1",
+ APP_SERVER_NOTIFICATIONS.ITEM_COMPLETED,
+ {
+ item: {
+ type: "mcpToolCall",
+ id: "m3",
+ server: "posthog",
+ tool: "exec",
+ status: "completed",
+ arguments: { command: "call query-trends" },
+ result: {
+ content: [{ type: "text", text: "Date|Pageviews" }],
+ structuredContent: null,
+ _meta: {
+ ui: { resourceUri: "ui://posthog/query-results.html" },
+ "com.posthog.mcp/app_data": { query: {}, results: [] },
+ },
+ },
+ },
+ },
+ );
+ const rawOutput = result?.update as {
+ rawOutput?: Record<string, unknown>;
+ };
+ expect(rawOutput.rawOutput).toEqual({
+ content: [{ type: "text", text: "Date|Pageviews" }],
+ _meta: {
+ ui: { resourceUri: "ui://posthog/query-results.html" },
+ "com.posthog.mcp/app_data": { query: {}, results: [] },
},
});
+ expect("structuredContent" in (rawOutput.rawOutput ?? {})).toBe(false);
});
it("renders a failed mcpToolCall's error message", () => {
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/mapping.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/mapping.ts
index 6f5dfc8d5172..6de0d32d2446 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/mapping.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/mapping.ts
@@ -3,7 +3,11 @@ import type {
ToolCallContent,
ToolCallLocation,
} from "@agentclientprotocol/sdk";
-import { mcpToolKey, posthogToolMeta } from "@posthog/shared";
+import {
+ mcpToolKey,
+ omitNullCallToolResultFields,
+ posthogToolMeta,
+} from "@posthog/shared";
import { APP_SERVER_NOTIFICATIONS } from "./protocol";
import { readTokenUsage } from "./token-usage";
@@ -508,6 +512,19 @@ function commandLocations(item: AppServerItem): ToolCallLocation[] | undefined {
return paths.map((path) => ({ path }));
}
+function toolCallMeta(
+ item: AppServerItem,
+ tool: ToolDescriptor,
+): ReturnType<typeof posthogToolMeta> | undefined {
+ if (item.type === "collabAgentToolCall") {
+ return posthogToolMeta({ toolName: collabAgentToolName(item.tool) });
+ }
+ if (tool.mcp) {
+ return posthogToolMeta({ toolName: mcpToolKey(tool.mcp), mcp: tool.mcp });
+ }
+ return undefined;
+}
+
function mapItem(
sessionId: string,
item: AppServerItem,
@@ -517,6 +534,7 @@ function mapItem(
if (!tool || !item.id) {
return null;
}
+ const meta = toolCallMeta(item, tool);
if (!completed) {
return {
@@ -529,20 +547,7 @@ function mapItem(
status: "in_progress",
...(tool.rawInput !== undefined ? { rawInput: tool.rawInput } : {}),
...(tool.locations?.length ? { locations: tool.locations } : {}),
- ...(item.type === "collabAgentToolCall"
- ? {
- _meta: posthogToolMeta({
- toolName: collabAgentToolName(item.tool),
- }),
- }
- : tool.mcp
- ? {
- _meta: posthogToolMeta({
- toolName: mcpToolKey(tool.mcp),
- mcp: tool.mcp,
- }),
- }
- : {}),
+ ...(meta ? { _meta: meta } : {}),
},
};
}
@@ -555,6 +560,15 @@ function mapItem(
toolCallId: item.id,
status: mapStatus(item.status),
...(content ? { content } : {}),
+ ...(meta ? { _meta: meta } : {}),
+ // rawOutput lets the desktop MCP Apps host render UI resources, not just text.
+ // The strip is source hygiene, not app validity: `toCallToolResult` owns
+ // the schema-valid result an app receives. Stripping here keeps the nulls
+ // out of stored transcripts and McpAppsService events, so a delivery path
+ // that skips `toCallToolResult` cannot carry them either.
+ ...(item.type === "mcpToolCall" && item.result !== undefined
+ ? { rawOutput: omitNullCallToolResultFields(item.result) }
+ : {}),
},
};
}
diff --git a/products/desktop/packages/shared/src/call-tool-result.ts b/products/desktop/packages/shared/src/call-tool-result.ts
new file mode 100644
index 000000000000..89e3dcb9753f
--- /dev/null
+++ b/products/desktop/packages/shared/src/call-tool-result.ts
@@ -0,0 +1,31 @@
+/**
+ * Normalization for raw MCP `CallToolResult` payloads on their way to an
+ * MCP App. Kept separate from `_meta` handling (see `tool-meta.ts`): a tool
+ * result is the payload of a call, not tool metadata.
+ */
+
+const CALL_TOOL_RESULT_OPTIONAL_KEYS = [
+ "structuredContent",
+ "isError",
+ "_meta",
+] as const;
+
+/**
+ * Some sources (the Codex app-server) serialize absent optional
+ * `CallToolResult` fields as JSON `null`. The app-side zod schema types them
+ * `.optional()`, not nullable, so an explicit null fails validation and drops
+ * the whole tool result, leaving the app on its loading state. Call this
+ * before a raw MCP result reaches an MCP App.
+ */
+export function omitNullCallToolResultFields<T>(result: T): T {
+ if (result == null || typeof result !== "object") return result;
+ const record = result as Record<string, unknown>;
+ if (!CALL_TOOL_RESULT_OPTIONAL_KEYS.some((key) => record[key] === null)) {
+ return result;
+ }
+ const stripped: Record<string, unknown> = { ...record };
+ for (const key of CALL_TOOL_RESULT_OPTIONAL_KEYS) {
+ if (stripped[key] === null) delete stripped[key];
+ }
+ return stripped as T;
+}
diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.ts
index 8ca3584c57bd..f7b8a24577c8 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -52,6 +52,7 @@ export {
tabsSnapshotSchema,
tabViewStateSchema,
} from "./browser-tabs-schemas";
+export { omitNullCallToolResultFields } from "./call-tool-result";
export * from "./canvas-contracts";
export * from "./canvas-platform";
export type { CloudRunSource, PrAuthorshipMode } from "./cloud";
diff --git a/products/desktop/packages/shared/src/rich-output-prompt.ts b/products/desktop/packages/shared/src/rich-output-prompt.ts
index 3a9456bc09c8..6c5606339d80 100644
--- a/products/desktop/packages/shared/src/rich-output-prompt.ts
+++ b/products/desktop/packages/shared/src/rich-output-prompt.ts
@@ -8,6 +8,7 @@ export const RICH_OUTPUT_TAGS_PROMPT = `Embed the PostHog objects behind your co
- Inline reference: \`<kind id="...">short human label</kind>\` inside a sentence, e.g. \`The <insight id="9pQx3">checkout funnel</insight> dropped after <flag id="42">new-checkout-flow</flag> rolled out.\` Kinds: insight, dashboard, error, replay, flag, experiment, survey, ticket, report, trace, eval, event, cohort, action, person. Use the object's id (insights: the short id; feature flags: the numeric id, falling back to the key; Inbox reports: the report uuid; persons: the uuid). It renders as a chip with a live hover preview that opens the object in PostHog.
- Inline SQL: \`<hogql label="signups today">SELECT count() FROM events WHERE ...</hogql>\` - the SQL is the tag body, the label is what the sentence shows. Hovering runs the query live; clicking opens the SQL editor.
- Full-size chart, for any numeric or time-series answer (always prefer this over a markdown table): a saved insight \`<insight id="9pQx3" display="block"/>\` or a query \`<hogql display="block" title="Daily active users, last 7 days" caption="optional context">SELECT ...</hogql>\`. The chart executes live on every view. Include the time range in the title, and keep blank lines out of the SQL body.
+- Some PostHog MCP query tools render their result as an interactive chart in the conversation, and the tool result says so. When the tool result says the user already sees the result as an interactive view, do not embed the same data again as a \`<hogql>\` chart; write the conclusion in text and let that view carry the data. When it does not, the tool renders nothing on its own, so follow the full-size chart rule above.
- Recording card: \`<replay id="<session_id>" display="block"/>\` renders the recording's details with a link into PostHog's player. Use it when a specific session is the evidence.`;
export function appendRichOutputPrompt(prompt: string): string {
diff --git a/products/desktop/packages/ui/src/features/mcp-apps/components/McpAppHost.tsx b/products/desktop/packages/ui/src/features/mcp-apps/components/McpAppHost.tsx
index 3ab962f843a1..f1ab18a1b053 100644
--- a/products/desktop/packages/ui/src/features/mcp-apps/components/McpAppHost.tsx
+++ b/products/desktop/packages/ui/src/features/mcp-apps/components/McpAppHost.tsx
@@ -17,7 +17,7 @@ import { useThemeStore } from "@posthog/ui/shell/themeStore";
import { Box, Flex, IconButton, Text } from "@radix-ui/themes";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useSubscription } from "@trpc/tanstack-react-query";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { type Phase, useAppBridge } from "../hooks/useAppBridge";
import {
@@ -108,7 +108,7 @@ export function McpAppHost({
);
const openLinkMut = useMutation(trpc.mcpApps.openLink.mutationOptions());
- const { sendWhenReady } = useAppBridge({
+ const { sendWhenReady, sendResultOnce } = useAppBridge({
iframeEl,
uiResource: uiResource,
serverName,
@@ -133,18 +133,6 @@ export function McpAppHost({
openLink: openLinkMut.mutateAsync,
});
- const sentResultForCallRef = useRef<string | null>(null);
- const sendResultOnce = useCallback(
- (raw: unknown) => {
- if (sentResultForCallRef.current === toolCall.toolCallId) return;
- sentResultForCallRef.current = toolCall.toolCallId;
- const toolResult = toCallToolResult(raw);
- log.info("Sending tool result to app", { mcpToolName, toolResult });
- sendWhenReady((bridge) => bridge.sendToolResult(toolResult));
- },
- [toolCall.toolCallId, sendWhenReady, mcpToolName],
- );
-
// Forward tool results from subscriptions
useSubscription(
trpc.mcpApps.onToolResult.subscriptionOptions(
@@ -153,7 +141,8 @@ export function McpAppHost({
onData: (event) => {
if (isExec) {
if (event.toolCallId !== toolCall.toolCallId) return;
- sendResultOnce(event.result);
+ log.info("Sending tool result to app", { mcpToolName });
+ sendResultOnce(toolCall.toolCallId, event.result);
return;
}
const toolResult = toCallToolResult(event.result);
@@ -181,7 +170,7 @@ export function McpAppHost({
log.info("exec replay: sending result from toolCall prop", {
toolCallId: toolCall.toolCallId,
});
- sendResultOnce(toolCall.rawOutput);
+ sendResultOnce(toolCall.toolCallId, toolCall.rawOutput);
}, [
isExec,
toolCall.status,
diff --git a/products/desktop/packages/ui/src/features/mcp-apps/hasUiAppResult.ts b/products/desktop/packages/ui/src/features/mcp-apps/hasUiAppResult.ts
new file mode 100644
index 000000000000..bb54804592cd
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/mcp-apps/hasUiAppResult.ts
@@ -0,0 +1,18 @@
+import { resolveResultResourceUri } from "@posthog/core/mcp-apps/schemas";
+import type { ConversationItem } from "@posthog/ui/features/sessions/components/buildConversationItems";
+
+/**
+ * Whether the item's resolved tool result carries a UI-app resource (an MCP
+ * chart or inline app). Checked on the result, not the tool name: Codex routes
+ * every tool through one inline-exec wrapper, so a name check would match
+ * every call in the session, not just the one that renders a chart.
+ */
+export function hasUiAppResult(item: ConversationItem): boolean {
+ if (item.type !== "session_update") return false;
+ if (item.update.sessionUpdate !== "tool_call") return false;
+ const { toolCallId } = item.update;
+ const resolved = toolCallId
+ ? item.turnContext.toolCalls.get(toolCallId)
+ : undefined;
+ return resolveResultResourceUri(resolved?.rawOutput) !== undefined;
+}
diff --git a/products/desktop/packages/ui/src/features/mcp-apps/hooks/useAppBridge.test.ts b/products/desktop/packages/ui/src/features/mcp-apps/hooks/useAppBridge.test.ts
new file mode 100644
index 000000000000..cc8468026fb4
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/mcp-apps/hooks/useAppBridge.test.ts
@@ -0,0 +1,272 @@
+import type { McpUiResource } from "@posthog/core/mcp-apps/schemas";
+import type { ToolCall } from "@posthog/ui/features/sessions/types";
+import { renderHook } from "@testing-library/react";
+import { act } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useAppBridge } from "./useAppBridge";
+
+const { bridgeInstances, createMockAppBridge, connectGate } = vi.hoisted(() => {
+ // When gated, connect stays pending until the test releases it, so a test
+ // can run a teardown while a connect is in flight.
+ const connectGate = {
+ enabled: false,
+ resolvers: [] as Array<() => void>,
+ enable() {
+ this.enabled = true;
+ },
+ release() {
+ this.enabled = false;
+ for (const resolve of this.resolvers.splice(0)) resolve();
+ },
+ };
+ class MockAppBridge {
+ oninitialized: (() => void) | null = null;
+ sendToolResult = vi.fn();
+ sendToolInput = vi.fn();
+ sendHostContextChange = vi.fn();
+ connect = vi.fn().mockImplementation(() => {
+ if (!connectGate.enabled) return Promise.resolve();
+ return new Promise<void>((resolve) => {
+ connectGate.resolvers.push(resolve);
+ });
+ });
+ sendSandboxResourceReady = vi.fn().mockResolvedValue(undefined);
+ teardownResource = vi.fn().mockResolvedValue(undefined);
+ close = vi.fn().mockResolvedValue(undefined);
+ }
+ const bridgeInstances: MockAppBridge[] = [];
+ function createMockAppBridge() {
+ const instance = new MockAppBridge();
+ bridgeInstances.push(instance);
+ return instance;
+ }
+ return { bridgeInstances, createMockAppBridge, connectGate };
+});
+
+vi.mock("@modelcontextprotocol/ext-apps/app-bridge", () => ({
+ AppBridge: vi.fn().mockImplementation(createMockAppBridge),
+ PostMessageTransport: vi.fn(),
+}));
+
+vi.mock("@posthog/ui/router/useAppView", () => ({
+ getAppViewSnapshot: () => ({ type: "default" }),
+}));
+
+vi.mock("../../message-editor/draftStore", () => ({
+ useDraftStore: {
+ getState: () => ({
+ actions: { setPendingContent: vi.fn(), requestFocus: vi.fn() },
+ }),
+ },
+}));
+
+let latestMessageListener: ((event: MessageEvent) => void) | undefined;
+
+beforeEach(() => {
+ latestMessageListener = undefined;
+ const realAddEventListener = window.addEventListener.bind(window);
+ vi.spyOn(window, "addEventListener").mockImplementation(
+ (type, listener, options) => {
+ if (type === "message") {
+ latestMessageListener = listener as (event: MessageEvent) => void;
+ }
+ return realAddEventListener(
+ type,
+ listener as EventListenerOrEventListenerObject,
+ options,
+ );
+ },
+ );
+});
+
+afterEach(() => {
+ bridgeInstances.length = 0;
+ connectGate.release();
+ vi.restoreAllMocks();
+});
+
+function makeToolCall(overrides: Partial<ToolCall> = {}): ToolCall {
+ return {
+ toolCallId: "tc-1",
+ title: "posthog",
+ kind: "other",
+ status: "completed",
+ rawInput: { foo: "bar" },
+ ...overrides,
+ };
+}
+
+function makeResource(uri: string): McpUiResource {
+ return { uri, mimeType: "text/html", html: "<div/>", serverName: "posthog" };
+}
+
+const fakeIframeEl = {
+ contentWindow: { name: "sandbox-proxy" },
+} as unknown as HTMLIFrameElement;
+
+async function dispatchProxyReady() {
+ await latestMessageListener?.({
+ source: fakeIframeEl.contentWindow,
+ data: { method: "ui/notifications/sandbox-proxy-ready" },
+ } as MessageEvent);
+}
+
+function baseArgs(overrides: Record<string, unknown> = {}) {
+ return {
+ iframeEl: fakeIframeEl,
+ uiResource: makeResource("ui://posthog/query-results.html"),
+ serverName: "posthog",
+ toolName: "exec",
+ toolDefinition: null,
+ toolCall: makeToolCall(),
+ isDarkMode: false,
+ displayMode: "inline" as const,
+ containerWidth: 640,
+ onPhaseChange: vi.fn(),
+ onSizeChange: vi.fn(),
+ onDisplayModeChange: vi.fn(),
+ proxyToolCall: vi.fn(),
+ proxyResourceRead: vi.fn(),
+ openLink: vi.fn(),
+ ...overrides,
+ };
+}
+
+describe("useAppBridge", () => {
+ it("redelivers a result queued before teardown once a new bridge initializes", async () => {
+ const { result, rerender } = renderHook((props) => useAppBridge(props), {
+ initialProps: baseArgs(),
+ });
+
+ await act(async () => {
+ await dispatchProxyReady();
+ });
+ expect(bridgeInstances).toHaveLength(1);
+ const firstBridge = bridgeInstances[0];
+
+ // Not yet initialized, so this only reaches `pendingRef`.
+ act(() => {
+ result.current.sendResultOnce("tc-1", { content: [] });
+ });
+ expect(firstBridge.sendToolResult).not.toHaveBeenCalled();
+
+ rerender(baseArgs({ uiResource: makeResource("ui://posthog/other.html") }));
+
+ await act(async () => {
+ await dispatchProxyReady();
+ });
+ expect(bridgeInstances).toHaveLength(2);
+ const secondBridge = bridgeInstances[1];
+
+ act(() => {
+ result.current.sendResultOnce("tc-1", { content: [] });
+ });
+ act(() => {
+ secondBridge.oninitialized?.();
+ });
+
+ expect(secondBridge.sendToolResult).toHaveBeenCalledTimes(1);
+ expect(firstBridge.sendToolResult).not.toHaveBeenCalled();
+ });
+
+ it("delivers a result immediately once, ignoring a duplicate call for the same toolCallId", async () => {
+ const { result } = renderHook((props) => useAppBridge(props), {
+ initialProps: baseArgs(),
+ });
+
+ await act(async () => {
+ await dispatchProxyReady();
+ });
+ const bridge = bridgeInstances[0];
+
+ act(() => {
+ bridge.oninitialized?.();
+ });
+
+ act(() => {
+ result.current.sendResultOnce("tc-1", { content: [] });
+ result.current.sendResultOnce("tc-1", { content: [] });
+ });
+
+ expect(bridge.sendToolResult).toHaveBeenCalledTimes(1);
+ });
+
+ it("sends an already-completed tool call's result once the app initializes", async () => {
+ renderHook((props) => useAppBridge(props), {
+ initialProps: baseArgs({
+ toolCall: makeToolCall({ rawOutput: { content: [] } }),
+ }),
+ });
+
+ await act(async () => {
+ await dispatchProxyReady();
+ });
+ const bridge = bridgeInstances[0];
+
+ act(() => {
+ bridge.oninitialized?.();
+ });
+
+ expect(bridge.sendToolResult).toHaveBeenCalledTimes(1);
+ });
+
+ it("drops a bridge whose connect finishes after a teardown (regression)", async () => {
+ connectGate.enable();
+ const onPhaseChange = vi.fn();
+ const { rerender } = renderHook((props) => useAppBridge(props), {
+ initialProps: baseArgs({ onPhaseChange }),
+ });
+
+ await act(async () => {
+ // Do not await the listener: with the gate on, it parks at connect.
+ void latestMessageListener?.({
+ source: fakeIframeEl.contentWindow,
+ data: { method: "ui/notifications/sandbox-proxy-ready" },
+ } as MessageEvent);
+ await Promise.resolve();
+ });
+ expect(bridgeInstances).toHaveLength(1);
+ const staleBridge = bridgeInstances[0];
+
+ // The resource changes while connect is still pending, so the effect
+ // that started this bridge tears down.
+ rerender(
+ baseArgs({
+ onPhaseChange,
+ uiResource: makeResource("ui://posthog/other.html"),
+ }),
+ );
+
+ await act(async () => {
+ connectGate.release();
+ });
+
+ expect(staleBridge.sendSandboxResourceReady).not.toHaveBeenCalled();
+ expect(staleBridge.close).toHaveBeenCalled();
+ expect(onPhaseChange).not.toHaveBeenCalledWith("resource-sent");
+ });
+
+ it("does not double-deliver when a result was already queued before the app initializes", async () => {
+ const { result } = renderHook((props) => useAppBridge(props), {
+ initialProps: baseArgs({
+ toolCall: makeToolCall({ rawOutput: { content: [] } }),
+ }),
+ });
+
+ await act(async () => {
+ await dispatchProxyReady();
+ });
+ const bridge = bridgeInstances[0];
+
+ act(() => {
+ result.current.sendResultOnce("tc-1", { content: [] });
+ });
+ expect(bridge.sendToolResult).not.toHaveBeenCalled();
+
+ act(() => {
+ bridge.oninitialized?.();
+ });
+
+ expect(bridge.sendToolResult).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/mcp-apps/hooks/useAppBridge.ts b/products/desktop/packages/ui/src/features/mcp-apps/hooks/useAppBridge.ts
index 2e2dae18d907..71e94658556b 100644
--- a/products/desktop/packages/ui/src/features/mcp-apps/hooks/useAppBridge.ts
+++ b/products/desktop/packages/ui/src/features/mcp-apps/hooks/useAppBridge.ts
@@ -61,6 +61,11 @@ interface UseAppBridgeArgs {
interface UseAppBridgeReturn {
sendWhenReady: (fn: (bridge: AppBridge) => void) => void;
+ /**
+ * Delivers a tool result at most once per `toolCallId`; the sent flag is
+ * bridge-scoped, so a teardown lets the next bridge redeliver it.
+ */
+ sendResultOnce: (toolCallId: string, raw: unknown) => void;
}
const HOST_INFO = { name: "posthog-code", version: "1.0.0" };
@@ -131,6 +136,7 @@ export function useAppBridge(args: UseAppBridgeArgs): UseAppBridgeReturn {
const bridgeRef = useRef<AppBridge | null>(null);
const initializedRef = useRef(false);
const pendingRef = useRef<Array<(bridge: AppBridge) => void>>([]);
+ const sentResultForCallRef = useRef<string | null>(null);
// Single mutable ref for latest props — handlers read from this
const latestRef = useRef(args);
@@ -146,6 +152,24 @@ export function useAppBridge(args: UseAppBridgeArgs): UseAppBridgeReturn {
containerWidth: number;
} | null>(null);
+ const sendWhenReady = useCallback((fn: (bridge: AppBridge) => void) => {
+ if (initializedRef.current && bridgeRef.current) {
+ fn(bridgeRef.current);
+ } else {
+ pendingRef.current.push(fn);
+ }
+ }, []);
+
+ const sendResultOnce = useCallback(
+ (toolCallId: string, raw: unknown) => {
+ if (sentResultForCallRef.current === toolCallId) return;
+ sentResultForCallRef.current = toolCallId;
+ const toolResult = toCallToolResult(raw);
+ sendWhenReady((bridge) => bridge.sendToolResult(toolResult));
+ },
+ [sendWhenReady],
+ );
+
// Main lifecycle effect
useEffect(() => {
if (!iframeEl || !uiResource) {
@@ -283,19 +307,21 @@ export function useAppBridge(args: UseAppBridgeArgs): UseAppBridgeReturn {
});
}
- // If the tool already completed (e.g. component remounted after
- // scrolling back into the virtualized list), send the result now
- // since the subscription event was missed.
+ // Remount after scrolling back into the virtualized list: the
+ // subscription event already fired, so send the stored result.
+ // `sendResultOnce` routes through `sendWhenReady`, so the once-per-id
+ // flag stays in one place; it delivers straight to this bridge (it
+ // is initialized above), or the flush below picks it up on the rare
+ // ordering where the ref is not set yet.
if (
tc.rawOutput &&
(tc.status === "completed" || tc.status === "failed")
) {
- const toolResult = toCallToolResult(tc.rawOutput);
log.debug("Sending existing tool result to app (remount)", {
serverName: latestRef.current.serverName,
- toolResult,
+ toolCallId: tc.toolCallId,
});
- bridge.sendToolResult(toolResult);
+ sendResultOnce(tc.toolCallId, tc.rawOutput);
}
// Flush pending
@@ -314,6 +340,13 @@ export function useAppBridge(args: UseAppBridgeArgs): UseAppBridgeReturn {
iframe.contentWindow as Window,
);
await bridge.connect(transport);
+ // The effect that started this bridge may have torn down while
+ // connect was pending. A stale bridge must not replace the next
+ // effect's bridge in the ref, or a result lands on the old iframe.
+ if (cleanedUp) {
+ bridge.close().catch(() => {});
+ return;
+ }
bridgeRef.current = bridge;
await bridge.sendSandboxResourceReady({
@@ -352,8 +385,14 @@ export function useAppBridge(args: UseAppBridgeArgs): UseAppBridgeReturn {
initializedRef.current = false;
prevContextRef.current = null;
pendingRef.current = [];
+ // Queued results die with this bridge; let the next bridge redeliver.
+ sentResultForCallRef.current = null;
};
- }, [iframeEl, uiResource, args.serverName]); // Only re-run when iframe element or resource identity changes
+ // Effect contract: re-runs only when the iframe or the resource changes.
+ // `sendResultOnce` is listed for the lint rule only: it is referentially
+ // stable (its sole dep, `sendWhenReady`, is stable), so it cannot fire this
+ // effect.
+ }, [iframeEl, uiResource, args.serverName, sendResultOnce]);
// Host context change effect — sends deltas when theme/displayMode/containerWidth change
useEffect(() => {
@@ -397,13 +436,5 @@ export function useAppBridge(args: UseAppBridgeArgs): UseAppBridgeReturn {
}
}, [args.isDarkMode, args.displayMode, args.containerWidth]);
- const sendWhenReady = useCallback((fn: (bridge: AppBridge) => void) => {
- if (initializedRef.current && bridgeRef.current) {
- fn(bridgeRef.current);
- } else {
- pendingRef.current.push(fn);
- }
- }, []);
-
- return { sendWhenReady };
+ return { sendWhenReady, sendResultOnce };
}
diff --git a/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-host-utils.test.ts b/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-host-utils.test.ts
index e465c389c6a4..a86624415a12 100644
--- a/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-host-utils.test.ts
+++ b/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-host-utils.test.ts
@@ -1,3 +1,4 @@
+import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
import { describe, expect, it } from "vitest";
import {
computeContainerDimensions,
@@ -134,4 +135,28 @@ describe("toCallToolResult", () => {
structuredContent: { key: "val" },
});
});
+
+ // Explicit nulls fail the app-side zod schema; see omitNullCallToolResultFields.
+ it.each(["structuredContent", "isError", "_meta"])(
+ "strips %s when it is null, keeping the payload app-schema-valid",
+ (key) => {
+ const raw = {
+ content: [{ type: "text" as const, text: "Date|Pageviews" }],
+ structuredContent: null,
+ isError: null,
+ _meta: null,
+ };
+ const result = toCallToolResult(raw);
+ expect((result as Record<string, unknown>)[key]).toBeUndefined();
+ expect(CallToolResultSchema.safeParse(result).success).toBe(true);
+ expect(CallToolResultSchema.safeParse(raw).success).toBe(false);
+ },
+ );
+
+ it("keeps the object identity when no nullable field needs stripping", () => {
+ const raw = {
+ content: [{ type: "text" as const, text: "hello" }],
+ };
+ expect(toCallToolResult(raw)).toBe(raw);
+ });
});
diff --git a/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-host-utils.ts b/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-host-utils.ts
index 74cae6a4b6d7..db6140936fc2 100644
--- a/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-host-utils.ts
+++ b/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-host-utils.ts
@@ -7,6 +7,7 @@
import type { McpUiDisplayMode } from "@modelcontextprotocol/ext-apps/app-bridge";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
+import { omitNullCallToolResultFields } from "@posthog/shared";
export const INLINE_MAX_HEIGHT = 600;
export const FULLSCREEN_HEADER_HEIGHT = 48;
@@ -40,13 +41,16 @@ export function parseMcpToolKey(mcpToolName: string): {
* where `mcpMeta` may contain `structuredContent` and `_meta`.
*
* This function ensures `content` is always an array while preserving all
- * other fields (structuredContent, _meta, isError) from the raw result.
+ * other fields (structuredContent, _meta, isError) from the raw result. It is
+ * the boundary that owns app validity: every result an MCP App receives
+ * crosses it, whatever source produced it, so the app-side zod schema never
+ * sees an explicit null it would reject (see `omitNullCallToolResultFields`).
*/
export function toCallToolResult(raw: unknown): CallToolResult {
if (raw != null && typeof raw === "object" && "content" in raw) {
const obj = raw as { content: unknown };
if (Array.isArray(obj.content)) {
- return raw as CallToolResult;
+ return omitNullCallToolResultFields(raw as CallToolResult);
}
// content exists but isn't an array — normalize to text block array
// while preserving structuredContent, _meta, isError, etc.
@@ -54,10 +58,10 @@ export function toCallToolResult(raw: unknown): CallToolResult {
typeof obj.content === "string"
? obj.content
: JSON.stringify(obj.content);
- return {
+ return omitNullCallToolResultFields({
...(raw as CallToolResult),
content: [{ type: "text", text }],
- };
+ });
}
// Wrap primitives (e.g. a bare string) into the expected shape
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
index 4a00fe505979..a501e4929aa1 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
@@ -47,6 +47,7 @@ import { ANALYTICS_EVENTS } from "@posthog/shared";
import type { Task } from "@posthog/shared/domain-types";
import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";
import { useSmoothedText } from "@posthog/ui/features/editor/components/useSmoothedText";
+import { hasUiAppResult } from "@posthog/ui/features/mcp-apps/hasUiAppResult";
import type {
BuildResult,
ConversationItem,
@@ -209,12 +210,30 @@ function isThoughtItem(item: ConversationItem): boolean {
);
}
+/**
+ * An item that must render as its own row, never folded into a `ToolGroupItem`:
+ * a plan awaiting approval, a show-actions handoff, or a call whose result
+ * carries a UI app. The next standalone item type joins this predicate instead
+ * of widening the condition at the call site.
+ *
+ * A UI-app call cannot ride in a group, and `keepMounted` on the group body is
+ * not the fix. It would keep every collapsed run's body mounted thread-wide,
+ * and a chart inside a group still stays invisible until the user expands it:
+ * while the run is live the group reads "Thinking…", so a rendered chart would
+ * hide behind a collapsed panel. Keeping the chart outside the group is the
+ * rule that fixes both.
+ */
+function rendersStandalone(item: ConversationItem): boolean {
+ return isPlanItem(item) || isShowActionsItem(item) || hasUiAppResult(item);
+}
+
/**
* Collapse each contiguous run of ≥2 tool-call updates into a single `ToolGroupItem`. A run is
* broken by any *visible* non-tool, non-thought item (prose, status) so groups follow reading
* order; invisible updates (see {@link INVISIBLE_UPDATES}) are transparent and don't split a run.
* A lone tool call passes through untouched as a single marker, and so do the thoughts around it:
- * thoughts ride along a run, they never make one.
+ * thoughts ride along a run, they never make one. A standalone item (see
+ * {@link rendersStandalone}) flushes the run and passes through alone.
*/
/**
* Item arrays for settled runs, keyed on the run's (stable) first item.
@@ -266,7 +285,7 @@ export function groupToolRuns(items: ConversationItem[]): ThreadItem[] {
for (const item of items) {
if (isToolCallItem(item)) {
- if (isPlanItem(item) || isShowActionsItem(item)) {
+ if (rendersStandalone(item)) {
flush();
out.push(item);
continue;
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts
index e0d03f8815ac..872bef5c5435 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts
@@ -121,4 +121,59 @@ describe("groupToolRuns", () => {
]);
expect(out[1]).toMatchObject({ id: "action" });
});
+
+ it("keeps a chart-rendering tool call out of the chip so its UI app never hides behind it", () => {
+ // The group collapses to "Thinking…" while a later call in the run is live,
+ // hiding the already-rendered chart.
+ const chartCall = toolItem("chart", { toolCallId: "chart" });
+ chartCall.turnContext.toolCalls.set("chart", {
+ toolCallId: "chart",
+ title: "chart",
+ kind: "execute",
+ status: "completed",
+ rawOutput: {
+ _meta: { ui: { resourceUri: "ui://posthog/mock-app.html" } },
+ },
+ });
+
+ const out = groupToolRuns([
+ toolItem("before-1"),
+ toolItem("before-2"),
+ chartCall,
+ toolItem("after-1"),
+ toolItem("after-2"),
+ ]);
+
+ expect(out.map((row) => row.type)).toEqual([
+ "tool_group",
+ "session_update",
+ "tool_group",
+ ]);
+ expect(out[1]).toMatchObject({ id: "chart" });
+ });
+
+ it("still groups an MCP tool call whose result has no UI app", () => {
+ const execCall = toolItem("exec", {
+ toolCallId: "exec",
+ _meta: posthogToolMeta({
+ toolName: "mcp__posthog__exec",
+ mcp: { server: "posthog", tool: "exec" },
+ }),
+ });
+ execCall.turnContext.toolCalls.set("exec", {
+ toolCallId: "exec",
+ title: "exec",
+ kind: "execute",
+ status: "completed",
+ rawOutput: { content: [{ type: "text", text: "no chart here" }] },
+ });
+
+ const out = groupToolRuns([
+ toolItem("before"),
+ execCall,
+ toolItem("after"),
+ ]);
+
+ expect(out.map((row) => row.type)).toEqual(["tool_group"]);
+ });
});
diff --git a/products/desktop/packages/ui/src/test/setup.ts b/products/desktop/packages/ui/src/test/setup.ts
index ca0b839d6f4f..6386a7e0654f 100644
--- a/products/desktop/packages/ui/src/test/setup.ts
+++ b/products/desktop/packages/ui/src/test/setup.ts
@@ -123,6 +123,15 @@ Object.defineProperty(window, "matchMedia", {
})),
});
+// jsdom lacks the FontFaceSet API; claim no custom font so buildFontCss
+// takes its fallback branch.
+if (typeof document.fonts === "undefined") {
+ Object.defineProperty(document, "fonts", {
+ configurable: true,
+ value: { check: () => false },
+ });
+}
+
afterEach(() => {
cleanup();
});
diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
index 2e47635f237b..a63c8599dff3 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
@@ -35,6 +35,16 @@ const mockAcpClient = vi.hoisted(() => ({
_meta?: { codeToolKind?: string };
};
}) => Promise<unknown>;
+ sessionUpdate: (params: {
+ update: {
+ sessionUpdate: "tool_call" | "tool_call_update";
+ toolCallId: string;
+ status?: string;
+ rawInput?: unknown;
+ rawOutput?: unknown;
+ _meta?: unknown;
+ };
+ }) => Promise<void>;
}
| undefined,
}));
@@ -588,6 +598,59 @@ describe("AgentService", () => {
});
});
+ describe("MCP tool result forwarding", () => {
+ it.each([
+ [
+ "legacy claudeCode channel (Claude adapter)",
+ { claudeCode: { toolName: "mcp__posthog__query" } },
+ ],
+ [
+ "canonical posthog channel (Codex adapter)",
+ {
+ posthog: {
+ toolName: "mcp__posthog__query",
+ mcp: { server: "posthog", tool: "query" },
+ },
+ },
+ ],
+ ])(
+ "forwards tool input/result to McpAppsService for the %s",
+ async (_label, meta) => {
+ await service.startSession(baseSessionParams);
+
+ await mockAcpClient.current?.sessionUpdate({
+ update: {
+ sessionUpdate: "tool_call",
+ toolCallId: "tc-1",
+ rawInput: { sql: "SELECT 1" },
+ _meta: meta,
+ },
+ });
+ expect(deps.mcpAppsService.notifyToolInput).toHaveBeenCalledWith(
+ "mcp__posthog__query",
+ "tc-1",
+ { sql: "SELECT 1" },
+ );
+
+ await mockAcpClient.current?.sessionUpdate({
+ update: {
+ sessionUpdate: "tool_call_update",
+ toolCallId: "tc-1",
+ status: "completed",
+ rawOutput: { content: [{ type: "text", text: "42 rows" }] },
+ _meta: meta,
+ },
+ });
+ expect(deps.mcpAppsService.notifyToolResult).toHaveBeenCalledWith(
+ "mcp__posthog__query",
+ "tc-1",
+ { content: [{ type: "text", text: "42 rows" }] },
+ false,
+ );
+ },
+ );
+ });
+
describe("reconnect", () => {
it("preserves conversation context when native reconnect fails", async () => {
const apiClient = {};
diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
index e3964292d414..66b5a63de28c 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
@@ -86,6 +86,8 @@ import {
type ExecutionMode,
isAuthError,
type ModelAccess,
+ readAgentToolName,
+ readMcpToolName,
resolveCloudInitialPermissionMode,
serializeError,
TypedEventEmitter,
@@ -151,11 +153,6 @@ function isDevBuild(): boolean {
/** Mark all content blocks as hidden so the renderer doesn't show a duplicate user message on retry */
type MessageCallback = (message: unknown) => void;
-/** Shape of the `_meta.claudeCode` extension field on tool call updates. */
-interface ClaudeCodeToolMeta {
- claudeCode?: { toolName?: string };
-}
-
class NdJsonTap {
private decoder = new TextDecoder();
private buffer = "";
@@ -2204,9 +2201,8 @@ For git operations while detached:
return;
}
- const toolName = (update._meta as ClaudeCodeToolMeta | undefined)
- ?.claudeCode?.toolName;
- if (!toolName?.startsWith("mcp__")) return;
+ const toolName = readMcpToolName(update._meta);
+ if (!toolName) return;
const session = service.sessions.get(taskRunId);
if (update.sessionUpdate === "tool_call") {
@@ -2378,13 +2374,7 @@ For git operations while detached:
params?: {
update?: {
sessionUpdate?: string;
- _meta?: {
- claudeCode?: {
- toolName?: string;
- toolResponse?: unknown;
- bashCommand?: string;
- };
- };
+ _meta?: unknown;
content?: Array<{ type?: string; text?: string }>;
};
};
@@ -2401,8 +2391,7 @@ For git operations while detached:
// toolName (e.g. in terminal output).
this.maybeAttachCreatedPr(taskRunId, session, update);
- const toolMeta = update._meta?.claudeCode;
- const toolName = toolMeta?.toolName;
+ const toolName = readAgentToolName(update._meta);
if (!toolName) return;
this.trackAgentFileActivity(taskRunId, session, toolName);