: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): make interactive apps discoverable in ChatGPT and Codex (#113140)
Daniel Parkerfa8326b0f650
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex db193889809a..969d81d48563 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -363,6 +363,8 @@ Product teams own their definitions and control which operations are exposed asname fails generation instead of silently dropping the argument at runtime.See "UI apps" in `services/mcp/CONTRIBUTING.md` for the rules.+ Some clients display interactive apps with `render-ui`. Apps fetch data through read-only tools such as `query-trends` and `query-funnel`, which stay hidden from the model. After changing tools, refresh the client's tool list and start a new conversation.+A custom UI app can set `resource_domains` when it loads an image, font, script, or stylesheet from an external source. Each value must be a CSP source expression. Declare only the required origin or path.#### Custom input schemasdiff --git a/services/mcp/README.md b/services/mcp/README.mdindex 0aaf43ff337a..977cc151e35b 100644--- a/services/mcp/README.md+++ b/services/mcp/README.md@@ -406,6 +406,12 @@ Then replace `https://mcp.posthog.com/mcp` with `http://localhost:8787/mcp` in tThe server defaults to port **8787**, reads config from `.env` (see `.env.example`), and expects a local Redis on port `6379` for session state; production deployments must set `REDIS_URL` to a TLS-encrypted `rediss://` endpoint.+`render-ui` is available in production for Claude UI hosts and OpenAI's MCP transport used by ChatGPT and Codex. OpenAI's generic plugin-discovery client receives it too, so the cached plugin tool list includes the app tools.++To test MCP Apps locally, run `pnpm run build:ui-apps`. Connect the client to `http://localhost:8787/mcp?mode=cli` and start a fresh chat so it discovers both `exec` and `render-ui`. Use `exec` to resolve an existing entity before calling `render-ui` with its read-only tool and input. Verify that the interactive app renders and fetches its data, as well as that the tool call succeeds. `MCP_APPS_BASE_URL` must point to the local MCP server so its UI assets can load. For ChatGPT web or desktop, expose the MCP server and local PostHog through HTTPS development tunnels. Set `MCP_APPS_BASE_URL` to the MCP tunnel, and `POSTHOG_PUBLIC_URL` to the PostHog tunnel. The local backend's `SITE_URL` must also use the PostHog tunnel so OAuth discovery advertises reachable endpoints. Its development frontend assets must be available over HTTPS. Create a custom MCP plugin in ChatGPT using the MCP tunnel's `/mcp?mode=cli&readonly=true` URL, complete OAuth, and start a fresh chat with that plugin selected. Keep `POSTHOG_API_BASE_URL` pointing to local PostHog. Stop the tunnels after testing. Refresh the plugin's tools after changing the advertised roster, then start a fresh chat.++In single-exec mode, UI hosts also discover the connection's permitted read-only tools with `ui.visibility: ["app"]`. These tools load data and support drill-down inside the visualization; the model continues to use `exec` and `render-ui`. Refresh the custom plugin's tool list after changing these descriptors, then start a fresh chat.+### Session cacheA session's client context lives in one `mcp:s:<id>:c` key with a 24-hour idle expiry, refreshed on every request in the session.diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex 197fa6d5e894..3b03a0735178 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -188,10 +188,7 @@ export class RequestStateResolver {userAgent: props.clientUserAgent,})- // `render-ui` is only meaningful for MCP Apps hosts (Claude web/desktop) that can- // mount its iframe. Single-exec CLI clients like Claude Code can't mount it, so the- // tool's advertisement and execution stay gated on the UI-host check.- const renderUiEnabled = clientProfile.isClaudeUiHost()+ const renderUiEnabled = clientProfile.isRenderUiHost()const { mode: resolvedMode, useSingleExec } = resolveMode({mode: requestContext.mode,diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex b9a80b5801b8..4164287e0f2a 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -89,8 +89,8 @@ interface ExecMetricState {** CLI-mode clients read `content[].text`, so for them the structured copy only adds* tokens. A render-ui host in single-exec mode is the exception, because there- * `buildAdvertisedTools` offers `exec` and `render-ui` only, and `handleToolCall` routes- * both of those before this path. Any other tool name that reaches here is therefore the+ * `buildAdvertisedTools` offers `exec` and `render-ui` to the model, and `handleToolCall`+ * routes both of those before this path. Any other tool name that reaches here is therefore the* render-ui app calling `callServerTool` to load its own data. That app reads* `structuredContent` and ignores the text channel, so dropping the structured payload* leaves it with nothing to draw, and it shows its error state instead of the chart. The@@ -157,7 +157,23 @@ export class ToolExecutor {// Guarded because analytics must never break `tools/list`.private injectAnalyticsParameters(tools: ListToolsResult['tools']): ListToolsResult['tools'] {try {- return getPostHogClient().prepareToolList(tools)+ return getPostHogClient()+ .prepareToolList(tools)+ .map((tool) => {+ const visibility = (tool._meta?.ui as { visibility?: unknown } | undefined)?.visibility+ if (!Array.isArray(visibility) || visibility.length !== 1 || visibility[0] !== 'app') {+ return tool+ }+ return {+ ...tool,+ inputSchema: {+ ...tool.inputSchema,+ required: tool.inputSchema.required?.filter(+ (name) => name !== 'context' && name !== 'llm_model'+ ),+ },+ }+ })} catch {return tools}@@ -166,7 +182,36 @@ export class ToolExecutor {private buildAdvertisedTools(state: ResolvedState): ListToolsResult['tools'] {if (state.useSingleExec) {const renderUiEntry = state.renderUiEnabled ? this.instructionsBuilder.buildRenderUiToolEntry(state) : null- return [this.instructionsBuilder.buildExecToolEntry(state), ...(renderUiEntry ? [renderUiEntry] : [])]+ // Hosts authorize app calls against tools/list, including tools hidden from the model.+ const appToolNames = new Set(+ renderUiEntry+ ? state.allTools.filter((tool) => tool.annotations.readOnlyHint).map((tool) => tool.name)+ : []+ )+ const appTools = this.catalog+ .getPreBuiltEntries()+ .filter((entry) => appToolNames.has(entry.name))+ .map((entry) => {+ const uiMeta = entry._meta?.ui+ return {+ ...entry,+ description: `Load ${entry.name} data for a PostHog app.`,+ // Omit generated query schemas to limit discovery size; calls still use the full validator.+ inputSchema: { type: 'object' as const, additionalProperties: true },+ _meta: {+ ...entry._meta,+ ui: {+ ...(uiMeta && typeof uiMeta === 'object' ? uiMeta : {}),+ visibility: ['app'],+ },+ },+ }+ })+ return [+ this.instructionsBuilder.buildExecToolEntry(state),+ ...(renderUiEntry ? [renderUiEntry] : []),+ ...appTools,+ ]}const nameSet = new Set(state.allTools.map((t) => t.name))diff --git a/services/mcp/src/lib/client-detection.ts b/services/mcp/src/lib/client-detection.tsindex cc37a50b6fe7..f93b8fbb95b6 100644--- a/services/mcp/src/lib/client-detection.ts+++ b/services/mcp/src/lib/client-detection.ts@@ -26,8 +26,7 @@* sent by the PostHog Desktop Tasks wrapper.** - `isClaudeUiHost()` matches Claude web/desktop and Cowork — MCP Apps hosts- * that render interactive UI (iframes). Used to advertise the `render-ui`- * tool to them.+ * that render interactive UI (iframes).** - `isClaudeChatHost()` matches Claude web/desktop only — the chat surfaces that* report `supportsInstructions` but never surface the `instructions` payload to@@ -332,6 +331,12 @@ export class MCPClientProfile {return matchesAnyFragment(this.userAgent, ANTHROPIC_UI_HOST_USER_AGENT_FRAGMENTS)}+ isRenderUiHost(): boolean {+ // OpenAI caches a shared roster, so generic discovery must also include render-ui.+ const isOpenAiTransport = (value: string | undefined): boolean => /^openai-mcp(?:[\s/(]|$)/i.test(value ?? '')+ return this.isClaudeUiHost() || isOpenAiTransport(this.clientName) || isOpenAiTransport(this.userAgent)+ }+isInlineExecUiHost(): boolean {// Claude Code renders MCP UI apps inline on the single-exec `exec` tool, while// Claude.ai and Cowork render through the separate `render-ui` tool.diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsindex 3e407f80c9bc..397424a67c3b 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'const {mockSessionStore,@@ -165,6 +165,10 @@ function makeResolverWithCatalog(): {}describe('RequestStateResolver MCP client contexts', () => {+ afterEach(() => {+ vi.unstubAllEnvs()+ })+beforeEach(() => {mockSessionStore.clear()mockTokenStore.clear()@@ -444,6 +448,31 @@ describe('RequestStateResolver MCP client contexts', () => {expect(result.useSingleExec).toBe(true)})+ it.each([+ { mcpClientName: 'openai-mcp' },+ { mcpClientName: 'openai-mcp (Codex)' },+ { mcpClientName: 'openai-mcp (ChatGPT)' },+ { mcpClientName: undefined, clientUserAgent: 'openai-mcp/1.0.0 (Codex)' },+ { mcpClientName: undefined, clientUserAgent: 'openai-mcp/1.0.0 (ChatGPT)' },+ { mcpClientName: undefined, clientUserAgent: 'openai-mcp/1.0.0' },+ ])('enables production render-ui for OpenAI transport %j', async (identity) => {+ vi.stubEnv('NODE_ENV', 'production')+ const result = await makeResolver().resolve(makeProps(identity))++ expect(result.renderUiEnabled).toBe(true)+ expect(result.useSingleExec).toBe(true)+ })++ it.each(['codex', 'codex-mcp-client'])(+ 'does not enable render-ui for terminal client %s',+ async (mcpClientName) => {+ const result = await makeResolver().resolve(makeProps({ mcpClientName }))++ expect(result.renderUiEnabled).toBe(false)+ expect(result.useSingleExec).toBe(true)+ }+ )+it('detects Claude web/desktop via the Claude-User user agent and enables render-ui', async () => {const props = makeProps({ mcpClientName: 'Claude Desktop', clientUserAgent: 'Claude-User' })const result = await makeResolver().resolve(props)diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.tsindex 1b7963d83208..fdb56cbe7023 100644--- a/services/mcp/tests/hono/tool-executor-intent.test.ts+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts@@ -187,6 +187,54 @@ describe('ToolExecutor analytics capture', () => {expect(state.context.api.config.onPrivateResponse).toBeUndefined()})+ it.each([false, true])('captures optional app analytics when supplied=%s', async (supplied) => {+ const capture = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})+ const tool = {+ name: 'projects-get',+ title: 'Read projects',+ description: 'Synthetic project read',+ scopes: [],+ annotations: { readOnlyHint: true },+ schema: z.object({}).strict(),+ handler: vi.fn(async () => ({ results: [] })),+ }+ vi.spyOn(catalog, 'getToolByName').mockReturnValue({+ build: () => tool,+ meta: undefined,+ rawInputSchema: undefined,+ definition: undefined,+ })+ vi.spyOn(catalog, 'getPreBuiltEntries').mockReturnValue([+ { name: tool.name, description: tool.description, inputSchema: { type: 'object' } },+ ])+ vi.spyOn(InstructionsBuilder.prototype, 'buildRenderUiToolEntry').mockReturnValue({+ name: 'render-ui',+ inputSchema: { type: 'object' },+ })+ const state = makeToolExecutorState([tool], { useSingleExec: true, renderUiEnabled: true })+ const listed = await executor.handleToolsList(state)+ const appTool = listed.tools.find((entry) => entry.name === tool.name)!+ expect(appTool.inputSchema.properties).toHaveProperty('context')+ expect(appTool.inputSchema.properties).toHaveProperty('llm_model')+ expect(appTool.inputSchema.required ?? []).not.toContain('context')+ expect(appTool.inputSchema.required ?? []).not.toContain('llm_model')++ const result = await executor.handleToolCall(+ {+ name: tool.name,+ arguments: supplied ? { context: 'Compare synthetic projects', llm_model: 'example-model' } : {},+ },+ state+ )+ expect(result).not.toHaveProperty('isError', true)+ expect(tool.handler).toHaveBeenCalledWith(expect.anything(), {})+ expect(capture).toHaveBeenCalledOnce()+ const captured = capture.mock.calls[0]![0]+ expect(captured.toolName).toBe(tool.name)+ expect(captured.intent).toBe(supplied ? 'Compare synthetic projects' : undefined)+ expect(captured.llmModel).toBe(supplied ? 'example-model' : undefined)+ })+it('injects the analytics arguments into advertised tools', async () => {const state = makeToolExecutorState([], { useSingleExec: true })diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex ee0617941d8e..f5e176b698c2 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -634,10 +634,26 @@ describe('ToolExecutor', () => {})it('lists render-ui alongside exec when render-ui is enabled and a UI-app tool is available', async () => {- const state = makeToolExecutorState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })+ const tools = [+ uiAppTool,+ { name: 'query-trends', annotations: { readOnlyHint: true } },+ { name: 'survey-create', annotations: { readOnlyHint: false } },+ ]+ const state = makeToolExecutorState(tools, { useSingleExec: true, renderUiEnabled: true })const result = await executor.handleToolsList(state)- expect(result.tools.map((t) => t.name)).toEqual(['exec', 'render-ui'])+ expect(result.tools.map((t) => t.name)).toEqual(+ expect.arrayContaining(['exec', 'render-ui', 'survey-get', 'query-trends'])+ )+ expect(result.tools).toHaveLength(4)+ for (const name of ['survey-get', 'query-trends']) {+ const appTool = result.tools.find((tool) => tool.name === name)!+ expect(appTool._meta?.ui).toMatchObject({+ visibility: ['app'],+ })+ expect(appTool.inputSchema.required ?? []).not.toContain('context')+ expect(appTool.inputSchema.required ?? []).not.toContain('llm_model')+ }// Pin the complete advertised schema because clients generate// render-ui calls from this list response.