: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): expose render-ui to clients with ui support (#123390)
Daniel Parker9eb751a89aec
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex 76e62b5c047e..f99e4e10eee2 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -310,6 +310,22 @@ after ten minutes and are bound to the authenticated user, PostHog instance, invtoken. They remain valid after project changes or flag changes because they cannot execute a tool.Duplicate, expired, and mismatched replies do not update suppression or emit response events.+## MCP UI hosts++In CLI mode, MCP Apps UI hosts receive a separate `render-ui` tool beside `exec`.+A client declares UI support with the `extensions["io.modelcontextprotocol/ui"]` capability.+The client supports `render-ui` when that capability lists `text/html;profile=mcp-app` in `mimeTypes`.+If the client sends the capability, the server uses it, and it overrides name detection in both directions.+If the client does not send the capability, the server falls back to known hosts: Claude web and desktop, Cowork, and the exact `openai-mcp` client name or user agent product.+The OpenAI match is exact, so Codex CLI (`codex-mcp-client`) does not receive `render-ui` without a declaration.+Legacy clients declare capabilities during `initialize`; the server retains UI support for later requests in that session.+Stateless clients declare capabilities in each request's `_meta["io.modelcontextprotocol/clientCapabilities"]`.+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.+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 budgetClaude web and desktop silently drop a tool when its serialized `inputSchema` reaches 16,384 characters, so the final `exec` input schema has a test budget below that limit.diff --git a/services/mcp/src/hono/cache/McpSessionRedisStore.ts b/services/mcp/src/hono/cache/McpSessionRedisStore.tsindex 60184baffc14..d7ea835b0956 100644--- a/services/mcp/src/hono/cache/McpSessionRedisStore.ts+++ b/services/mcp/src/hono/cache/McpSessionRedisStore.ts@@ -10,6 +10,7 @@ const SESSION_CONTEXT_KEYS = ['mcpClientVersion','mcpProtocolVersion','mcpElicitationUrlSupported',+ 'mcpUiSupported','mcpConsumer','mcpVendorClient',] as constdiff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.tsindex c9bb7ffb4ba5..fd6f14b0c34c 100644--- a/services/mcp/src/hono/instructions.ts+++ b/services/mcp/src/hono/instructions.ts@@ -110,8 +110,8 @@ export class InstructionsBuilder {}}- buildRenderUiToolEntry(state: ResolvedState): McpTool | null {- const toolNames = getRenderableToolNames(state.allTools)+ buildRenderUiToolEntry(tools: McpTool[]): McpTool | null {+ const toolNames = getRenderableToolNames(tools)if (toolNames.length === 0) {return null}@@ -119,8 +119,7 @@ export class InstructionsBuilder {name: RENDER_UI_TOOL_NAME,title: RENDER_UI_TOOL_TITLE,description: renderUiDescription(toolNames),- // Derived from the same zod schema the executor validates with, so the- // advertised contract (enum, descriptions, required) cannot drift from it.+ // OpenAI caches this schema across accounts; authorization stays in the executor.inputSchema: toMcpInputSchema(makeRenderUiSchema(toolNames as [string, ...string[]])),// Advertise the umbrella UI resource so MCP Apps hosts (e.g. Claude) discover// render-ui as renderable from `tools/list` and mount its iframe. Both thediff --git a/services/mcp/src/hono/mcp-context.ts b/services/mcp/src/hono/mcp-context.tsindex bf4c3617f158..f56a3fe87629 100644--- a/services/mcp/src/hono/mcp-context.ts+++ b/services/mcp/src/hono/mcp-context.ts@@ -10,6 +10,7 @@ export interface MCPClientContext extends Pick<| 'mcpConsumer'| 'mcpVendorClient'| 'mcpElicitationUrlSupported'+ | 'mcpUiSupported'> {}export interface MCPRequestContext@@ -50,6 +51,7 @@ export function buildMCPRequestContext(props: RequestProperties): MCPRequestContmcpClientVersion: props.mcpClientVersion,mcpProtocolVersion: props.mcpProtocolVersion,mcpElicitationUrlSupported: props.mcpElicitationUrlSupported,+ mcpUiSupported: props.mcpUiSupported,transport: props.transport,mcpSessionId: props.mcpSessionId,mcpConversationId: props.mcpConversationId,diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex 39f51c59b186..85143eb079c2 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -279,12 +279,10 @@ export class RequestStateResolver {oauthClientName: oauthClientName || undefined,vendorClient: clientContext.mcpVendorClient,userAgent: props.clientUserAgent,+ uiSupported: requestContext.mcpUiSupported ?? sessionContext?.mcpUiSupported,})- // `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/request-utils.ts b/services/mcp/src/hono/request-utils.tsindex a9b47527ac81..87fa4dd1e3f6 100644--- a/services/mcp/src/hono/request-utils.ts+++ b/services/mcp/src/hono/request-utils.ts@@ -1,3 +1,4 @@+import { getUiCapability, RESOURCE_MIME_TYPE } from '@modelcontextprotocol/ext-apps/server'import { z } from 'zod'import { classifyAuthFailure, mapErrorToAuthResponse, validateBearerToken } from '@/lib/auth-errors'@@ -9,7 +10,7 @@ import {type Transport,} from '@/lib/request-properties'import { getRegionFromRequest } from '@/lib/routing'-import { parseRequestProtocolMeta } from '@/lib/stateless-protocol'+import { META_CLIENT_CAPABILITIES, parseRequestProtocolMeta } from '@/lib/stateless-protocol'import { extractBearerToken, sanitizeHeaderValue } from '@/lib/utils'import { trackAuthFailure } from './analytics'@@ -34,6 +35,18 @@ const JsonRpcMessageSchema = z.object({params: z.unknown().optional(),})+function parseUiCapabilities(capabilities: unknown): Pick<ClientInfo, 'uiSupported'> {+ const parsed = z+ .object({ extensions: z.record(z.string(), z.record(z.string(), z.unknown())).optional() })+ .safeParse(capabilities)+ const uiCapability = getUiCapability(parsed.success ? parsed.data : undefined)+ if (uiCapability === undefined) {+ return { uiSupported: undefined }+ }+ const ui = z.object({ mimeTypes: z.array(z.string()).optional() }).safeParse(uiCapability)+ return { uiSupported: ui.success && ui.data.mimeTypes?.includes(RESOURCE_MIME_TYPE) === true }+}+function parseClientInfo(bodyText: string): ClientInfo {try {const parsed = JSON.parse(bodyText)@@ -59,15 +72,22 @@ function parseClientInfo(bodyText: string): ClientInfo {elicitationUrlSupported: z.object({ elicitation: z.object({ url: z.object({}) }) }).safeParse(params.data.capabilities).success,+ ...parseUiCapabilities(params.data.capabilities),}}if (!metaFallback) {const meta = parseRequestProtocolMeta(rpc.data.params)if (meta.protocolVersion || meta.clientName) {+ const params = z+ .object({ _meta: z.record(z.string(), z.unknown()).optional() })+ .safeParse(rpc.data.params)metaFallback = {clientName: sanitizeHeaderValue(meta.clientName),clientVersion: sanitizeHeaderValue(meta.clientVersion),protocolVersion: sanitizeHeaderValue(meta.protocolVersion),+ ...parseUiCapabilities(+ params.success ? params.data._meta?.[META_CLIENT_CAPABILITIES] : undefined+ ),}}}diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex d04a1097034b..6184b1791078 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -191,7 +191,9 @@ export class ToolExecutor {private buildAdvertisedTools(state: ResolvedState): ListToolsResult['tools'] {if (state.useSingleExec) {- const renderUiEntry = state.renderUiEnabled ? this.instructionsBuilder.buildRenderUiToolEntry(state) : null+ const renderUiEntry = state.renderUiEnabled+ ? this.instructionsBuilder.buildRenderUiToolEntry(this.catalog.getPreBuiltEntries())+ : nullreturn [this.instructionsBuilder.buildExecToolEntry(state), ...(renderUiEntry ? [renderUiEntry] : [])]}@@ -215,7 +217,7 @@ export class ToolExecutor {return this.instructionsBuilder.buildExecToolEntry(state)}if (toolName === 'render-ui' && state.renderUiEnabled) {- return this.instructionsBuilder.buildRenderUiToolEntry(state) ?? undefined+ return this.instructionsBuilder.buildRenderUiToolEntry(this.catalog.getPreBuiltEntries()) ?? undefined}return undefined}diff --git a/services/mcp/src/lib/client-detection.ts b/services/mcp/src/lib/client-detection.tsindex cc37a50b6fe7..049c9eb4a3a3 100644--- a/services/mcp/src/lib/client-detection.ts+++ b/services/mcp/src/lib/client-detection.ts@@ -25,9 +25,9 @@* - `isPostHogCodeConsumer()` matches the `x-posthog-mcp-consumer` header* 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.+ * - `isRenderUiHost()` uses declared MCP Apps support when the client sends it.+ * Otherwise it matches Claude web/desktop, Cowork, and the exact `openai-mcp`+ * client name.** - `isClaudeChatHost()` matches Claude web/desktop only — the chat surfaces that* report `supportsInstructions` but never surface the `instructions` payload to@@ -54,6 +54,11 @@ function matchesAnyFragment(clientName: string | undefined, fragments: readonlyreturn fragments.some((fragment) => normalized.includes(normalizeClientName(fragment)))}+function matchesProductName(value: string | undefined, names: readonly string[]): boolean {+ const product = value?.trim().split(/[\s/]/, 1)[0]?.toLowerCase()+ return !!product && names.includes(product)+}+// Coding agents and LLM-driven clients that render text rather than MCP Apps UI.// Matched by `isCliModeEnabled()`, which gates dropping `structuredContent` when a// `formatted_results` override is set. Mode selection does NOT read this list — CLI@@ -204,6 +209,12 @@ export const INLINE_EXEC_UI_APP_VENDOR_FRAGMENTS = ['claudecode'] as constexport const ANTHROPIC_USER_AGENT_FRAGMENTS = ['claude-user'] as constexport const ANTHROPIC_UI_HOST_USER_AGENT_FRAGMENTS = ANTHROPIC_USER_AGENT_FRAGMENTS+// OpenAI clients send no vendor header, so the shared `openai-mcp` client is matched+// on `clientInfo.name` or the User-Agent product token. The match is exact because a+// substring match on `codex` also matches Codex CLI (`codex-mcp-client`), which cannot+// render UI.+export const OPENAI_RENDER_UI_CLIENT_NAMES = ['openai-mcp'] 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@@ -244,6 +255,7 @@ type MCPClientProfileInput = {vendorClient?: string | undefined// Per-request `User-Agent` (e.g. `Claude-User` for Claude web/desktop).userAgent?: string | undefined+ uiSupported?: boolean | undefined}export class MCPClientProfile {@@ -253,6 +265,7 @@ export class MCPClientProfile {readonly oauthClientName: string | undefinedreadonly vendorClient: string | undefinedreadonly userAgent: string | undefined+ readonly uiSupported: boolean | undefinedprivate _capabilities: ClientCapabilities | undefined@@ -263,6 +276,7 @@ export class MCPClientProfile {this.oauthClientName = input.oauthClientNamethis.vendorClient = input.vendorClientthis.userAgent = input.userAgent+ this.uiSupported = input.uiSupported}isToolsModeClient(): boolean {@@ -294,7 +308,7 @@ export class MCPClientProfile {// is the reliable signal of the live product when present. Some surfaces// (Claude.ai web/desktop, internal tools) connect without that header, so// also accept the `Claude-User` user-agent and the pooled `Anthropic/…`- // `clientInfo.name`. Unlike `isClaudeUiHost`, matching the pooled name here+ // `clientInfo.name`. Unlike `isRenderUiHost`, matching the pooled name here// is safe and intended: every Anthropic product belongs in CLI mode, so// there is nothing to misclassify.return matchesAnyFragment(this.vendorClient, ANTHROPIC_CLIENT_NAME_FRAGMENTS) || this.isAnthropicConnector()@@ -316,20 +330,30 @@ export class MCPClientProfile {return this.consumer === POSTHOG_CODE_CONSUMER}- isClaudeUiHost(): boolean {+ isRenderUiHost(): boolean {+ // 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+ }// The per-request vendor client (`x-anthropic-client`) is authoritative: it// distinguishes the Claude surfaces that pool the same MCP transport —// `ClaudeAI` (web/desktop) and `Cowork`, both `render-ui` hosts, from// `ClaudeCode`, which only renders UI apps inline on the `exec` response// (see `isInlineExecUiHost`). When it's present, trust it exclusively; only- // fall back to the `Claude-User` user-agent when the vendor header is+ // fall back to the user-agent and client name when the vendor header is// absent. Otherwise a non-render-ui surface like Claude Code — which can// share the `Claude-User` user-agent with web/desktop — would be// misclassified as a UI host.if (this.vendorClient) {return matchesAnyFragment(this.vendorClient, ANTHROPIC_UI_HOST_VENDOR_FRAGMENTS)}- return matchesAnyFragment(this.userAgent, ANTHROPIC_UI_HOST_USER_AGENT_FRAGMENTS)+ return (+ matchesAnyFragment(this.userAgent, ANTHROPIC_UI_HOST_USER_AGENT_FRAGMENTS) ||+ matchesProductName(this.userAgent, OPENAI_RENDER_UI_CLIENT_NAMES) ||+ matchesProductName(this.clientName, OPENAI_RENDER_UI_CLIENT_NAMES)+ )}isInlineExecUiHost(): boolean {@@ -342,7 +366,7 @@ export class MCPClientProfile {}isClaudeChatHost(): boolean {- // Same vendor-authoritative shape as `isClaudeUiHost`, narrowed to the chat+ // Same vendor-authoritative shape as `isRenderUiHost`, narrowed to the chat// surfaces (Claude web/desktop) that ignore the `instructions` payload. The// `Claude-User` user-agent fallback is kept for requests without the vendor// header — those are predominantly chat sessions, and keeping env-context@@ -389,10 +413,3 @@ export function isPostHogCodeConsumer(mcpConsumer: string | undefined): booleanexport function isToolsModeClient(clientName: string | undefined, userAgent?: string | undefined): boolean {return new MCPClientProfile({ clientName, userAgent }).isToolsModeClient()}--export function isClaudeUiHostClient(args: {- vendorClient?: string | undefined- userAgent?: string | undefined-}): boolean {- return new MCPClientProfile(args).isClaudeUiHost()-}diff --git a/services/mcp/src/lib/request-properties.ts b/services/mcp/src/lib/request-properties.tsindex 91dbd140313b..95ed36efed65 100644--- a/services/mcp/src/lib/request-properties.ts+++ b/services/mcp/src/lib/request-properties.ts@@ -23,6 +23,7 @@ export type RequestProperties = {mcpClientName?: string | undefinedmcpClientVersion?: string | undefinedmcpElicitationUrlSupported?: boolean | undefined+ mcpUiSupported?: boolean | undefinedmcpProtocolVersion?: string | undefinedmcpVendorClient?: string | undefinedreadOnly?: boolean | undefined@@ -53,6 +54,7 @@ export type ClientInfo = {clientVersion?: string | undefinedprotocolVersion?: string | undefinedelicitationUrlSupported?: boolean | undefined+ uiSupported?: boolean | undefined}function header(request: Request, name: string): string | undefined {@@ -124,6 +126,7 @@ export function parseRequestProperties(mcpClientVersion: clientInfo.clientVersion,mcpProtocolVersion: clientInfo.protocolVersion,mcpElicitationUrlSupported: clientInfo.elicitationUrlSupported,+ mcpUiSupported: clientInfo.uiSupported,mcpVendorClient: vendorClient,mode: viaMcpStore ? 'tools' : parseMcpMode(header(request, 'x-posthog-mcp-mode') || params.get('mode')),viaMcpStore,diff --git a/services/mcp/src/tools/render-ui.ts b/services/mcp/src/tools/render-ui.tsindex dc04f6c8d33e..991cb994c095 100644--- a/services/mcp/src/tools/render-ui.ts+++ b/services/mcp/src/tools/render-ui.ts@@ -1,4 +1,5 @@import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'+import type { Tool as McpTool } from '@modelcontextprotocol/sdk/types.js'import { z } from 'zod'import { markExecPayload, type ToolResultPayload } from '@/lib/build-tool-result'@@ -26,12 +27,12 @@ const URI_TO_APP_KEY = new Map<string, UiAppKey>(const DISPATCHABLE = new Set<UiAppKey>(DISPATCHABLE_APP_KEYS)/** The dispatchable app key for a tool, or undefined when it has no renderable UI app. */-function toDispatchableAppKey(tool: Tool<ZodObjectAny>): UiAppKey | undefined {- const resourceUri = tool._meta?.ui?.resourceUri- if (!resourceUri) {+function toDispatchableAppKey(tool: Pick<McpTool, '_meta'>): UiAppKey | undefined {+ const ui = tool._meta?.ui+ if (!ui || typeof ui !== 'object' || !('resourceUri' in ui) || typeof ui.resourceUri !== 'string') {return undefined}- const appKey = URI_TO_APP_KEY.get(resourceUri)+ const appKey = URI_TO_APP_KEY.get(ui.resourceUri)return appKey && DISPATCHABLE.has(appKey) ? appKey : undefined}@@ -40,15 +41,14 @@ function toDispatchableAppKey(tool: Tool<ZodObjectAny>): UiAppKey | undefined {* Restricted to read-only tools: `render-ui` is annotated read-only, so it must not be a* back door for dispatching state-changing tools (e.g. `survey-launch`, `workflows-create`).*/-export function getRenderableToolNames(allTools: Tool<ZodObjectAny>[]): string[] {+export function getRenderableToolNames(allTools: Pick<McpTool, 'name' | 'annotations' | '_meta'>[]): string[] {return allTools- .filter((tool) => tool.annotations.readOnlyHint && toDispatchableAppKey(tool) !== undefined)+ .filter((tool) => tool.annotations?.readOnlyHint && toDispatchableAppKey(tool) !== undefined).map((tool) => tool.name)}-/** Single source of truth for the `render-ui` input contract — the executor- * validates with it, and `buildRenderUiToolEntry` derives the advertised- * `tools/list` schema from it, so the two cannot drift. */+/** OpenAI caches the advertised catalog across accounts, so execution must+ * validate the same input shape against the current account's allowed tools. */export function makeRenderUiSchema(toolNames: [string, ...string[]]): z.ZodObject<{ tool_name: z.ZodEnum<Record<string, string>>; tool_input: z.ZodOptional<z.ZodRecord> }> {diff --git a/services/mcp/tests/hono/mcp-protocol.test.ts b/services/mcp/tests/hono/mcp-protocol.test.tsindex f0b1a04fff8c..1d2fecda6e9a 100644--- a/services/mcp/tests/hono/mcp-protocol.test.ts+++ b/services/mcp/tests/hono/mcp-protocol.test.ts@@ -1,5 +1,6 @@+import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'import { setupServer } from 'msw/node'-import { afterAll, beforeAll } from 'vitest'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { createApp } from '@/hono/app'import type { RedisLike } from '@/hono/cache/RedisCache'@@ -92,3 +93,48 @@ defineCatalogFilterTests('Hono', harness)defineExecModeTests('Hono', harness)defineSessionTrackingTests('Hono', harness)defineStatelessProtocolTests('Hono', harness)++describe.each(['2025-11-25', '2026-07-28'] as const)('MCP UI capability negotiation on %s', (version) => {+ it.each([+ { name: 'example-client', mimeTypes: ['text/html;profile=mcp-app'], supported: true },+ { name: 'openai-mcp', mimeTypes: undefined, supported: true },+ { name: 'example-client', mimeTypes: undefined, supported: false },+ { name: 'ChatGPT', mimeTypes: ['text/html'], supported: false },+ ])('gates tool discovery and cached calls for %j', async ({ name, mimeTypes, supported }) => {+ const client = new Client(+ { name, version: '1.0' },+ {+ capabilities: { extensions: mimeTypes ? { 'io.modelcontextprotocol/ui': { mimeTypes } } : {} },+ versionNegotiation: { mode: version === '2026-07-28' ? { pin: version } : 'legacy' },+ }+ )+ const transport = new StreamableHTTPClientTransport(new URL('https://hono.test/mcp'), {+ fetch: async (input, init) =>+ app.fetch(+ new Request(input, {+ ...init,+ headers: {+ ...Object.fromEntries(new Headers(init?.headers)),+ Authorization: 'Bearer phx_integration_test_token',+ },+ })+ ),+ })+ try {+ await client.connect(transport)+ const { tools } = await client.listTools()+ expect(tools.some((tool) => tool.name === 'render-ui')).toBe(supported)++ const result = await client.callTool({+ name: 'render-ui',+ arguments: { tool_name: 'survey-get', tool_input: { surveyId: 'synthetic-survey' } },+ })+ expect(result.isError === true).toBe(!supported)+ if (supported) {+ expect(result._meta).toMatchObject({ ui: { resourceUri: 'ui://posthog/render-ui.html' } })+ }+ } finally {+ await client.close()+ }+ })+})diff --git a/services/mcp/tests/hono/mcp-session-redis-store.test.ts b/services/mcp/tests/hono/mcp-session-redis-store.test.tsindex 9ec121e1a13c..fe5be4776ed7 100644--- a/services/mcp/tests/hono/mcp-session-redis-store.test.ts+++ b/services/mcp/tests/hono/mcp-session-redis-store.test.ts@@ -34,6 +34,7 @@ const liveContext: MCPClientContext = {mcpClientVersion: '1.2.3',mcpProtocolVersion: '2025-11-25',mcpElicitationUrlSupported: true,+ mcpUiSupported: true,mcpConsumer: 'posthog-code',mcpVendorClient: 'ClaudeCode',}@@ -57,13 +58,16 @@ describe('McpSessionRedisStore', () => {expect(JSON.parse(redis.store.get(compactKeyIn(redis))!)).toEqual(liveContext)})- it.each([true, false])('preserves URL support %s on a later request that carries none', async (supported) => {- const store = new McpSessionRedisStore(redis, 'session-1')- const context = { ...liveContext, mcpElicitationUrlSupported: supported }- await store.resolve(context)+ it.each([true, false])(+ 'preserves capability support %s on a later request that carries none',+ async (supported) => {+ const store = new McpSessionRedisStore(redis, 'session-1')+ const context = { ...liveContext, mcpElicitationUrlSupported: supported, mcpUiSupported: supported }+ await store.resolve(context)- expect(await new McpSessionRedisStore(redis, 'session-1').resolve({})).toEqual(context)- })+ expect(await new McpSessionRedisStore(redis, 'session-1').resolve({})).toEqual(context)+ }+ )it('serves live context instead of throwing when the compact read fails', async () => {vi.mocked(redis.get).mockRejectedValue(new Error('Valkey read failed'))diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsindex 9db3b58c0af5..70f9814d785d 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -46,7 +46,14 @@ vi.mock('@/lib/posthog/flags', () => ({vi.mock('@/hono/cache/McpSessionRedisStore', () => ({McpSessionRedisStore: class {async resolve(requestContext: Record<string, unknown>): Promise<Record<string, unknown>> {- const keys = ['mcpClientName', 'mcpClientVersion', 'mcpProtocolVersion', 'mcpConsumer', 'mcpVendorClient']+ const keys = [+ 'mcpClientName',+ 'mcpClientVersion',+ 'mcpProtocolVersion',+ 'mcpConsumer',+ 'mcpVendorClient',+ 'mcpUiSupported',+ ]const resolved = Object.fromEntries(keys.map((key) => [key, mockSessionStore.get(key) ?? requestContext[key]]))@@ -465,6 +472,7 @@ describe('RequestStateResolver MCP client contexts', () => {const result = await makeResolver().resolve(props)expect(result.useSingleExec).toBe(true)+ expect(result.renderUiEnabled).toBe(false)expect(props.mode).toBe('cli')})@@ -546,8 +554,14 @@ describe('RequestStateResolver MCP client contexts', () => {expect(mockSessionStore.get('mcpVendorClient')).toBe('ClaudeCode')})- it('puts Claude web/desktop in single-exec and enables render-ui', async () => {- const props = makeProps({ mcpClientName: 'Claude Desktop', mcpVendorClient: 'ClaudeAI' })+ it.each([+ { mcpClientName: 'Claude Desktop', mcpVendorClient: 'ClaudeAI' },+ { mcpClientName: 'Anthropic/ClaudeAI', mcpVendorClient: 'Cowork' },+ { mcpClientName: 'example-client', mcpUiSupported: true },+ { mcpClientName: 'openai-mcp' },+ { mcpClientName: undefined, clientUserAgent: 'openai-mcp/1.0.0' },+ ])('puts UI host %j in single-exec and enables render-ui', async (clientProps) => {+ const props = makeProps(clientProps)const result = await makeResolver().resolve(props)expect(result.renderUiEnabled).toBe(true)@@ -570,17 +584,34 @@ describe('RequestStateResolver MCP client contexts', () => {expect(props.mode).toBe('cli')})- it('does not enable render-ui for Claude Code', async () => {- // Claude Code is a single-exec CLI client but not an MCP Apps host — it can't- // mount the iframe. It must stay in single-exec while `renderUiEnabled` resolves- // to false, so the tool-executor never advertises or accepts `render-ui` for it.- const props = makeProps({ mcpClientName: 'Anthropic/ClaudeAI', mcpVendorClient: 'ClaudeCode' })+ it.each([+ { mcpClientName: 'Anthropic/ClaudeAI', mcpVendorClient: 'ClaudeCode' },+ { mcpClientName: 'example-client' },+ { mcpClientName: 'codex-mcp-client', clientUserAgent: 'codex-mcp-client/0.165.0' },+ { mcpClientName: 'ChatGPT' },+ { mcpClientName: 'codex', mcpUiSupported: false },+ { mcpClientName: undefined, clientUserAgent: 'openai-mcp/1.0.0', mcpUiSupported: false },+ { mcpClientName: 'Claude Desktop', mcpVendorClient: 'ClaudeAI', mcpUiSupported: false },+ ])('does not enable render-ui without UI support for %j', async (clientProps) => {+ const props = makeProps(clientProps)const result = await makeResolver().resolve(props)expect(result.renderUiEnabled).toBe(false)expect(result.useSingleExec).toBe(true)})+ it.each([+ { cached: true, live: undefined, expected: true },+ { cached: true, live: false, expected: false },+ { cached: false, live: true, expected: true },+ ])('resolves UI support from the live declaration before the legacy session: %j', async (testCase) => {+ await makeResolver().resolve(makeProps({ mcpClientName: 'example-client', mcpUiSupported: testCase.cached }))++ const result = await makeResolver().resolve(makeProps({ mcpUiSupported: testCase.live }))++ expect(result.renderUiEnabled).toBe(testCase.expected)+ })+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.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex 8adf22ace4bb..02fbeeee4771 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -470,7 +470,6 @@ describe('ToolExecutor', () => {clientProfile: {capabilities: { supportsInstructions: true },isCliModeEnabled: vi.fn(() => true),- isClaudeUiHost: vi.fn(() => isClaudeChatHost),isInlineExecUiHost: vi.fn(() => false),isClaudeChatHost: vi.fn(() => isClaudeChatHost),isAnthropicConnector: vi.fn(() => isClaudeChatHost),@@ -727,7 +726,6 @@ describe('ToolExecutor', () => {clientProfile: {capabilities: { supportsInstructions },isCliModeEnabled: vi.fn(() => true),- isClaudeUiHost: vi.fn(() => false),isInlineExecUiHost: vi.fn(() => false),isClaudeChatHost: vi.fn(() => isClaudeChatHost),isAnthropicConnector: vi.fn(() => isClaudeChatHost),@@ -763,7 +761,6 @@ describe('ToolExecutor', () => {clientProfile: {capabilities: { supportsInstructions: true },isCliModeEnabled: vi.fn(() => true),- isClaudeUiHost: vi.fn(() => false),isInlineExecUiHost: vi.fn(() => false),isClaudeChatHost: vi.fn(() => true),isAnthropicConnector: vi.fn(() => true),@@ -783,7 +780,7 @@ describe('ToolExecutor', () => {expect(result.content[0]!.text).toContain('### Rendering visualizations')})- it('lists render-ui alongside exec when render-ui is enabled and a UI-app tool is available', async () => {+ it('advertises the same render-ui schema across accounts with different allowed tools', async () => {const state = makeToolExecutorState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })const result = await executor.handleToolsList(state)@@ -793,12 +790,18 @@ describe('ToolExecutor', () => {// render-ui calls from this list response.const renderUiEntry = result.tools[1]!const properties = renderUiEntry.inputSchema.properties as Record<string, Record<string, unknown>>- expect(properties.tool_name!.enum).toEqual(['survey-get'])+ expect(properties.tool_name!.enum).toEqual(expect.arrayContaining(['survey-get', 'query-trends']))+ expect(properties.tool_name!.enum).not.toContain('survey-launch')expect(properties.tool_name!.description).toBeTruthy()expect(properties.tool_input!.description).toBeTruthy()expect(properties.context!.description).toBeTruthy()expect(properties.llm_model!.description).toBeTruthy()expect(renderUiEntry.inputSchema.required).toEqual(['tool_name', 'context', 'llm_model'])++ const restrictedResult = await executor.handleToolsList(+ makeToolExecutorState([], { useSingleExec: true, renderUiEnabled: true })+ )+ expect(restrictedResult.tools.find((tool) => tool.name === 'render-ui')).toEqual(renderUiEntry)})it('omits render-ui when render-ui is disabled, even with a UI-app tool available', async () => {@@ -834,6 +837,18 @@ describe('ToolExecutor', () => {expect(result.isError).toBe(true)expect(result.content[0].text).toContain('not found')})++ it('rejects a cached render-ui choice that is not allowed for the current account', async () => {+ const state = makeToolExecutorState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })++ const result = (await executor.handleToolCall(+ { name: 'render-ui', arguments: { tool_name: 'query-trends', tool_input: {} } },+ state+ )) as { isError?: boolean; _meta?: { ui?: unknown } }++ expect(result.isError).toBe(true)+ expect(result._meta?.ui).toBeUndefined()+ })})// A render-ui app loads its own data with a direct `tools/call`, readingdiff --git a/services/mcp/tests/integration/skill-analytics.integration.test.ts b/services/mcp/tests/integration/skill-analytics.integration.test.tsindex 0d6bcf2c72be..0a923d55562f 100644--- a/services/mcp/tests/integration/skill-analytics.integration.test.ts+++ b/services/mcp/tests/integration/skill-analytics.integration.test.ts@@ -111,7 +111,6 @@ describe.skipIf(!API_TOKEN)('skill read reaches PostHog with $mcp_skill_name', (clientProfile: {capabilities: { supportsInstructions: true },isCliModeEnabled: () => true,- isClaudeUiHost: () => false,isInlineExecUiHost: () => false,isClaudeChatHost: () => false,isAnthropicConnector: () => false,diff --git a/services/mcp/tests/shared/test-utils.ts b/services/mcp/tests/shared/test-utils.tsindex 7d08d278d249..c7526a301a00 100644--- a/services/mcp/tests/shared/test-utils.ts+++ b/services/mcp/tests/shared/test-utils.ts@@ -686,7 +686,6 @@ export function makeToolExecutorState(clientProfile: {capabilities: { supportsInstructions: true },isCliModeEnabled: vi.fn(() => false),- isClaudeUiHost: vi.fn(() => false),isInlineExecUiHost: vi.fn(() => false),isClaudeChatHost: vi.fn(() => false),isAnthropicConnector: vi.fn(() => false),diff --git a/services/mcp/tests/unit/client-detection.test.ts b/services/mcp/tests/unit/client-detection.test.tsindex c23c616f9727..89866e644e88 100644--- a/services/mcp/tests/unit/client-detection.test.ts+++ b/services/mcp/tests/unit/client-detection.test.ts@@ -7,10 +7,10 @@ import {CODING_AGENT_CLIENT_NAME_FRAGMENTS,DEFAULT_CLIENT_CAPABILITIES,MCPClientProfile,+ OPENAI_RENDER_UI_CLIENT_NAMES,POSTHOG_CODE_CONSUMER,TOOLS_MODE_CLIENT_NAME_FRAGMENTS,TOOLS_MODE_USER_AGENT_FRAGMENTS,- isClaudeUiHostClient,isCliModeEnabledClient,isLegacyDialectOnlyClient,isPostHogCodeConsumer,@@ -247,38 +247,6 @@ describe('isToolsModeClient', () => {})})-describe('isClaudeUiHostClient', () => {- it.each([['ClaudeAI'], ['claudeai'], ['CLAUDEAI'], ['Anthropic/ClaudeAI']])(- 'returns true for vendor client %s',- (vendorClient) => {- expect(isClaudeUiHostClient({ vendorClient })).toBe(true)- }- )-- it.each([['Claude-User'], ['claude-user'], ['Claude_User']])('returns true for user agent %s', (userAgent) => {- expect(isClaudeUiHostClient({ userAgent })).toBe(true)- })-- it.each([['ClaudeCode'], ['some-random-tool'], ['']])('returns false for vendor client %s', (vendorClient) => {- expect(isClaudeUiHostClient({ vendorClient })).toBe(false)- })-- it('returns false when nothing matches', () => {- expect(isClaudeUiHostClient({})).toBe(false)- expect(isClaudeUiHostClient({ vendorClient: 'ClaudeCode', userAgent: 'node-fetch' })).toBe(false)- })-- it('keeps the fragment lists non-empty and lowercased', () => {- for (const fragments of [ANTHROPIC_UI_HOST_VENDOR_FRAGMENTS, ANTHROPIC_UI_HOST_USER_AGENT_FRAGMENTS]) {- expect(fragments.length).toBeGreaterThan(0)- for (const fragment of fragments) {- expect(fragment).toBe(fragment.toLowerCase())- expect(fragment.length).toBeGreaterThan(0)- }- }- })-})-describe('MCPClientProfile', () => {describe('isCliModeEnabled()', () => {it.each([@@ -409,48 +377,51 @@ describe('MCPClientProfile', () => {})})- describe('isClaudeUiHost()', () => {- it('returns true for Claude web/desktop vendor client (x-anthropic-client: ClaudeAI)', () => {- expect(new MCPClientProfile({ vendorClient: 'ClaudeAI' }).isClaudeUiHost()).toBe(true)- })-- it('returns true via User-Agent (Claude-User) when the vendor header is absent', () => {- expect(new MCPClientProfile({ userAgent: 'Claude-User' }).isClaudeUiHost()).toBe(true)- })-- it('returns false for Claude Code (vendorClient: ClaudeCode)', () => {- expect(new MCPClientProfile({ vendorClient: 'ClaudeCode' }).isClaudeUiHost()).toBe(false)- })-- it('returns true for Cowork (vendorClient: Cowork)', () => {- expect(new MCPClientProfile({ vendorClient: 'Cowork' }).isClaudeUiHost()).toBe(true)- })-- it('vendor client wins over a shared Claude-User user-agent', () => {- // Claude Code can share the `Claude-User` user-agent with web/desktop,- // but its vendor client is authoritative and excludes it.- expect(- new MCPClientProfile({ vendorClient: 'ClaudeCode', userAgent: 'Claude-User' }).isClaudeUiHost()- ).toBe(false)- })-- it('does not match the pooled clientName alone — avoids misclassifying Claude Code', () => {- // Claude Code's pooled initialize body also says `Anthropic/ClaudeAI`;- // only the per-request vendor client / user-agent identify a UI host.- expect(new MCPClientProfile({ clientName: 'Anthropic/ClaudeAI' }).isClaudeUiHost()).toBe(false)- expect(- new MCPClientProfile({ clientName: 'Anthropic/ClaudeAI', vendorClient: 'ClaudeCode' }).isClaudeUiHost()- ).toBe(false)+ describe('isRenderUiHost()', () => {+ it.each([+ { vendorClient: 'ClaudeAI' },+ { vendorClient: 'CLAUDEAI' },+ { vendorClient: 'Anthropic/ClaudeAI' },+ { vendorClient: 'Cowork' },+ { userAgent: 'Claude-User' },+ { userAgent: 'Claude_User' },+ ])('returns true for Claude web/desktop and Cowork: %j', (input) => {+ expect(new MCPClientProfile(input).isRenderUiHost()).toBe(true)})- it('returns false when nothing is set', () => {- expect(new MCPClientProfile({}).isClaudeUiHost()).toBe(false)+ it.each([+ {},+ { vendorClient: 'ClaudeCode' },+ { vendorClient: 'some-random-tool' },+ { vendorClient: 'ClaudeCode', userAgent: 'node-fetch' },+ // The vendor client is authoritative, so Claude Code stays excluded when it+ // shares the `Claude-User` user-agent with web/desktop.+ { vendorClient: 'ClaudeCode', userAgent: 'Claude-User' },+ // Claude Code's pooled initialize body also says `Anthropic/ClaudeAI`.+ { clientName: 'Anthropic/ClaudeAI' },+ { clientName: 'Anthropic/ClaudeAI', vendorClient: 'ClaudeCode' },+ ])('returns false for %j', (input) => {+ expect(new MCPClientProfile(input).isRenderUiHost()).toBe(false)})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)- expect(profile.isClaudeUiHost()).toBe(false)+ expect(profile.isRenderUiHost()).toBe(false)+ })++ it('keeps the fragment lists non-empty and lowercased', () => {+ for (const fragments of [+ ANTHROPIC_UI_HOST_VENDOR_FRAGMENTS,+ ANTHROPIC_UI_HOST_USER_AGENT_FRAGMENTS,+ OPENAI_RENDER_UI_CLIENT_NAMES,+ ]) {+ expect(fragments.length).toBeGreaterThan(0)+ for (const fragment of fragments) {+ expect(fragment).toBe(fragment.toLowerCase())+ expect(fragment.length).toBeGreaterThan(0)+ }+ }})})