: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
feat(mcp): add render_ui umbrella tool for cli mode (#61881)
Georgiy Tarasovaa126626cbf6
diff --git a/ee/hogai/eval/sandboxed/cli_mcp/eval_render_ui.py b/ee/hogai/eval/sandboxed/cli_mcp/eval_render_ui.pynew file mode 100644index 000000000000..ce2a38c8e289--- /dev/null+++ b/ee/hogai/eval/sandboxed/cli_mcp/eval_render_ui.py@@ -0,0 +1,136 @@+"""Eval cases for the ``render-ui`` umbrella tool conventions.++Grades the "when to render a visualization" behaviour spelled out in the+``render-ui`` tool prompt (``services/mcp/src/templates/render-ui-prompt.md``)+and its exec-reference pointer (``services/mcp/src/templates/sections/cli-rendering.md``).++The categories the prompt tells the agent to render on, and the cases that+exercise each (all use the experiment family — the only entity in the hedgebox+demo that is both richly seeded and renderable):++* **Status / health** (``status_experiment``) — "how is X going" renders the+ experiment.+* **Lists / inventory** (``list_experiments``) — "what do we have" renders the+ ``*-list`` view rather than a markdown table.+* **Results / stats** (``experiment_results``) — "is it significant" renders the+ experiment's results view.++Two cross-cutting rules are graded alongside:++* ``ExecBeforeRender`` — ``render-ui`` is the final presentation step; every+ render must be preceded by a successful ``exec`` discovery call (resolve the+ real ID, confirm the data), never rendered first or with a guessed input.+* ``eval_no_render_for_query_results`` — ``query-trends`` & friends render via+ their own app automatically and must NOT be routed through ``render-ui``.++Not exercised here (sandbox/scope limits, not prompt gaps):++* **Error-tracking** (lists / evidence-mid-investigation) — the demo seeds+ Postgres issue rows + raw exception events but the sandbox's ClickHouse+ error-tracking *issues* aren't populated, so ``query-error-tracking-*`` returns+ an empty list and the agent has no issue to render.+* **Post-mutation** (create/launch/pause → render to confirm) — requires write+ side effects against the shared demo project.+* **Surveys** — the hedgebox demo seeds none.++``render-ui`` is registered only in ``cli`` mode AND when the ``mcp-render-ui``+feature flag is on. The eval forces the flag on for the MCP server via the+dev/test-only ``FEATURE_FLAG_OVERRIDES`` seam (see ``conftest.py:_mcp_server``),+so the only remaining gate here is the mode: all cases skip under+``--mcp-mode=tools`` (see ``conftest.py:_apply_mcp_mode``).++To run a single eval:+ pytest ee/hogai/eval/sandboxed/cli_mcp/eval_render_ui.py::eval_renders_entity_ui --mcp-mode=cli+"""++from __future__ import annotations++import pytest++from ee.hogai.eval.sandboxed.base import SandboxedPublicEval+from ee.hogai.eval.sandboxed.cli_mcp.scorers import CalledTargetTool, DidNotRenderUi, ExecBeforeRender, RenderedEntityUi+from ee.hogai.eval.sandboxed.config import SandboxedEvalCase+from ee.hogai.eval.sandboxed.scorers import ExitCodeZero++# Renderable experiment tools (detail + results). The agent may render the detail+# view (``experiment-get``) or a results view for a status/results question. Two+# results tools exist: ``experiment-results-get`` (handwritten — what the agent+# reaches for in practice) and ``experiment-timeseries-results`` (generated).+EXPERIMENT_RENDER_TOOLS = ["experiment-results-get", "experiment-get", "experiment-timeseries-results"]+++async def eval_renders_entity_ui(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+ """Entity-centric answers must render the entity (in addition to summarizing it)."""+ if mcp_mode == "tools":+ pytest.skip("render-ui only exists in cli mode")++ cases: list[SandboxedEvalCase] = [+ # Status / health → render the experiment ("File engagement boost" runs in the demo).+ SandboxedEvalCase(+ name="status_experiment",+ prompt="How is the 'File engagement boost' experiment going?",+ expected={+ "rendered_entity_ui": {"tool_name_any_of": EXPERIMENT_RENDER_TOOLS},+ "exec_before_render": {},+ },+ ),+ # Lists / inventory → render the experiment list, not a markdown table.+ SandboxedEvalCase(+ name="list_experiments",+ prompt="What experiments do we have in this project?",+ expected={+ "rendered_entity_ui": {"tool_name_any_of": ["experiment-list"]},+ "exec_before_render": {},+ },+ ),+ # Results / stats → render the experiment's results/detail view.+ SandboxedEvalCase(+ name="experiment_results",+ prompt="Show me the results of the 'Pricing page redesign' experiment — did it reach significance?",+ expected={+ "rendered_entity_ui": {"tool_name_any_of": EXPERIMENT_RENDER_TOOLS},+ "exec_before_render": {},+ },+ ),+ ]++ await SandboxedPublicEval(+ experiment_name=f"sandboxed-cli-mcp-renders-entity-ui-{mcp_mode}",+ cases=cases,+ scorers=[ExitCodeZero(), RenderedEntityUi(), ExecBeforeRender()],+ pytestconfig=pytestconfig,+ sandboxed_demo_data=sandboxed_demo_data,+ posthog_client=posthog_client,+ )+++async def eval_no_render_for_query_results(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+ """Insight/trends answers must NOT be routed through ``render-ui``.++ ``query-trends`` (and the other insight ``query-*`` tools) carry the custom+ ``query-results`` app, which renders automatically — they are not in+ ``render-ui``'s enum. The agent should answer with the query tool and never+ call ``render-ui``.+ """+ if mcp_mode == "tools":+ pytest.skip("render-ui only exists in cli mode")++ cases: list[SandboxedEvalCase] = [+ SandboxedEvalCase(+ name="trends_chart_not_via_render_ui",+ prompt="Show me a trends chart of `$pageview` events over the last 7 days.",+ expected={+ "called_target_tool": {"tool": "query-trends"},+ "did_not_render_ui": {},+ },+ ),+ ]++ await SandboxedPublicEval(+ experiment_name=f"sandboxed-cli-mcp-no-render-for-query-{mcp_mode}",+ cases=cases,+ scorers=[ExitCodeZero(), CalledTargetTool(), DidNotRenderUi()],+ pytestconfig=pytestconfig,+ sandboxed_demo_data=sandboxed_demo_data,+ posthog_client=posthog_client,+ )diff --git a/ee/hogai/eval/sandboxed/cli_mcp/scorers.py b/ee/hogai/eval/sandboxed/cli_mcp/scorers.pyindex f04257488c4c..1ca8bd308666 100644--- a/ee/hogai/eval/sandboxed/cli_mcp/scorers.py+++ b/ee/hogai/eval/sandboxed/cli_mcp/scorers.py@@ -39,11 +39,14 @@ from ee.hogai.eval.sandboxed.log_parser import EXEC_TOOL_NAME, INFO_SYNTHETIC_PR__all__ = ["CalledTargetTool",+ "DidNotRenderUi","DrilledIntoSchema",+ "ExecBeforeRender","InfoBeforeCall","PreferredSearchOverTools","RanPythonPostProcessing","RecoveredToCorrectTool",+ "RenderedEntityUi","RetrievedSchemaPath","SurfacedGeneratedAppUrl","UsedJsonOutputFormat",@@ -56,6 +59,13 @@ __all__ = [# the capture keeps a trailing `\` and never substring-matches the (unescaped) final message._URL_RE = re.compile(r"https?://[^\s\"'`)\]<>\\]+")+RENDER_UI_TOOL_NAME = "render-ui"+"""Normalized name of the umbrella render tool (``mcp__<server>__render-ui`` → ``render-ui``).++Registered only in single-exec (``cli``) MCP mode — see+``services/mcp/src/tools/render-ui.ts`` and its prompt+``services/mcp/src/templates/render-ui-prompt.md``."""+def _read_tool(expected: dict | None, scorer_name: str) -> str | None:"""Look up ``expected[scorer_name]["tool"]`` with permissive validation."""@@ -771,3 +781,192 @@ class RanPythonPostProcessing(Scorer):"bash_call_count": len(bash_calls),},)+++def _render_ui_calls(parser: LogParser) -> list[ToolCall]:+ return parser.get_tool_calls(RENDER_UI_TOOL_NAME)+++def _rendered_tool_name(call: ToolCall) -> str | None:+ """The ``tool_name`` a ``render-ui`` call asked to render, if present."""+ name = call.input.get("tool_name")+ return name if isinstance(name, str) and name else None+++class RenderedEntityUi(Scorer):+ """Binary: did the agent render the expected entity via ``render-ui``?++ ``expected = {"rendered_entity_ui":+ {"tool_name_any_of": ["experiment-get", "experiment-timeseries-results"]}}``+ or ``{"rendered_entity_ui": {}}`` to accept any render.++ Score 1.0 when a successful ``render-ui`` call carried a ``tool_name`` in+ ``tool_name_any_of`` (or any ``tool_name`` when the list is omitted). 0.0+ otherwise, with what was actually rendered in metadata. ``None`` if the spec+ is absent. Mirrors the "strongly prefer rendering for entity-centric+ answers" rule in ``render-ui-prompt.md``.+ """++ def _name(self) -> str:+ return "rendered_entity_ui"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ spec = _read_spec(expected, self._name())+ if spec is None:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} spec on case"})++ parser = _build_parser(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ allowed = spec.get("tool_name_any_of")+ allowed_set = {t for t in allowed if isinstance(t, str) and t} if isinstance(allowed, list) else None++ rendered: list[str] = []+ errored_matches: list[str] = []+ for call in _render_ui_calls(parser):+ tool_name = _rendered_tool_name(call)+ if tool_name is None:+ continue+ rendered.append(tool_name)+ if allowed_set is not None and tool_name not in allowed_set:+ continue+ if call.is_error:+ errored_matches.append(tool_name)+ continue+ return Score(+ name=self._name(),+ score=1.0,+ metadata={"rendered_tool_name": tool_name, "call_id": call.call_id},+ )++ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "render-ui was not called with an expected tool_name",+ "expected_any_of": sorted(allowed_set) if allowed_set else "any",+ "rendered_tool_names": rendered,+ "errored_matches": errored_matches,+ },+ )+++class ExecBeforeRender(Scorer):+ """Binary: was every ``render-ui`` call preceded by a successful ``exec`` action?++ Opt-in via ``expected = {"exec_before_render": {}}``.++ ``render-ui`` is the final presentation step, never a discovery step — the+ agent must resolve the entity (look up its real ID) and confirm the data via+ ``exec`` (``search``/``info``/``schema``/``call``) first. For each+ ``render-ui`` call, requires a successful exec-derived call strictly earlier+ in the run. Score 1.0 if every render qualifies, 0.0 if any render fired with+ no prior exec (rendered before discovery / with a guessed input). ``None`` if+ ``render-ui`` was never called (covered by ``RenderedEntityUi``).+ """++ def _name(self) -> str:+ return "exec_before_render"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ @staticmethod+ def _is_exec_action(call: ToolCall) -> bool:+ if call.is_error:+ return False+ return call.is_exec_unwrapped or call.name == EXEC_TOOL_NAME or call.name.startswith(INFO_SYNTHETIC_PREFIX)++ def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ if _read_spec(expected, self._name()) is None:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} key on case"})++ parser = _build_parser(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ calls = sorted(parser.get_tool_calls(), key=lambda c: c.position)+ render_calls = [c for c in calls if c.name == RENDER_UI_TOOL_NAME]+ if not render_calls:+ return Score(name=self._name(), score=None, metadata={"reason": "render-ui never called"})++ offenders: list[str] = []+ for render_call in render_calls:+ preceded = any(self._is_exec_action(c) and c.position < render_call.position for c in calls)+ if not preceded:+ offenders.append(render_call.call_id)++ if offenders:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "render-ui fired before any successful exec call",+ "offenders": offenders,+ "render_calls": len(render_calls),+ },+ )+ return Score(name=self._name(), score=1.0, metadata={"render_calls": len(render_calls)})+++class DidNotRenderUi(Scorer):+ """Binary: did the agent correctly avoid ``render-ui`` here?++ ``expected = {"did_not_render_ui": {}}`` penalizes any ``render-ui`` call;+ ``{"did_not_render_ui": {"tool_name_any_of": ["query-trends"]}}`` penalizes+ only renders that routed one of those tool names.++ Use for query/insight answers: ``query-*`` results render through their own+ app automatically and must not be passed to ``render-ui``. Score 1.0 when no+ offending ``render-ui`` call exists, 0.0 otherwise. ``None`` if the spec is+ absent.+ """++ def _name(self) -> str:+ return "did_not_render_ui"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ spec = _read_spec(expected, self._name())+ if spec is None:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} key on case"})++ parser = _build_parser(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ allowed = spec.get("tool_name_any_of")+ target_set = {t for t in allowed if isinstance(t, str) and t} if isinstance(allowed, list) else None++ offenders: list[dict[str, object]] = []+ for call in _render_ui_calls(parser):+ tool_name = _rendered_tool_name(call)+ if target_set is None or (tool_name is not None and tool_name in target_set):+ offenders.append({"tool_name": tool_name, "call_id": call.call_id})++ if offenders:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "render-ui was called when it should not have been", "offenders": offenders},+ )+ return Score(+ name=self._name(),+ score=1.0,+ metadata={"scope": "any render-ui" if target_set is None else sorted(target_set)},+ )diff --git a/ee/hogai/eval/sandboxed/conftest.py b/ee/hogai/eval/sandboxed/conftest.pyindex 41c0a255d24f..2bf92e998bc0 100644--- a/ee/hogai/eval/sandboxed/conftest.py+++ b/ee/hogai/eval/sandboxed/conftest.py@@ -1,6 +1,7 @@from __future__ import annotationsimport os+import jsonimport atexitimport asyncioimport logging@@ -533,6 +534,12 @@ def _mcp_server(_django_live_server, _sandbox_settings):"NODE_ENV": "development","PORT": str(MCP_PORT),"HOST": "0.0.0.0",+ # The MCP server evaluates feature flags via posthog-node, which is disabled+ # here (no POSTHOG_ANALYTICS_* config), so every flag would resolve false.+ # Force flag-gated behavior on for evals via the dev/test-only override seam+ # (honored only when NODE_ENV is explicitly development/test — set above).+ # `mcp-render-ui` gates the render_ui umbrella tool — see eval_render_ui.py.+ "FEATURE_FLAG_OVERRIDES": json.dumps({"mcp-render-ui": True}),}logger.info("Starting MCP server (Hono runtime) on port %d (API: %s)", MCP_PORT, api_url)diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex adc354fa19b9..6295441ad49e 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -16,6 +16,10 @@ ui_apps:type: customapp_name: Query Resultsdescription: Interactive visualization for PostHog query results+ render-ui:+ type: custom+ app_name: PostHog Render UI+ description: Renders the visualization for a PostHog MCP tool resulttools:activity-retrieve:operation: organizations_projects_activity_retrievediff --git a/services/mcp/scripts/generate-ui-apps.ts b/services/mcp/scripts/generate-ui-apps.tsindex 8bcbdf6c5922..ad1ad97f287b 100644--- a/services/mcp/scripts/generate-ui-apps.ts+++ b/services/mcp/scripts/generate-ui-apps.ts@@ -33,6 +33,11 @@ const DEFINITIONS_DIR = path.resolve(MCP_ROOT_DIR, 'definitions')const PRODUCTS_DIR = path.resolve(ROOT_DIR, 'products')const GENERATED_APPS_DIR = path.resolve(MCP_ROOT_DIR, 'src/ui-apps/apps/generated')const GENERATED_REGISTRY_PATH = path.resolve(MCP_ROOT_DIR, 'src/resources/ui-apps.generated.ts')+// The render-ui umbrella app dispatches a tool result to its matching view. This+// module imports React view components, so it must live OUTSIDE src/ui-apps/apps/+// (where `discoverApps` would otherwise build it as a standalone app bundle).+const GENERATED_DISPATCH_DIR = path.resolve(MCP_ROOT_DIR, 'src/ui-apps/generated')+const GENERATED_DISPATCH_PATH = path.resolve(GENERATED_DISPATCH_DIR, 'render-dispatch.generated.tsx')const AUTO_GENERATED_HEADER = '// AUTO-GENERATED by generate-ui-apps.ts — do not edit\n'@@ -142,27 +147,15 @@ if (container) {`}-function generateListApp(appKey: string, config: ResolvedListUiApp): string {+/**+ * The list-to-detail `Content` component for a list app — owns the click handler+ * that fetches a single item via `callServerTool` and the chat fallback. Shared by+ * the standalone list entry point and the render-ui dispatch module so the+ * drill-down behavior can't drift between them.+ */+function buildListContentComponent(appKey: string, config: ResolvedListUiApp): string {const pascalName = kebabToPascal(appKey)- return `${AUTO_GENERATED_HEADER}import '../../styles/tailwind.css'--import type { App } from '@modelcontextprotocol/ext-apps'-import { useCallback } from 'react'-import { createRoot } from 'react-dom/client'--import { type ${config.item_data_type}, type ${config.list_data_type}, ${config.view_component} } from '${config.component_import}'--import { AppWrapper } from '../../components/AppWrapper'--function ${pascalName}App(): JSX.Element {- return (- <AppWrapper<${config.list_data_type}> appName="${config.app_name}">- {({ data, app }) => <${pascalName}Content data={data!} app={app} />}- </AppWrapper>- )-}--function ${pascalName}Content({ data, app }: { data: ${config.list_data_type}; app: App | null }): JSX.Element {+ return `function ${pascalName}Content({ data, app }: { data: ${config.list_data_type}; app: App | null }): JSX.Element {const fallbackToChat = useCallback((name: string) => {app?.sendMessage({@@ -198,8 +191,31 @@ function ${pascalName}Content({ data, app }: { data: ${config.list_data_type}; a)return <${config.view_component} data={data} ${config.click_prop}={handleClick} />+}`}+function generateListApp(appKey: string, config: ResolvedListUiApp): string {+ const pascalName = kebabToPascal(appKey)+ return `${AUTO_GENERATED_HEADER}import '../../styles/tailwind.css'++import type { App } from '@modelcontextprotocol/ext-apps'+import { useCallback } from 'react'+import { createRoot } from 'react-dom/client'++import { type ${config.item_data_type}, type ${config.list_data_type}, ${config.view_component} } from '${config.component_import}'++import { AppWrapper } from '../../components/AppWrapper'++function ${pascalName}App(): JSX.Element {+ return (+ <AppWrapper<${config.list_data_type}> appName="${config.app_name}">+ {({ data, app }) => <${pascalName}Content data={data!} app={app} />}+ </AppWrapper>+ )+}++${buildListContentComponent(appKey, config)}+const container = document.getElementById('root')if (container) {createRoot(container).render(<${pascalName}App />)@@ -207,6 +223,86 @@ if (container) {`}+// ------------------------------------------------------------------+// Render-ui dispatch module generator+// ------------------------------------------------------------------++type DispatchApp =+ | { appKey: string; type: 'detail'; config: ResolvedDetailUiApp }+ | { appKey: string; type: 'list'; config: ResolvedListUiApp }++/**+ * Generates the dispatch module consumed by the `render-ui` umbrella app. It maps+ * each detail/list app key to a render function so `render-ui` can fetch a tool+ * result and mount the matching view. Custom apps are excluded — they have no+ * convention view component to dispatch to.+ */+function generateDispatchModule(apps: DispatchApp[]): string {+ // Merge named imports per component_import path (multiple apps from the same+ // product share one import line, e.g. survey + survey-list + survey-stats).+ const importsByPath = new Map<string, Set<string>>()+ const addImport = (importPath: string, spec: string): void => {+ const specs = importsByPath.get(importPath) ?? new Set<string>()+ specs.add(spec)+ importsByPath.set(importPath, specs)+ }+ for (const app of apps) {+ if (app.type === 'detail') {+ addImport(app.config.component_import, `type ${app.config.data_type}`)+ addImport(app.config.component_import, app.config.view_component)+ } else {+ addImport(app.config.component_import, `type ${app.config.item_data_type}`)+ addImport(app.config.component_import, `type ${app.config.list_data_type}`)+ addImport(app.config.component_import, app.config.view_component)+ }+ }++ const componentImports = [...importsByPath.entries()]+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([importPath, specs]) => `import { ${[...specs].sort().join(', ')} } from '${importPath}'`)+ .join('\n')++ const hasListApp = apps.some((app) => app.type === 'list')++ const listContents = apps+ .filter((app): app is Extract<DispatchApp, { type: 'list' }> => app.type === 'list')+ .map((app) => buildListContentComponent(app.appKey, app.config))+ .join('\n\n')++ const entries = apps+ .map((app) => {+ if (app.type === 'detail') {+ const { view_component, view_prop, data_type, link_prop } = app.config+ if (link_prop) {+ return ` '${app.appKey}': ({ data, openLink }) => <${view_component} ${view_prop}={data as ${data_type}} ${link_prop}={openLink} />,`+ }+ return ` '${app.appKey}': ({ data }) => <${view_component} ${view_prop}={data as ${data_type}} />,`+ }+ const pascalName = kebabToPascal(app.appKey)+ return ` '${app.appKey}': ({ data, app }) => <${pascalName}Content data={data as ${app.config.list_data_type}} app={app} />,`+ })+ .join('\n')++ const reactImport = hasListApp ? "import { useCallback } from 'react'\n\n" : ''+ const listBlock = listContents ? `${listContents}\n\n` : ''++ return `${AUTO_GENERATED_HEADER}import type { App } from '@modelcontextprotocol/ext-apps'+${reactImport}${componentImports}++import type { UiAppKey } from '../../resources/ui-apps.generated'++export interface RenderDispatchProps {+ data: unknown+ app: App | null+ openLink: (url: string) => void+}++${listBlock}export const RENDER_DISPATCH: Partial<Record<UiAppKey, (props: RenderDispatchProps) => JSX.Element>> = {+${entries}+}+`+}+// ------------------------------------------------------------------// Registry generator// ------------------------------------------------------------------@@ -228,7 +324,7 @@ function toUri(appKey: string): string {return `ui://posthog/${appKey}.html`}-function generateRegistry(entries: RegistryEntry[]): string {+function generateRegistry(entries: RegistryEntry[], dispatchableKeys: string[]): string {const constants = entries.map((e) => `export const ${e.constName} = '${e.uri}'`).join('\n')const keyUnion = entries.map((e) => `'${e.appKey}'`).join(' | ')@@ -242,6 +338,11 @@ function generateRegistry(entries: RegistryEntry[]): string {).join(',\n')+ const dispatchableEntries = [...dispatchableKeys]+ .sort()+ .map((key) => ` '${key}'`)+ .join(',\n')+return `${AUTO_GENERATED_HEADER}${constants}@@ -251,6 +352,14 @@ export const URI_MAP: Record<UiAppKey, string> = {${uriMapEntries},}+/**+ * App keys with a generated detail/list view that the \`render-ui\` umbrella tool+ * can render. Excludes custom apps, which have no convention view component.+ */+export const DISPATCHABLE_APP_KEYS: UiAppKey[] = [+${dispatchableEntries},+]+export const UI_APPS: Array<{name: stringuri: string@@ -272,6 +381,7 @@ function main(): void {fs.mkdirSync(GENERATED_APPS_DIR, { recursive: true })const registryEntries: RegistryEntry[] = []+ const dispatchApps: DispatchApp[] = []const generatedFiles: string[] = []// Collect all ui_app keys for cross-referencing with tool ui_app fields@@ -319,6 +429,8 @@ function main(): void {fs.writeFileSync(outPath, code)generatedFiles.push(outPath)+ dispatchApps.push({ appKey, type: 'detail', config: resolved })+registryEntries.push({appKey,appDir: `generated/${appKey}`,@@ -340,6 +452,8 @@ function main(): void {fs.writeFileSync(outPath, code)generatedFiles.push(outPath)+ dispatchApps.push({ appKey, type: 'list', config: resolved })+registryEntries.push({appKey,appDir: `generated/${appKey}`,@@ -383,16 +497,25 @@ function main(): void {}}- // Sort registry entries alphabetically for stable output+ // Sort entries alphabetically for stable outputregistryEntries.sort((a, b) => a.appKey.localeCompare(b.appKey))+ dispatchApps.sort((a, b) => a.appKey.localeCompare(b.appKey))- // Write registry- const registryCode = generateRegistry(registryEntries)+ // Write registry (with the render-ui dispatchable key list)+ const registryCode = generateRegistry(+ registryEntries,+ dispatchApps.map((a) => a.appKey)+ )fs.writeFileSync(GENERATED_REGISTRY_PATH, registryCode)generatedFiles.push(GENERATED_REGISTRY_PATH)+ // Write the render-ui dispatch module+ fs.mkdirSync(GENERATED_DISPATCH_DIR, { recursive: true })+ fs.writeFileSync(GENERATED_DISPATCH_PATH, generateDispatchModule(dispatchApps))+ generatedFiles.push(GENERATED_DISPATCH_PATH)+process.stdout.write(- `Generated ${generatedFiles.length - 1} UI app entry point(s) + registry (${registryEntries.length} app(s))\n`+ `Generated ${generatedFiles.length - 2} UI app entry point(s) + registry + dispatch (${registryEntries.length} app(s))\n`)formatOutput(generatedFiles)@@ -421,7 +544,10 @@ function formatOutput(generatedFiles: string[]): void {// Export for testingexport {+ type DispatchApp,+ buildListContentComponent,generateDetailApp,+ generateDispatchModule,generateListApp,generateRegistry,kebabToPascal,diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.tsindex 480f34451fa0..eeccbd4b2f69 100644--- a/services/mcp/src/hono/instructions.ts+++ b/services/mcp/src/hono/instructions.ts@@ -1,3 +1,4 @@+import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'import type { Tool as McpTool } from '@modelcontextprotocol/sdk/types.js'import { hasScope } from '@/lib/api'@@ -5,10 +6,19 @@ import type { QueryToolInfo } from '@/lib/instructions'import { type InstructionsContext, InstructionsFormatter } from '@/lib/instructions-formatter'import type { RequestProperties } from '@/lib/request-properties'import { formatPrompt } from '@/lib/utils'+import { RENDER_UI_RESOURCE_URI } from '@/resources/ui-apps.generated'import EXECUTE_SQL_PROMPT from '@/templates/execute-sql-prompt.md'+import {+ getRenderableToolNames,+ makeRenderUiSchema,+ RENDER_UI_TOOL_DESCRIPTION,+ RENDER_UI_TOOL_NAME,+ RENDER_UI_TOOL_TITLE,+} from '@/tools/render-ui'import { getToolDefinition } from '@/tools/toolDefinitions'import type { ResolvedState } from './request-state-resolver'+import { toMcpInputSchema } from './tool-catalog'export class InstructionsBuilder {private readonly formatter: InstructionsFormatter@@ -64,6 +74,7 @@ export class InstructionsBuilder {} as QueryToolInfo}),featureFlags: state.toolFeatureFlags,+ renderUiEnabled: state.renderUiEnabled,}}@@ -83,6 +94,28 @@ export class InstructionsBuilder {}}+ buildRenderUiToolEntry(state: ResolvedState): McpTool | null {+ const toolNames = getRenderableToolNames(state.allTools)+ if (toolNames.length === 0) {+ return null+ }+ return {+ name: RENDER_UI_TOOL_NAME,+ title: RENDER_UI_TOOL_TITLE,+ description: RENDER_UI_TOOL_DESCRIPTION,+ // Derived from the same zod schema the executor validates with, so the+ // advertised contract (enum, descriptions, required) cannot drift from it.+ 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 the+ // modern and legacy keys are emitted since this entry isn't normalized downstream.+ _meta: {+ ui: { resourceUri: RENDER_UI_RESOURCE_URI },+ [RESOURCE_URI_META_KEY]: RENDER_UI_RESOURCE_URI,+ },+ }+ }+buildExecCommandReference(state: ResolvedState): string {const supportsInstructions = state.clientProfile.capabilities.supportsInstructionsconst ctx = this.buildContext(state)diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex 667f0e239c2b..20049cfffc04 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -1,8 +1,14 @@import { MCPClientProfile } from '@/lib/client-detection'import { buildMCPAnalyticsGroups } from '@/lib/posthog/analytics'-import { type EvaluatedFlags, evaluateFeatureFlags, type FlagGroups } from '@/lib/posthog/flags'+import {+ type EvaluatedFlags,+ evaluateFeatureFlags,+ type FlagGroups,+ resolveFeatureFlagOverrides,+} from '@/lib/posthog/flags'import type { RequestProperties } from '@/lib/request-properties'import type { McpMode } from '@/lib/utils'+import { RENDER_UI_FEATURE_FLAG } from '@/tools/render-ui'import { getRequiredFeatureFlags, getScopeGatedTools, type ScopeGatedTool } from '@/tools/toolDefinitions'import type { Context, Tool, Env, State, ZodObjectAny } from '@/tools/types'@@ -30,21 +36,31 @@ export interface ResolvedState {allTools: Tool<ZodObjectAny>[]scopeGatedTools: ScopeGatedTool[]distinctId: string+ renderUiEnabled: boolean}// ─── Pure helpers ───-export function resolveMode(args: { mode: McpMode | undefined; clientProfile: MCPClientProfile }): {+export function resolveMode(args: {+ mode: McpMode | undefined+ clientProfile: MCPClientProfile+ // The raw `mcp-render-ui` flag value — NOT the UI-host-gated `renderUiEnabled`+ // on ResolvedState; the UI-host check is applied here, on the flag.+ renderUiFlagEnabled: boolean+}): {mode: McpModeuseSingleExec: boolean} {- const { mode, clientProfile } = args+ const { mode, clientProfile, renderUiFlagEnabled } = argsconst useSingleExec =mode === 'cli' ||(mode !== 'tools' &&(clientProfile.isCliModeEnabled() ||clientProfile.isPostHogCodeConsumer() ||- clientProfile.isVibeCodingClient()))+ clientProfile.isVibeCodingClient() ||+ // Claude web/desktop render MCP Apps UI; put them in single-exec so+ // `render-ui` is available — but only when the feature flag is on.+ (renderUiFlagEnabled && clientProfile.isClaudeUiHost())))return { mode: mode ?? (useSingleExec ? 'cli' : 'tools'), useSingleExec }}@@ -93,7 +109,10 @@ export class RequestStateResolver {}const toolFlagKeys = getRequiredFeatureFlags()- const allFlagKeys = toolFlagKeys+ // `mcp-render-ui` isn't a catalog tool flag, but it rides the same batched+ // evaluation and lives in the same map so the instructions layer can gate+ // the rendering prompt section on it (like `mcp-feedback-tool`).+ const allFlagKeys = [...toolFlagKeys, RENDER_UI_FEATURE_FLAG]const flagAnalyticsContext = await reqCtx.getAnalyticsContextSafe(context)const flagGroups = flagAnalyticsContext ? buildMCPAnalyticsGroups(flagAnalyticsContext) : undefined@@ -104,10 +123,16 @@ export class RequestStateResolver {reqCtx.getDistinctId(),])+ // Dev/test-only overrides win over evaluated values (no-op in production).+ const overrides = resolveFeatureFlagOverrides(props.featureFlagOverrides)+ const mergedFlags = { ...allFlags, ...overrides }// Preserve variant strings (and `undefined` for unevaluated flags) — the// tool filter needs raw values to support `feature_flag_variant` matching.- const toolFeatureFlags =- toolFlagKeys.length > 0 ? Object.fromEntries(toolFlagKeys.map((k) => [k, allFlags[k]])) : undefined+ // Include override keys so a forced flag reaches the tool/instructions layer+ // even when no catalog tool referenced it.+ const flagKeysForState = [...new Set([...allFlagKeys, ...Object.keys(overrides)])]+ const toolFeatureFlags = Object.fromEntries(flagKeysForState.map((k) => [k, mergedFlags[k]]))+ const renderUiFlagEnabled = mergedFlags[RENDER_UI_FEATURE_FLAG] === trueconst oauthClientName = (await reqCtx.tokenCache.get('clientName')) || undefined@@ -117,11 +142,21 @@ export class RequestStateResolver {consumer: clientContext.mcpConsumer,oauthClientName,vendorClient: clientContext.mcpVendorClient,+ userAgent: props.clientUserAgent,})+ // `render-ui` is only meaningful for MCP Apps hosts (Claude web/desktop) that can+ // mount its iframe. The flag is necessary but not sufficient: Claude Code and other+ // single-exec CLI clients pool the same flag value, so the tool's advertisement and+ // execution must also require the UI-host check — otherwise rolling the flag out to+ // everyone leaks `render-ui` into Claude Code. `resolveMode` applies the same gate+ // independently for its single-exec decision, so it receives the raw flag value.+ const renderUiEnabled = renderUiFlagEnabled && clientProfile.isClaudeUiHost()+const { mode: resolvedMode, useSingleExec } = resolveMode({mode: requestContext.mode,clientProfile,+ renderUiFlagEnabled,})requestContext.mode = resolvedModereqCtx.setMcpContexts(requestContext, sessionContext)@@ -164,6 +199,7 @@ export class RequestStateResolver {allTools,scopeGatedTools,distinctId,+ renderUiEnabled,}}diff --git a/services/mcp/src/hono/tool-catalog.ts b/services/mcp/src/hono/tool-catalog.tsindex 02f4843cad74..88cb380ac4d9 100644--- a/services/mcp/src/hono/tool-catalog.ts+++ b/services/mcp/src/hono/tool-catalog.ts@@ -25,6 +25,25 @@ export type { PreBuiltTool }const EMPTY_OBJECT_JSON_SCHEMA = { type: 'object' as const, properties: {} }+/**+ * Convert a tool's zod schema to the MCP `inputSchema` wire shape. Single source+ * for every advertised schema (catalog entries and the `render-ui` umbrella entry)+ * so what `tools/list` advertises cannot drift from what the executor validates.+ */+export function toMcpInputSchema(schema: ZodObjectAny): McpTool['inputSchema'] {+ let jsonSchema = toJsonSchemaCompat(schema, { strictUnions: true }) as Record<string, unknown>+ delete jsonSchema['$schema']+ delete jsonSchema['additionalProperties']+ // MCP requires inputSchema.type === 'object'. Top-level discriminated unions+ // (e.g. `oneOf` on a polymorphic request body) come back without a root `type`.+ // Add it so the schema satisfies the MCP tool contract; the union constraint+ // still applies via the nested anyOf/oneOf.+ if (!jsonSchema['type'] && (Array.isArray(jsonSchema['anyOf']) || Array.isArray(jsonSchema['oneOf']))) {+ jsonSchema = { type: 'object', ...jsonSchema }+ }+ return jsonSchema as McpTool['inputSchema']+}+export class ToolCatalog {private _preBuilt: Map<string, PreBuiltTool> = new Map()private _entries: McpTool[] = []@@ -80,18 +99,9 @@ export class ToolCatalog {continue}- let jsonSchema: Record<string, unknown>+ let jsonSchema: McpTool['inputSchema']try {- jsonSchema = toJsonSchemaCompat(preBuilt.base.schema, { strictUnions: true }) as Record<string, unknown>- delete jsonSchema['$schema']- delete jsonSchema['additionalProperties']- // MCP requires inputSchema.type === 'object'. Top-level discriminated unions- // (e.g. `oneOf` on a polymorphic request body) come back without a root `type`.- // Add it so the schema satisfies the MCP tool contract; the union constraint- // still applies via the nested anyOf/oneOf.- if (!jsonSchema['type'] && (Array.isArray(jsonSchema['anyOf']) || Array.isArray(jsonSchema['oneOf']))) {- jsonSchema = { type: 'object', ...jsonSchema }- }+ jsonSchema = toMcpInputSchema(preBuilt.base.schema)} catch {jsonSchema = EMPTY_OBJECT_JSON_SCHEMA}@@ -108,7 +118,7 @@ export class ToolCatalog {name,title: def.title,description: def.description,- inputSchema: jsonSchema as McpTool['inputSchema'],+ inputSchema: jsonSchema,annotations: def.annotations as McpTool['annotations'],...(meta ? { _meta: meta } : {}),}diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 79fcdfe233ee..3f43eba4a202 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -12,6 +12,7 @@ import {} from '@/lib/errors'import { AnalyticsEvent } from '@/lib/posthog/analytics'import { createExecTool, type ExecInnerCallTracker } from '@/tools/exec'+import { createRenderUiTool } from '@/tools/render-ui'import { getToolCategory } from '@/tools/toolDefinitions'import type { Context, ZodObjectAny } from '@/tools/types'@@ -44,7 +45,10 @@ export class ToolExecutor {async handleToolsList(state: ResolvedState): Promise<ListToolsResult> {if (state.useSingleExec) {- return { tools: [this.instructionsBuilder.buildExecToolEntry(state)] }+ const renderUiEntry = state.renderUiEnabled ? this.instructionsBuilder.buildRenderUiToolEntry(state) : null+ return {+ tools: [this.instructionsBuilder.buildExecToolEntry(state), ...(renderUiEntry ? [renderUiEntry] : [])],+ }}const nameSet = new Set(state.allTools.map((t) => t.name))@@ -70,6 +74,15 @@ export class ToolExecutor {return this.callExecTool(params, state)}+ if (toolName === 'render-ui') {+ // render-ui is only advertised when the flag is on; reject calls otherwise.+ if (!state.renderUiEnabled) {+ toolCallsTotal.inc({ tool: toolName, status: 'error' })+ return { content: [{ type: 'text', text: `Tool ${toolName} not found` }], isError: true }+ }+ return this.callRenderUiTool(params, state)+ }+if (!state.allTools.some((t) => t.name === toolName)) {toolCallsTotal.inc({ tool: toolName, status: 'error' })return { content: [{ type: 'text', text: `Tool ${toolName} not found` }], isError: true }@@ -248,6 +261,44 @@ export class ToolExecutor {_meta: execTool._meta,}}++ private async callRenderUiTool(+ params: Record<string, unknown> | undefined,+ state: ResolvedState+ ): Promise<unknown> {+ const renderUiTool = createRenderUiTool(state.allTools, state.context)+ if (!renderUiTool) {+ return {+ content: [{ type: 'text', text: 'render-ui is not available — no tool has a UI app' }],+ isError: true,+ }+ }++ const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>+ const validation = renderUiTool.schema.safeParse(toolArgs)+ if (!validation.success) {+ toolCallsTotal.inc({ tool: 'render-ui', status: 'validation_error' })+ return { content: [{ type: 'text', text: `Invalid input: ${validation.error.message}` }], isError: true }+ }++ const stop = toolCallDurationSeconds.startTimer({ tool: 'render-ui' })+ const startMs = Date.now()+ try {+ const handlerResult = await renderUiTool.handler(state.context, validation.data)+ toolCallsTotal.inc({ tool: 'render-ui', status: 'success' })+ stop({ status: 'success' })+ void trackToolCall('render-ui', Date.now() - startMs, false, state)+ // The handler always returns an exec-built payload (UI resourceUri + structuredContent).+ return handlerResult+ } catch (error: unknown) {+ toolCallsTotal.inc({ tool: 'render-ui', status: 'error' })+ stop({ status: 'error' })+ classifyToolError(error, 'render-ui')+ void trackToolCall('render-ui', Date.now() - startMs, true, state)+ const sessionUuid = await state.reqCtx.getSessionUuid(state.requestContext.sessionId)+ return handleToolError(error, 'render-ui', state.distinctId, sessionUuid)+ }+ }}function classifyToolError(error: unknown, toolName: string): void {diff --git a/services/mcp/src/lib/client-detection.ts b/services/mcp/src/lib/client-detection.tsindex 47f86288a1f7..11ae2c80e4be 100644--- a/services/mcp/src/lib/client-detection.ts+++ b/services/mcp/src/lib/client-detection.ts@@ -28,6 +28,10 @@* reliable identifier. Used to force single-exec mode regardless of the* self-reported MCP client name.*+ * - `isClaudeUiHost()` matches Claude web and desktop — MCP Apps hosts that+ * render interactive UI (iframes). Used to put them in single-exec mode so the+ * `render-ui` tool is available, gated behind the `mcp-render-ui` flag.+ ** - `capabilities` is a feature-flag-style object describing protocol* features the client actually implements (e.g. `supportsInstructions` —* Codex ignores the `instructions` field returned from `initialize`).@@ -101,6 +105,19 @@ export const POSTHOG_CODE_CONSUMER = 'posthog-code'// OAuth name without the `notion-mcp-client` self-report.export const VIBE_CODING_OAUTH_CLIENT_NAME_FRAGMENTS = ['lovable', 'replit', 'notion'] as const+// Claude web and desktop are MCP Apps hosts that render interactive UI (iframes),+// so the `render-ui` tool is meaningful for them. They send `x-anthropic-client:+// ClaudeAI` (vs `ClaudeCode` for Claude Code, `Cowork` for Cowork) and+// `User-Agent: Claude-User`. The vendor client is authoritative when present:+// only `ClaudeAI` is a UI host, so Cowork and Claude Code are excluded even+// though they may share the `Claude-User` user-agent. The user-agent is a+// fallback solely for requests that omit the vendor header. We deliberately do+// NOT match `clientName` here — Anthropic pools transports, so Claude Code's+// `clientInfo.name` is also `Anthropic/ClaudeAI`, and matching it would+// misclassify Claude Code as a UI host.+export const ANTHROPIC_UI_HOST_VENDOR_FRAGMENTS = ['claudeai'] as const+export const ANTHROPIC_UI_HOST_USER_AGENT_FRAGMENTS = ['claude-user'] 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@@ -133,6 +150,8 @@ type MCPClientProfileInput = {// Anthropic pools MCP transports across products, so the live inner client// can disagree with the session-pinned `clientName` from `initialize`.vendorClient?: string | undefined+ // Per-request `User-Agent` (e.g. `Claude-User` for Claude web/desktop).+ userAgent?: string | undefined}export class MCPClientProfile {@@ -141,6 +160,7 @@ export class MCPClientProfile {readonly consumer: string | undefinedreadonly oauthClientName: string | undefinedreadonly vendorClient: string | undefined+ readonly userAgent: string | undefinedprivate _capabilities: ClientCapabilities | undefined@@ -150,6 +170,7 @@ export class MCPClientProfile {this.consumer = input.consumerthis.oauthClientName = input.oauthClientNamethis.vendorClient = input.vendorClient+ this.userAgent = input.userAgent}isCliModeEnabled(): boolean {@@ -172,6 +193,20 @@ export class MCPClientProfile {return matchesAnyFragment(this.oauthClientName, VIBE_CODING_OAUTH_CLIENT_NAME_FRAGMENTS)}+ isClaudeUiHost(): boolean {+ // The per-request vendor client (`x-anthropic-client`) is authoritative: it+ // distinguishes the Claude surfaces that pool the same MCP transport —+ // `ClaudeAI` (web/desktop, a UI-Apps host) from `Cowork` and `ClaudeCode`,+ // which render no MCP-Apps UI. When it's present, trust it exclusively; only+ // fall back to the `Claude-User` user-agent when the vendor header is absent.+ // Otherwise a non-UI surface like Cowork — 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)+ }+get capabilities(): ClientCapabilities {if (!this._capabilities) {this._capabilities = this._resolveCapabilities()@@ -201,3 +236,10 @@ export function isPostHogCodeConsumer(mcpConsumer: string | undefined): booleanexport function isVibeCodingClient(oauthClientName: string | undefined): boolean {return new MCPClientProfile({ oauthClientName }).isVibeCodingClient()}++export function isClaudeUiHostClient(args: {+ vendorClient?: string | undefined+ userAgent?: string | undefined+}): boolean {+ return new MCPClientProfile(args).isClaudeUiHost()+}diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.tsindex debac393e0f5..1c6aeda8bd41 100644--- a/services/mcp/src/lib/instructions-formatter.ts+++ b/services/mcp/src/lib/instructions-formatter.ts@@ -14,6 +14,7 @@ import BASIC_FUNCTIONALITY from '@/templates/sections/basic-functionality.md'import CLI_DATA_DISCOVERY from '@/templates/sections/cli-data-discovery.md'import CLI_ERROR_HANDLING from '@/templates/sections/cli-error-handling.md'import CLI_EXAMPLES from '@/templates/sections/cli-examples.md'+import CLI_RENDERING from '@/templates/sections/cli-rendering.md'import CLI_SCHEMA_DRILLDOWN from '@/templates/sections/cli-schema-drilldown.md'import CLI_SYNTAX from '@/templates/sections/cli-syntax.md'import COMPACT_INSTRUCTIONS from '@/templates/sections/compact-instructions.md'@@ -34,6 +35,10 @@ export interface InstructionsContext {/** Resolved tool feature flags from `resolveToolFeatureFlags`. Used to gate* prompt sections whose corresponding tool is flag-gated. */featureFlags?: EvaluatedFlags | undefined+ /** Whether `render-ui` is actually available to this client (the `mcp-render-ui`+ * flag is on AND the client is an MCP Apps host). Gates the CLI rendering section+ * so it never reaches clients — like Claude Code — that can't mount the iframe. */+ renderUiEnabled?: boolean | undefined}/**@@ -86,6 +91,7 @@ export class InstructionsFormatter {CLI_DATA_DISCOVERY,CLI_EXAMPLES,CLI_ERROR_HANDLING,+ ...(ctx.renderUiEnabled ? [CLI_RENDERING] : []),BASIC_FUNCTIONALITY,TOOL_SEARCH,RETRIEVING_DATA,diff --git a/services/mcp/src/lib/posthog/flags.ts b/services/mcp/src/lib/posthog/flags.tsindex 58f9715284c0..8332514f3835 100644--- a/services/mcp/src/lib/posthog/flags.ts+++ b/services/mcp/src/lib/posthog/flags.ts@@ -1,3 +1,5 @@+import { env } from '@/lib/env'+import { getPostHogClient } from './client'// Group type → group key, matching the `$groups` shape from `buildMCPAnalyticsGroups`.@@ -38,3 +40,56 @@ export async function evaluateFeatureFlags(}return result}++// Env var (or Cloudflare var) holding a JSON object of flag overrides, e.g.+// `FEATURE_FLAG_OVERRIDES={"mcp-render-ui": true, "some-flag": "variant-a"}`.+const FEATURE_FLAG_OVERRIDES_ENV = 'FEATURE_FLAG_OVERRIDES'++/** Parse a JSON object of flag overrides. Non-object JSON, parse errors, and+ * values that aren't booleans or variant strings are ignored. */+function parseFlagOverridesJson(raw: string | undefined): EvaluatedFlags {+ if (!raw) {+ return {}+ }+ try {+ const parsed: unknown = JSON.parse(raw)+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ return {}+ }+ const result: EvaluatedFlags = {}+ for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {+ if (typeof value === 'boolean' || typeof value === 'string') {+ result[key] = value+ }+ }+ return result+ } catch {+ return {}+ }+}++/**+ * Dev/test-only feature-flag overrides, merged on top of the posthog-node+ * evaluation so flags can be forced for local dev and evals — where the+ * analytics client is disabled (no `POSTHOG_ANALYTICS_*`) and every flag would+ * otherwise resolve to `false`.+ *+ * Sources, later wins: the `FEATURE_FLAG_OVERRIDES` env/Cloudflare var+ * (server-wide), then the per-request override (`?flag_overrides=` query param /+ * `x-posthog-flag-overrides` header on the Hono path). Both are JSON objects.+ *+ * Honored ONLY when NODE_ENV is explicitly `development` or `test`: without this+ * guard a request could send `?flag_overrides={"<gated-flag>":true}` to unlock+ * flag-gated tools. The positive allowlist (rather than `!== 'production'`) makes+ * the seam fail closed when NODE_ENV is unset — e.g. on Cloudflare Workers, where+ * `process.env` may be empty — mirroring `extractBearerToken` in `lib/utils`.+ */+export function resolveFeatureFlagOverrides(requestOverrides?: string): EvaluatedFlags {+ if (env.NODE_ENV !== 'development' && env.NODE_ENV !== 'test') {+ return {}+ }+ return {+ ...parseFlagOverridesJson(env[FEATURE_FLAG_OVERRIDES_ENV]),+ ...parseFlagOverridesJson(requestOverrides),+ }+}diff --git a/services/mcp/src/lib/request-properties.ts b/services/mcp/src/lib/request-properties.tsindex 3fdfbc282853..d210df5fe01d 100644--- a/services/mcp/src/lib/request-properties.ts+++ b/services/mcp/src/lib/request-properties.ts@@ -27,6 +27,10 @@ export type RequestProperties = {mcpConversationId?: string | undefinedviaSseRedirect?: boolean | undefinedrequestStartTime?: number | undefined+ // Dev/test-only per-request feature-flag overrides — a JSON object string from+ // `?flag_overrides=` or the `x-posthog-flag-overrides` header. Parsed and gated+ // to NODE_ENV development/test (fail-closed) in `resolveFeatureFlagOverrides`.+ featureFlagOverrides?: string | undefined}export type ClientInfo = {@@ -79,5 +83,6 @@ export function parseRequestProperties(mode: parseMcpMode(header(request, 'x-posthog-mcp-mode') || params.get('mode')),transport,requestStartTime: Date.now(),+ featureFlagOverrides: header(request, 'x-posthog-flag-overrides') || params.get('flag_overrides') || undefined,}}diff --git a/services/mcp/src/resources/ui-apps.generated.ts b/services/mcp/src/resources/ui-apps.generated.tsindex 88a8b68ee3a0..5741c7b71050 100644--- a/services/mcp/src/resources/ui-apps.generated.ts+++ b/services/mcp/src/resources/ui-apps.generated.ts@@ -17,6 +17,7 @@ export const FEATURE_FLAG_TESTING_RESOURCE_URI = 'ui://posthog/feature-flag-testexport const INSIGHT_ACTORS_RESOURCE_URI = 'ui://posthog/insight-actors.html'export const LLM_COSTS_RESOURCE_URI = 'ui://posthog/llm-costs.html'export const QUERY_RESULTS_RESOURCE_URI = 'ui://posthog/query-results.html'+export const RENDER_UI_RESOURCE_URI = 'ui://posthog/render-ui.html'export const SESSION_RECORDING_RESOURCE_URI = 'ui://posthog/session-recording.html'export const SESSION_SUMMARY_RESOURCE_URI = 'ui://posthog/session-summary.html'export const SURVEY_RESOURCE_URI = 'ui://posthog/survey.html'@@ -47,6 +48,7 @@ export type UiAppKey =| 'insight-actors'| 'llm-costs'| 'query-results'+ | 'render-ui'| 'session-recording'| 'session-summary'| 'survey'@@ -77,6 +79,7 @@ export const URI_MAP: Record<UiAppKey, string> = {'insight-actors': INSIGHT_ACTORS_RESOURCE_URI,'llm-costs': LLM_COSTS_RESOURCE_URI,'query-results': QUERY_RESULTS_RESOURCE_URI,+ 'render-ui': RENDER_UI_RESOURCE_URI,'session-recording': SESSION_RECORDING_RESOURCE_URI,'session-summary': SESSION_SUMMARY_RESOURCE_URI,survey: SURVEY_RESOURCE_URI,@@ -90,6 +93,38 @@ export const URI_MAP: Record<UiAppKey, string> = {'workflow-list': WORKFLOW_LIST_RESOURCE_URI,}+/**+ * App keys with a generated detail/list view that the `render-ui` umbrella tool+ * can render. Excludes custom apps, which have no convention view component.+ */+export const DISPATCHABLE_APP_KEYS: UiAppKey[] = [+ 'action',+ 'action-list',+ 'cohort',+ 'cohort-list',+ 'error-details',+ 'error-issue',+ 'error-issue-list',+ 'experiment',+ 'experiment-list',+ 'experiment-results',+ 'feature-flag',+ 'feature-flag-list',+ 'feature-flag-testing',+ 'insight-actors',+ 'llm-costs',+ 'session-recording',+ 'session-summary',+ 'survey',+ 'survey-global-stats',+ 'survey-list',+ 'survey-stats',+ 'trace-span',+ 'trace-span-list',+ 'workflow',+ 'workflow-list',+]+export const UI_APPS: Array<{name: stringuri: string@@ -198,6 +233,12 @@ export const UI_APPS: Array<{description: 'Interactive visualization for PostHog query results',appDir: 'query-results',},+ {+ name: 'PostHog Render UI',+ uri: RENDER_UI_RESOURCE_URI,+ description: 'Renders the visualization for a PostHog MCP tool result',+ appDir: 'render-ui',+ },{name: 'PostHog Session Recording',uri: SESSION_RECORDING_RESOURCE_URI,diff --git a/services/mcp/src/templates/render-ui-prompt.md b/services/mcp/src/templates/render-ui-prompt.mdnew file mode 100644index 000000000000..f9b3fe1f92da--- /dev/null+++ b/services/mcp/src/templates/render-ui-prompt.md@@ -0,0 +1,47 @@+Render an interactive, explorable visualization of a PostHog entity for the user. Strongly prefer rendering whenever your answer centers on a specific entity or list that has a UI app — an experiment (or its results), survey (or its stats), cohort, action, error-tracking issue, session recording, trace, or workflow, plus the list view for most — so the user can see and verify it, not just read a text summary. Render in addition to your written summary, not instead of it, and not only when the user explicitly asks to "see" something.++ALWAYS run `exec` first — `render-ui` is the final presentation step, never a discovery step. Use `exec` (`search` → `info` → `schema` → `call`) to resolve the entity (look up its real ID), confirm the data exists, and gather what you need for your written summary; only then render. Never render with a guessed `tool_input`.++`tool_name` must be a tool from the enum; `tool_input` is the same input you would `call` it with — which you already know from your exec work. The widget fetches its own data, so you may skip a *redundant* `call` of that same UI-app tool purely to populate the widget — but that is the only `call` you may skip, never the discovery/verification workflow. Never invent a `tool_name`. Results from `query-*` tools render through their own app automatically — do not route those through `render-ui`.++When to render (always after exec, alongside your written answer):++- Show me / pull up X → its detail tool, e.g. `render-ui({ "tool_name": "survey-get", "tool_input": { "id": "abc123" } })`+- Status, "how is X going" → `render-ui({ "tool_name": "experiment-get", "tool_input": { "id": 2 } })`+- Lists / inventory, "what do we have" → the `*-list` tool, e.g. `render-ui({ "tool_name": "experiment-list", "tool_input": {} })`+- Results / stats, "is it significant", "response rate" → the results tool, e.g. `render-ui({ "tool_name": "survey-stats", "tool_input": { "survey_id": "abc123" } })`+- After a mutation (create/launch/pause/end/resolve) → the entity's detail tool, to confirm the change landed+- Evidence mid-investigation (a recording, error issue, trace) → render it inline, e.g. `render-ui({ "tool_name": "query-error-tracking-issue", "tool_input": { "issueId": "0190-..." } })`++<example>+User: How is the "File engagement boost" experiment going?+Assistant: [exec first: search experiment → info experiment-get → call to resolve it to id 2 and read its results]+Assistant: <concise summary — front-runner, significance, caveats>, then renders it so the user can verify.+[Calls render-ui({ "tool_name": "experiment-get", "tool_input": { "id": 2 } })]+<reasoning>exec first to resolve the id and gather the numbers; render last, alongside the summary.</reasoning>+</example>++<example>+User: What experiments are we running right now?+Assistant: [exec first: call experiment-list to read what's running for the summary]+Assistant: Four are running, then renders the interactive list rather than a markdown table.+[Calls render-ui({ "tool_name": "experiment-list", "tool_input": {} })]+</example>++<bad-example>+User: How is the "File engagement boost" experiment going?+Assistant: [Immediately calls render-ui with a guessed id, without any exec search/info/call first]+WRONG — render-ui is not a discovery tool. Run exec first to resolve the experiment's real id and read its results, then render — never render before exec or with a guessed input.+</bad-example>++<bad-example>+User: How is the "File engagement boost" experiment going?+Assistant: [Reads the results via exec, then replies with a long text-only breakdown of every metric and never calls render-ui]+WRONG — the answer centers on a single experiment that has a UI app (`experiment-get` is in the enum). Render it so the user can see and verify the results, then add your summary.+</bad-example>++<bad-example>+User: Show me a trends chart of weekly signups+Assistant: [Calls render-ui({ "tool_name": "query-trends", ... })]+WRONG — `query-*` results render through their own app automatically and are not in `render-ui`'s enum. Run the query directly; do not route it through `render-ui`.+</bad-example>diff --git a/services/mcp/src/templates/sections/cli-rendering.md b/services/mcp/src/templates/sections/cli-rendering.mdnew file mode 100644index 000000000000..f0c4c3e9e00b--- /dev/null+++ b/services/mcp/src/templates/sections/cli-rendering.md@@ -0,0 +1,24 @@+### Rendering visualizations++`render-ui` is a separate tool (not an `exec` command) — see its own description for the full enum and worked examples. When your answer centers on an entity or list whose tool is in `render-ui`'s `tool_name` enum, strongly prefer rendering it **in addition to** your written summary (not instead of it), so the user can verify the result instead of trusting a text dump — not only when they explicitly ask to "see" something. Reach for it on: status/health, lists/inventory, results/stats, post-mutation verification, and evidence surfaced mid-investigation. Pass the same `tool_input` you would `call` the tool with; it fetches its own data. Never invent a `tool_name`. (Results from `query-*` tools render through their own app automatically — do not route those through `render-ui`.)++ALWAYS run `exec` first. `render-ui` is the final presentation step, never a discovery step — use `exec` (`search`/`info`/`schema`/`call`) to resolve the entity's real ID and confirm the data, then render. Never render before exec, and never with a guessed `tool_input`.++<example>+User: How is the "File engagement boost" experiment going?+Assistant: [exec first: search/info/call to resolve it to id 2 and read its results]+Assistant: <concise summary of the results>, then renders it so the user can verify.+[Runs render-ui({ "tool_name": "experiment-get", "tool_input": { "id": 2 } })]+</example>++<bad-example>+User: How is the "File engagement boost" experiment going?+Assistant: [Calls render-ui with a guessed id before running any exec command]+WRONG — run exec first to resolve the real id and read the results; render-ui is not a discovery tool.+</bad-example>++<bad-example>+User: How is the "File engagement boost" experiment going?+Assistant: [Reads the results via exec, then replies with a long text-only breakdown of every metric and never calls render-ui]+WRONG — the answer centers on a single experiment, which has a UI app (`experiment-get` is in `render-ui`'s enum). Render it with render-ui so the user can see and verify the results, then add your summary. Strongly prefer render-and-summarize over a text dump alone.+</bad-example>diff --git a/services/mcp/src/tools/render-ui.ts b/services/mcp/src/tools/render-ui.tsnew file mode 100644index 000000000000..e4b92ae219c4--- /dev/null+++ b/services/mcp/src/tools/render-ui.ts@@ -0,0 +1,129 @@+import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'+import { z } from 'zod'++import { markExecPayload, type ToolResultPayload } from '@/lib/build-tool-result'+import { DISPATCHABLE_APP_KEYS, RENDER_UI_RESOURCE_URI, URI_MAP, type UiAppKey } from '@/resources/ui-apps.generated'+import RENDER_UI_PROMPT from '@/templates/render-ui-prompt.md'++import { type Context, type Tool, type ZodObjectAny } from './types'++export const RENDER_UI_TOOL_NAME = 'render-ui'+export const RENDER_UI_TOOL_TITLE = 'Render a PostHog visualization'+export const RENDER_UI_TOOL_DESCRIPTION = RENDER_UI_PROMPT.trim()++// Feature flag gating the entire `render-ui` feature: tool registration/advertisement,+// the rendering prompt section, and the single-exec switch for Claude web/desktop.+export const RENDER_UI_FEATURE_FLAG = 'mcp-render-ui'++// Reverse of URI_MAP so a tool's `_meta.ui.resourceUri` resolves back to its app key.+const URI_TO_APP_KEY = new Map<string, UiAppKey>(+ Object.entries(URI_MAP).map(([appKey, uri]) => [uri, appKey as 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) {+ return undefined+ }+ const appKey = URI_TO_APP_KEY.get(resourceUri)+ return appKey && DISPATCHABLE.has(appKey) ? appKey : undefined+}++/**+ * Names of the tools `render-ui` can render — those whose UI app has a generated view.+ * 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[] {+ return allTools+ .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. */+export function makeRenderUiSchema(+ toolNames: [string, ...string[]]+): z.ZodObject<{ tool_name: z.ZodEnum<Record<string, string>>; tool_input: z.ZodOptional<z.ZodRecord> }> {+ return z.object({+ tool_name: z+ .enum(toolNames)+ .describe('A tool that has a UI app — its visualization will be rendered for the user.'),+ tool_input: z+ .record(z.string(), z.unknown())+ .optional()+ .describe('The generated input for that tool. The UI app uses it to fetch and render the visualization.'),+ })+}++type RenderUiSchema = ReturnType<typeof makeRenderUiSchema>++/**+ * Builds the `render-ui` umbrella tool. Returns `null` when no tool in `allTools`+ * has a renderable UI app (a `z.enum` needs at least one value, and there is+ * nothing to render anyway). Unlike the per-entity tools, this one does not run+ * the inner tool: it emits a render directive (`{ tool_name, tool_input, app_key }`+ * + the render-ui resourceUri) and the UI app fetches its own data.+ */+export function createRenderUiTool(allTools: Tool<ZodObjectAny>[], context: Context): Tool<RenderUiSchema> | null {+ const renderableNames = getRenderableToolNames(allTools)+ if (renderableNames.length === 0) {+ return null+ }+ const schema = makeRenderUiSchema(renderableNames as [string, ...string[]])++ return {+ name: RENDER_UI_TOOL_NAME,+ title: RENDER_UI_TOOL_TITLE,+ description: RENDER_UI_TOOL_DESCRIPTION,+ schema,+ scopes: [],+ annotations: {+ destructiveHint: false,+ idempotentHint: true,+ openWorldHint: false,+ readOnlyHint: true,+ },+ // Advertise the umbrella UI resource on the tool definition itself.+ // MCP Apps hosts (e.g. Claude) discover renderable tools from `tools/list`+ // `_meta.ui.resourceUri`, pre-fetch the template, and only mount the iframe+ // for a tool declared this way — the result-level `_meta` alone is ignored.+ // `registerTool` back-fills the legacy `ui/resourceUri` key from this.+ _meta: {+ ui: { resourceUri: RENDER_UI_RESOURCE_URI },+ [RESOURCE_URI_META_KEY]: RENDER_UI_RESOURCE_URI,+ },+ handler: async (_context: Context, params: z.infer<RenderUiSchema>) => {+ const tool = allTools.find((t) => t.name === params.tool_name)+ const appKey = tool ? toDispatchableAppKey(tool) : undefined+ if (!tool || !appKey) {+ throw new Error(`Tool "${params.tool_name}" does not have a renderable UI app.`)+ }++ const toolInput = params.tool_input ?? {}+ // `render-ui` only emits a render directive — it never executes the inner tool,+ // so the inner tool is deliberately not counted in per-tool call metrics. The+ // umbrella call itself is tracked under `render-ui` by the executor.+ const distinctId = await context.getDistinctId()++ const payload: ToolResultPayload = {+ content: [{ type: 'text', text: `Rendering the ${tool.name} visualization for the user.` }],+ structuredContent: {+ tool_name: tool.name,+ tool_input: toolInput,+ app_key: appKey,+ _analytics: { distinctId, toolName: RENDER_UI_TOOL_NAME },+ },+ _meta: {+ ui: { resourceUri: RENDER_UI_RESOURCE_URI },+ [RESOURCE_URI_META_KEY]: RENDER_UI_RESOURCE_URI,+ },+ }+ return markExecPayload(payload)+ },+ }+}diff --git a/services/mcp/src/ui-apps/apps/render-ui.tsx b/services/mcp/src/ui-apps/apps/render-ui.tsxnew file mode 100644index 000000000000..5e03bf49b022--- /dev/null+++ b/services/mcp/src/ui-apps/apps/render-ui.tsx@@ -0,0 +1,92 @@+import '../styles/tailwind.css'++import type { App } from '@modelcontextprotocol/ext-apps'+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 { RENDER_DISPATCH } from '../generated/render-dispatch.generated'++/**+ * Envelope emitted by the `render-ui` server tool. It carries the tool to render+ * and its input — never the data itself. This app fetches the data via+ * `callServerTool` (the same path the list apps use for drill-down) and mounts+ * the matching view from the generated dispatch registry.+ */+interface RenderUiEnvelope {+ tool_name: string+ tool_input?: Record<string, unknown>+ app_key: UiAppKey+}++function RenderUiApp(): JSX.Element {+ return (+ <AppWrapper<RenderUiEnvelope> appName="PostHog Render UI">+ {({ data, app, openLink }) => <RenderUiContent envelope={data!} app={app} openLink={openLink} />}+ </AppWrapper>+ )+}++function RenderUiContent({+ envelope,+ app,+ openLink,+}: {+ envelope: RenderUiEnvelope+ app: App | null+ openLink: (url: string) => void+}): JSX.Element {+ const [data, setData] = useState<unknown>(null)+ const [error, setError] = useState<string | null>(null)++ // Key the fetch on serialized values, not `envelope` identity — a parent+ // re-render with a fresh-but-equal envelope object must not refetch.+ const toolName = envelope.tool_name+ const toolInputJson = JSON.stringify(envelope.tool_input ?? {})+ useEffect(() => {+ if (!app) {+ setError('Visualization unavailable: app context not provided.')+ return+ }+ let cancelled = false+ setData(null)+ setError(null)+ app.callServerTool({ name: toolName, arguments: JSON.parse(toolInputJson) as Record<string, unknown> })+ .then((result) => {+ if (cancelled) {+ return+ }+ if (result.isError || !result.structuredContent) {+ setError(`Could not load data for ${toolName}.`)+ return+ }+ setData(result.structuredContent)+ })+ .catch((e: unknown) => {+ if (!cancelled) {+ setError(e instanceof Error ? e.message : String(e))+ }+ })+ return () => {+ cancelled = true+ }+ }, [app, toolName, toolInputJson])++ const render = RENDER_DISPATCH[envelope.app_key]+ if (!render) {+ return <AppErrorState message={`No visualization is available for ${envelope.tool_name}.`} />+ }+ if (error) {+ return <AppErrorState message={error} />+ }+ if (data === null) {+ return <AppLoadingState />+ }+ return render({ data, app, openLink })+}++const container = document.getElementById('root')+if (container) {+ createRoot(container).render(<RenderUiApp />)+}diff --git a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsxnew file mode 100644index 000000000000..0d80d3fb34db--- /dev/null+++ b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx@@ -0,0 +1,390 @@+// AUTO-GENERATED by generate-ui-apps.ts — do not edit+import type { App } from '@modelcontextprotocol/ext-apps'+import { useCallback } from 'react'++import { ActionListView, ActionView, type ActionData, type ActionListData } from 'products/actions/mcp/apps'+import { LLMCostsView, type LLMCostsData } from 'products/ai_observability/mcp/apps'+import { CohortListView, CohortView, type CohortData, type CohortListData } from 'products/cohorts/mcp/apps'+import {+ ErrorDetailsView,+ ErrorIssueListView,+ ErrorIssueView,+ type ErrorDetailsData,+ type ErrorIssueData,+ type ErrorIssueListData,+} from 'products/error_tracking/mcp/apps'+import {+ ExperimentListView,+ ExperimentResultsView,+ ExperimentView,+ type ExperimentData,+ type ExperimentListData,+ type ExperimentResultsData,+} from 'products/experiments/mcp/apps'+import {+ FeatureFlagListView,+ FeatureFlagTestingView,+ FeatureFlagView,+ type FeatureFlagData,+ type FeatureFlagListData,+ type FeatureFlagTestingData,+} from 'products/feature_flags/mcp/apps'+import { InsightActorsView, type InsightActorsData } from 'products/product_analytics/mcp/apps'+import {+ SessionRecordingView,+ SessionSummaryView,+ type SessionRecordingData,+ type SessionSummaryData,+} from 'products/replay/mcp/apps'+import {+ SurveyListView,+ SurveyStatsView,+ SurveyView,+ type SurveyData,+ type SurveyListData,+ type SurveyStatsData,+} from 'products/surveys/mcp/apps'+import { TraceSpanListView, TraceSpanView, type TraceSpanData, type TraceSpanListData } from 'products/tracing/mcp/apps'+import { WorkflowListView, WorkflowView, type WorkflowData, type WorkflowListData } from 'products/workflows/mcp/apps'++import type { UiAppKey } from '../../resources/ui-apps.generated'++export interface RenderDispatchProps {+ data: unknown+ app: App | null+ openLink: (url: string) => void+}++function ActionListContent({ data, app }: { data: ActionListData; app: App | null }): JSX.Element {+ const fallbackToChat = useCallback(+ (name: string) => {+ app?.sendMessage({+ role: 'user',+ content: [{ type: 'text', text: `Show me the details for action "${name}"` }],+ })+ },+ [app]+ )++ const handleClick = useCallback(+ async (item: ActionData): Promise<ActionData | null> => {+ if (!app) {+ fallbackToChat(item.name)+ return null+ }+ try {+ const result = await app.callServerTool({+ name: 'action-get',+ arguments: { id: item.id },+ })+ if (result.isError || !result.structuredContent) {+ fallbackToChat(item.name)+ return null+ }+ return result.structuredContent as unknown as ActionData+ } catch {+ fallbackToChat(item.name)+ return null+ }+ },+ [app, fallbackToChat]+ )++ return <ActionListView data={data} onActionClick={handleClick} />+}++function CohortListContent({ data, app }: { data: CohortListData; app: App | null }): JSX.Element {+ const fallbackToChat = useCallback(+ (name: string) => {+ app?.sendMessage({+ role: 'user',+ content: [{ type: 'text', text: `Show me the details for cohort "${name}"` }],+ })+ },+ [app]+ )++ const handleClick = useCallback(+ async (item: CohortData): Promise<CohortData | null> => {+ if (!app) {+ fallbackToChat(item.name)+ return null+ }+ try {+ const result = await app.callServerTool({+ name: 'cohorts-retrieve',+ arguments: { id: item.id },+ })+ if (result.isError || !result.structuredContent) {+ fallbackToChat(item.name)+ return null+ }+ return result.structuredContent as unknown as CohortData+ } catch {+ fallbackToChat(item.name)+ return null+ }+ },+ [app, fallbackToChat]+ )++ return <CohortListView data={data} onCohortClick={handleClick} />+}++function ErrorIssueListContent({ data, app }: { data: ErrorIssueListData; app: App | null }): JSX.Element {+ const fallbackToChat = useCallback(+ (name: string) => {+ app?.sendMessage({+ role: 'user',+ content: [{ type: 'text', text: `Show me the details for error issue "${name}"` }],+ })+ },+ [app]+ )++ const handleClick = useCallback(+ async (item: ErrorIssueData): Promise<ErrorIssueData | null> => {+ if (!app) {+ fallbackToChat(item.name)+ return null+ }+ try {+ const result = await app.callServerTool({+ name: 'query-error-tracking-issue',+ arguments: { issueId: item.id },+ })+ if (result.isError || !result.structuredContent) {+ fallbackToChat(item.name)+ return null+ }+ return result.structuredContent as unknown as ErrorIssueData+ } catch {+ fallbackToChat(item.name)+ return null+ }+ },+ [app, fallbackToChat]+ )++ return <ErrorIssueListView data={data} onIssueClick={handleClick} />+}++function ExperimentListContent({ data, app }: { data: ExperimentListData; app: App | null }): JSX.Element {+ const fallbackToChat = useCallback(+ (name: string) => {+ app?.sendMessage({+ role: 'user',+ content: [{ type: 'text', text: `Show me the details for experiment "${name}"` }],+ })+ },+ [app]+ )++ const handleClick = useCallback(+ async (item: ExperimentData): Promise<ExperimentData | null> => {+ if (!app) {+ fallbackToChat(item.name)+ return null+ }+ try {+ const result = await app.callServerTool({+ name: 'experiment-get',+ arguments: { id: item.id },+ })+ if (result.isError || !result.structuredContent) {+ fallbackToChat(item.name)+ return null+ }+ return result.structuredContent as unknown as ExperimentData+ } catch {+ fallbackToChat(item.name)+ return null+ }+ },+ [app, fallbackToChat]+ )++ return <ExperimentListView data={data} onExperimentClick={handleClick} />+}++function FeatureFlagListContent({ data, app }: { data: FeatureFlagListData; app: App | null }): JSX.Element {+ const fallbackToChat = useCallback(+ (name: string) => {+ app?.sendMessage({+ role: 'user',+ content: [{ type: 'text', text: `Show me the details for feature flag "${name}"` }],+ })+ },+ [app]+ )++ const handleClick = useCallback(+ async (item: FeatureFlagData): Promise<FeatureFlagData | null> => {+ if (!app) {+ fallbackToChat(item.key)+ return null+ }+ try {+ const result = await app.callServerTool({+ name: 'feature-flag-get-definition',+ arguments: { flagId: item.id },+ })+ if (result.isError || !result.structuredContent) {+ fallbackToChat(item.key)+ return null+ }+ return result.structuredContent as unknown as FeatureFlagData+ } catch {+ fallbackToChat(item.key)+ return null+ }+ },+ [app, fallbackToChat]+ )++ return <FeatureFlagListView data={data} onFlagClick={handleClick} />+}++function SurveyListContent({ data, app }: { data: SurveyListData; app: App | null }): JSX.Element {+ const fallbackToChat = useCallback(+ (name: string) => {+ app?.sendMessage({+ role: 'user',+ content: [{ type: 'text', text: `Show me the details for survey "${name}"` }],+ })+ },+ [app]+ )++ const handleClick = useCallback(+ async (item: SurveyData): Promise<SurveyData | null> => {+ if (!app) {+ fallbackToChat(item.name)+ return null+ }+ try {+ const result = await app.callServerTool({+ name: 'survey-get',+ arguments: { surveyId: item.id },+ })+ if (result.isError || !result.structuredContent) {+ fallbackToChat(item.name)+ return null+ }+ return result.structuredContent as unknown as SurveyData+ } catch {+ fallbackToChat(item.name)+ return null+ }+ },+ [app, fallbackToChat]+ )++ return <SurveyListView data={data} onSurveyClick={handleClick} />+}++function TraceSpanListContent({ data, app }: { data: TraceSpanListData; app: App | null }): JSX.Element {+ const fallbackToChat = useCallback(+ (name: string) => {+ app?.sendMessage({+ role: 'user',+ content: [{ type: 'text', text: `Show me the details for trace span "${name}"` }],+ })+ },+ [app]+ )++ const handleClick = useCallback(+ async (item: TraceSpanData): Promise<TraceSpanData | null> => {+ if (!app) {+ fallbackToChat(item.name)+ return null+ }+ try {+ const result = await app.callServerTool({+ name: 'apm-trace-get',+ arguments: { trace_id: item.trace_id },+ })+ if (result.isError || !result.structuredContent) {+ fallbackToChat(item.name)+ return null+ }+ return result.structuredContent as unknown as TraceSpanData+ } catch {+ fallbackToChat(item.name)+ return null+ }+ },+ [app, fallbackToChat]+ )++ return <TraceSpanListView data={data} onSpanClick={handleClick} />+}++function WorkflowListContent({ data, app }: { data: WorkflowListData; app: App | null }): JSX.Element {+ const fallbackToChat = useCallback(+ (name: string) => {+ app?.sendMessage({+ role: 'user',+ content: [{ type: 'text', text: `Show me the details for workflow "${name}"` }],+ })+ },+ [app]+ )++ const handleClick = useCallback(+ async (item: WorkflowData): Promise<WorkflowData | null> => {+ if (!app) {+ fallbackToChat(item.name)+ return null+ }+ try {+ const result = await app.callServerTool({+ name: 'workflows-get',+ arguments: { id: item.id },+ })+ if (result.isError || !result.structuredContent) {+ fallbackToChat(item.name)+ return null+ }+ return result.structuredContent as unknown as WorkflowData+ } catch {+ fallbackToChat(item.name)+ return null+ }+ },+ [app, fallbackToChat]+ )++ return <WorkflowListView data={data} onWorkflowClick={handleClick} />+}++export const RENDER_DISPATCH: Partial<Record<UiAppKey, (props: RenderDispatchProps) => JSX.Element>> = {+ action: ({ data }) => <ActionView action={data as ActionData} />,+ 'action-list': ({ data, app }) => <ActionListContent data={data as ActionListData} app={app} />,+ cohort: ({ data }) => <CohortView cohort={data as CohortData} />,+ 'cohort-list': ({ data, app }) => <CohortListContent data={data as CohortListData} app={app} />,+ 'error-details': ({ data }) => <ErrorDetailsView data={data as ErrorDetailsData} />,+ 'error-issue': ({ data }) => <ErrorIssueView issue={data as ErrorIssueData} />,+ 'error-issue-list': ({ data, app }) => <ErrorIssueListContent data={data as ErrorIssueListData} app={app} />,+ experiment: ({ data }) => <ExperimentView experiment={data as ExperimentData} />,+ 'experiment-list': ({ data, app }) => <ExperimentListContent data={data as ExperimentListData} app={app} />,+ 'experiment-results': ({ data }) => <ExperimentResultsView data={data as ExperimentResultsData} />,+ 'feature-flag': ({ data }) => <FeatureFlagView flag={data as FeatureFlagData} />,+ 'feature-flag-list': ({ data, app }) => <FeatureFlagListContent data={data as FeatureFlagListData} app={app} />,+ 'feature-flag-testing': ({ data }) => <FeatureFlagTestingView flag={data as FeatureFlagTestingData} />,+ 'insight-actors': ({ data, openLink }) => (+ <InsightActorsView data={data as InsightActorsData} openLink={openLink} />+ ),+ 'llm-costs': ({ data }) => <LLMCostsView data={data as LLMCostsData} />,+ 'session-recording': ({ data }) => <SessionRecordingView recording={data as SessionRecordingData} />,+ 'session-summary': ({ data }) => <SessionSummaryView data={data as SessionSummaryData} />,+ survey: ({ data }) => <SurveyView survey={data as SurveyData} />,+ 'survey-global-stats': ({ data }) => <SurveyStatsView data={data as SurveyStatsData} />,+ 'survey-list': ({ data, app }) => <SurveyListContent data={data as SurveyListData} app={app} />,+ 'survey-stats': ({ data }) => <SurveyStatsView data={data as SurveyStatsData} />,+ 'trace-span': ({ data }) => <TraceSpanView data={data as TraceSpanData} />,+ 'trace-span-list': ({ data, app }) => <TraceSpanListContent data={data as TraceSpanListData} app={app} />,+ workflow: ({ data }) => <WorkflowView workflow={data as WorkflowData} />,+ 'workflow-list': ({ data, app }) => <WorkflowListContent data={data as WorkflowListData} app={app} />,+}diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsindex 3e5ddd1dddea..8d99a4d2e03f 100644--- a/services/mcp/tests/hono/analytics.test.ts+++ b/services/mcp/tests/hono/analytics.test.ts@@ -55,6 +55,7 @@ function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {allTools: [],scopeGatedTools: [],distinctId: 'distinct-id',+ renderUiEnabled: false,...overrides,}}diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsindex b573a05014a3..7e444ba23c46 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -7,6 +7,7 @@ const { mockSessionStore, mockTokenStore } = vi.hoisted(() => ({vi.mock('@/lib/posthog/flags', () => ({evaluateFeatureFlags: vi.fn(async () => ({})),+ resolveFeatureFlagOverrides: vi.fn(() => ({})),}))vi.mock('@/hono/request-context', () => {@@ -66,6 +67,7 @@ vi.mock('@/hono/request-context', () => {import type { RedisLike } from '@/hono/cache/RedisCache'import { RequestStateResolver } from '@/hono/request-state-resolver'+import { evaluateFeatureFlags, resolveFeatureFlagOverrides } from '@/lib/posthog/flags'import type { RequestProperties } from '@/lib/request-properties'import type { Env } from '@/tools/types'@@ -223,6 +225,63 @@ describe('RequestStateResolver MCP client contexts', () => {expect(mockSessionStore.get('mcpVendorClient')).toBe('ClaudeCode')})+ it('puts Claude web/desktop in single-exec when the render-ui flag is on', async () => {+ vi.mocked(evaluateFeatureFlags).mockResolvedValueOnce({ 'mcp-render-ui': true })+ const props = makeProps({ mcpClientName: 'Claude Desktop', mcpVendorClient: 'ClaudeAI' })+ const result = await makeResolver().resolve(props)++ expect(result.renderUiEnabled).toBe(true)+ expect(result.useSingleExec).toBe(true)+ expect(props.mode).toBe('cli')+ })++ it('keeps Claude web/desktop in tools mode when the render-ui flag is off', async () => {+ // A `ClaudeAI` vendor header is unconditionally single-exec, so the render-ui+ // gate only observably matters on the User-Agent-only path, where the client+ // isn't otherwise a CLI-mode client.+ const props = makeProps({ mcpClientName: 'Claude Desktop', clientUserAgent: 'Claude-User' })+ const result = await makeResolver().resolve(props)++ expect(result.renderUiEnabled).toBe(false)+ expect(result.useSingleExec).toBe(false)+ expect(props.mode).toBe('tools')+ })++ it('does not enable render-ui for Claude Code even when the flag is on', async () => {+ // Claude Code pools the same `mcp-render-ui` flag value as Claude web/desktop, but+ // it isn't an MCP Apps host — it can't mount the iframe. It must stay in single-exec+ // (it's a CLI client) while `renderUiEnabled` resolves to false, so the tool-executor+ // never advertises or accepts `render-ui` for it.+ vi.mocked(evaluateFeatureFlags).mockResolvedValueOnce({ 'mcp-render-ui': true })+ const props = makeProps({ mcpClientName: 'Anthropic/ClaudeAI', mcpVendorClient: 'ClaudeCode' })+ const result = await makeResolver().resolve(props)++ expect(result.renderUiEnabled).toBe(false)+ expect(result.useSingleExec).toBe(true)+ expect(result.toolFeatureFlags?.['mcp-render-ui']).toBe(true)+ })++ it('detects Claude web/desktop via the Claude-User user agent', async () => {+ vi.mocked(evaluateFeatureFlags).mockResolvedValueOnce({ 'mcp-render-ui': true })+ const props = makeProps({ mcpClientName: 'Claude Desktop', clientUserAgent: 'Claude-User' })+ const result = await makeResolver().resolve(props)++ expect(result.useSingleExec).toBe(true)+ expect(props.mode).toBe('cli')+ })++ it('honors a dev/test flag override even when evaluation returns nothing', async () => {+ // Evaluation stays empty (analytics client disabled, as in local dev/evals);+ // the override seam is what flips the flag on.+ vi.mocked(resolveFeatureFlagOverrides).mockReturnValueOnce({ 'mcp-render-ui': true })+ const props = makeProps({ mcpClientName: 'Claude Desktop', mcpVendorClient: 'ClaudeAI' })+ const result = await makeResolver().resolve(props)++ expect(result.renderUiEnabled).toBe(true)+ expect(result.useSingleExec).toBe(true)+ expect(result.toolFeatureFlags?.['mcp-render-ui']).toBe(true)+ })+it('captures consumer from a later request when initialize omitted the header', async () => {await makeResolver().resolve(makeProps({diff --git a/services/mcp/tests/hono/session-mode-pool.test.ts b/services/mcp/tests/hono/session-mode-pool.test.tsindex 80f636b7d282..75a18d388ef7 100644--- a/services/mcp/tests/hono/session-mode-pool.test.ts+++ b/services/mcp/tests/hono/session-mode-pool.test.ts@@ -131,19 +131,19 @@ describe('Resolved mode is preserved across pooled-transport vendor flips', () =expect(sessionId).toBeTruthy()// Client caches the tools payload at init. cli mode collapses the wire- // roster to a single `exec`.+ // roster to the single `exec` umbrella tool (the sibling `render-ui` tool+ // is gated behind the `mcp-render-ui` flag, which is off in tests).const cachedTools = await clientA.listTools()- expect(cachedTools.tools).toHaveLength(1)- expect(cachedTools.tools[0]!.name).toBe('exec')+ expect(cachedTools.tools.map((t) => t.name).sort()).toEqual(['exec'])// headers_2 — pool member flipping to a different Anthropic vendor.// `ClaudeAI` is itself an Anthropic client, so it resolves to cli mode on// its own merits; combined with the cached session hints from init, the- // request stays in cli mode and the roster still collapses to a single- // `exec`. Every Anthropic vendor (the `x-anthropic-client` header) runs- // in cli mode, so no pooled vendor flip can downgrade to tools mode.+ // request stays in cli mode and the roster still collapses to the `exec`+ // umbrella tool. Every Anthropic vendor (the `x-anthropic-client` header)+ // runs in cli mode, so no pooled vendor flip can downgrade to tools mode.const pooledRoster = await listToolsOnSession(sessionId!, 'ClaudeAI')- expect(pooledRoster.map((t) => t.name)).toEqual(['exec'])+ expect(pooledRoster.map((t) => t.name).sort()).toEqual(['exec'])await clientA.close()})diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 9fdc246a44c0..679fef1c5f23 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -77,6 +77,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>allTools: tools as any,scopeGatedTools: [],distinctId: 'test-distinct-id',+ renderUiEnabled: false,...overrides,}}diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex de88d81c2ef6..528a0af88cb1 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -15,6 +15,14 @@ import { InstructionsBuilder } from '@/hono/instructions'import type { ResolvedState } from '@/hono/request-state-resolver'import { ToolCatalog } from '@/hono/tool-catalog'import { ToolExecutor } from '@/hono/tool-executor'+import { RENDER_UI_RESOURCE_URI, URI_MAP } from '@/resources/ui-apps.generated'++// A tool with a renderable (dispatchable) UI app — used to exercise the render-ui path.+const uiAppTool = {+ name: 'survey-get',+ annotations: { readOnlyHint: true },+ _meta: { ui: { resourceUri: URI_MAP['survey'] } },+}function makeState(tools: { name: string }[], overrides: Partial<ResolvedState> = {}): ResolvedState {return {@@ -51,6 +59,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>allTools: tools as any,scopeGatedTools: [],distinctId: 'test-distinct-id',+ renderUiEnabled: false,...overrides,}}@@ -168,5 +177,55 @@ describe('ToolExecutor', () => {expect(result.tools).toHaveLength(1)expect(result.tools[0]!.name).toBe('exec')})++ it('lists render-ui alongside exec when render-ui is enabled and a UI-app tool is available', async () => {+ const state = makeState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })++ const result = await executor.handleToolsList(state)+ expect(result.tools.map((t) => t.name)).toEqual(['exec', 'render-ui'])++ // The advertised schema is derived from the zod validation schema —+ // pin the contract the agent writes calls against.+ 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!.description).toBeTruthy()+ expect(properties.tool_input!.description).toBeTruthy()+ expect(renderUiEntry.inputSchema.required).toEqual(['tool_name'])+ })++ it('omits render-ui when the flag is off, even with a UI-app tool available', async () => {+ const state = makeState([uiAppTool], { useSingleExec: true, renderUiEnabled: false })++ const result = await executor.handleToolsList(state)+ expect(result.tools.map((t) => t.name)).toEqual(['exec'])+ })+ })++ describe('render-ui', () => {+ it('dispatches to the render-ui payload when the flag is on', async () => {+ const state = makeState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })++ const result = (await executor.handleToolCall(+ { name: 'render-ui', arguments: { tool_name: 'survey-get', tool_input: { surveyId: 'abc' } } },+ state+ )) as any++ expect(result._meta.ui.resourceUri).toBe(RENDER_UI_RESOURCE_URI)+ expect(result.structuredContent.tool_name).toBe('survey-get')+ expect(result.structuredContent.app_key).toBe('survey')+ })++ it('rejects a render-ui call when the flag is off', async () => {+ const state = makeState([uiAppTool], { useSingleExec: true, renderUiEnabled: false })++ const result = (await executor.handleToolCall(+ { name: 'render-ui', arguments: { tool_name: 'survey-get', tool_input: { surveyId: 'abc' } } },+ state+ )) as any++ expect(result.isError).toBe(true)+ expect(result.content[0].text).toContain('not found')+ })})})diff --git a/services/mcp/tests/integration/mcp-protocol-suite.ts b/services/mcp/tests/integration/mcp-protocol-suite.tsindex 1383e57c50f6..266f0c149d31 100644--- a/services/mcp/tests/integration/mcp-protocol-suite.ts+++ b/services/mcp/tests/integration/mcp-protocol-suite.ts@@ -48,9 +48,10 @@ function buildStreamableClient(return { client, transport }}-function buildExecModeClient(- harness: ProtocolTestHarness-): { client: Client; transport: StreamableHTTPClientTransport } {+function buildExecModeClient(harness: ProtocolTestHarness): {+ client: Client+ transport: StreamableHTTPClientTransport+} {const transport = new StreamableHTTPClientTransport(new URL('/mcp', harness.baseUrl), {fetch: harness.fetch,requestInit: {@@ -1591,10 +1592,12 @@ export function defineExecModeTests(await safeClose(client)})- it('lists only the exec tool when in cli mode', async () => {+ it('lists the exec umbrella tool in cli mode', async () => {const { tools } = await client.listTools()- expect(tools).toHaveLength(1)- expect(tools[0]!.name).toBe('exec')+ // The sibling `render-ui` tool is gated behind the `mcp-render-ui` flag,+ // which is off in this environment (analytics client disabled), so the+ // cli-mode roster collapses to just `exec`.+ expect(tools.map((t) => t.name).sort()).toEqual(['exec'])})it('exec "tools" lists available inner tools', async () => {diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txtindex 58bb90a1386a..485a5e03a3af 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt@@ -109,6 +109,31 @@ WRONG — the real event might be `file_downloaded`, `download_completed`, or no- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.- If a tool name doesn't exist, run `tools` again to find the correct name.+### Rendering visualizations++`render-ui` is a separate tool (not an `exec` command) — see its own description for the full enum and worked examples. When your answer centers on an entity or list whose tool is in `render-ui`'s `tool_name` enum, strongly prefer rendering it **in addition to** your written summary (not instead of it), so the user can verify the result instead of trusting a text dump — not only when they explicitly ask to "see" something. Reach for it on: status/health, lists/inventory, results/stats, post-mutation verification, and evidence surfaced mid-investigation. Pass the same `tool_input` you would `call` the tool with; it fetches its own data. Never invent a `tool_name`. (Results from `query-*` tools render through their own app automatically — do not route those through `render-ui`.)++ALWAYS run `exec` first. `render-ui` is the final presentation step, never a discovery step — use `exec` (`search`/`info`/`schema`/`call`) to resolve the entity's real ID and confirm the data, then render. Never render before exec, and never with a guessed `tool_input`.++<example>+User: How is the "File engagement boost" experiment going?+Assistant: [exec first: search/info/call to resolve it to id 2 and read its results]+Assistant: <concise summary of the results>, then renders it so the user can verify.+[Runs render-ui({ "tool_name": "experiment-get", "tool_input": { "id": 2 } })]+</example>++<bad-example>+User: How is the "File engagement boost" experiment going?+Assistant: [Calls render-ui with a guessed id before running any exec command]+WRONG — run exec first to resolve the real id and read the results; render-ui is not a discovery tool.+</bad-example>++<bad-example>+User: How is the "File engagement boost" experiment going?+Assistant: [Reads the results via exec, then replies with a long text-only breakdown of every metric and never calls render-ui]+WRONG — the answer centers on a single experiment, which has a UI app (`experiment-get` is in `render-ui`'s enum). Render it with render-ui so the user can see and verify the results, then add your summary. Strongly prefer render-and-summarize over a text dump alone.+</bad-example>+### Basic functionalityYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.diff --git a/services/mcp/tests/unit/client-detection.test.ts b/services/mcp/tests/unit/client-detection.test.tsindex 044920a003c4..325bb69e86c1 100644--- a/services/mcp/tests/unit/client-detection.test.ts+++ b/services/mcp/tests/unit/client-detection.test.ts@@ -2,11 +2,14 @@ import { describe, expect, it } from 'vitest'import {ANTHROPIC_CLIENT_NAME_FRAGMENTS,+ ANTHROPIC_UI_HOST_USER_AGENT_FRAGMENTS,+ ANTHROPIC_UI_HOST_VENDOR_FRAGMENTS,CODING_AGENT_CLIENT_NAME_FRAGMENTS,DEFAULT_CLIENT_CAPABILITIES,MCPClientProfile,POSTHOG_CODE_CONSUMER,VIBE_CODING_OAUTH_CLIENT_NAME_FRAGMENTS,+ isClaudeUiHostClient,isCliModeEnabledClient,isPostHogCodeConsumer,isVibeCodingClient,@@ -169,6 +172,38 @@ describe('isVibeCodingClient', () => {})})+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([@@ -294,6 +329,54 @@ 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 false for Cowork (vendorClient: Cowork)', () => {+ expect(new MCPClientProfile({ vendorClient: 'Cowork' }).isClaudeUiHost()).toBe(false)+ })++ it('vendor client wins over a shared Claude-User user-agent', () => {+ // Cowork and Claude Code can share the `Claude-User` user-agent with+ // web/desktop, but their vendor client is authoritative and excludes them.+ expect(new MCPClientProfile({ vendorClient: 'Cowork', userAgent: 'Claude-User' }).isClaudeUiHost()).toBe(+ false+ )+ 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)+ })++ it('returns false when nothing is set', () => {+ expect(new MCPClientProfile({}).isClaudeUiHost()).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)+ })+ })+describe('capabilities.supportsInstructions', () => {it.each([['codex'], ['Codex'], ['CODEX'], ['codex-cli'], ['Codex CLI'], ['codex/1.2.3'], ['openai-codex']])('is false for Codex variant %s',@@ -332,12 +415,14 @@ describe('MCPClientProfile', () => {consumer: POSTHOG_CODE_CONSUMER,oauthClientName: 'Lovable',vendorClient: 'ClaudeCode',+ userAgent: 'Claude-User',})expect(profile.clientName).toBe('claude-code')expect(profile.clientVersion).toBe('1.2.3')expect(profile.consumer).toBe(POSTHOG_CODE_CONSUMER)expect(profile.oauthClientName).toBe('Lovable')expect(profile.vendorClient).toBe('ClaudeCode')+ expect(profile.userAgent).toBe('Claude-User')})})diff --git a/services/mcp/tests/unit/feature-flag-overrides.test.ts b/services/mcp/tests/unit/feature-flag-overrides.test.tsnew file mode 100644index 000000000000..b09aae5fb656--- /dev/null+++ b/services/mcp/tests/unit/feature-flag-overrides.test.ts@@ -0,0 +1,56 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'++import { resolveFeatureFlagOverrides } from '@/lib/posthog/flags'++describe('resolveFeatureFlagOverrides', () => {+ const ORIG_OVERRIDES = process.env.FEATURE_FLAG_OVERRIDES+ const ORIG_NODE_ENV = process.env.NODE_ENV++ beforeEach(() => {+ delete process.env.FEATURE_FLAG_OVERRIDES+ process.env.NODE_ENV = 'test'+ })++ afterEach(() => {+ if (ORIG_OVERRIDES === undefined) {+ delete process.env.FEATURE_FLAG_OVERRIDES+ } else {+ process.env.FEATURE_FLAG_OVERRIDES = ORIG_OVERRIDES+ }+ process.env.NODE_ENV = ORIG_NODE_ENV+ })++ it('parses the env JSON object with boolean and variant values', () => {+ process.env.FEATURE_FLAG_OVERRIDES = JSON.stringify({ 'mcp-render-ui': true, 'some-flag': 'variant-a' })+ expect(resolveFeatureFlagOverrides()).toEqual({ 'mcp-render-ui': true, 'some-flag': 'variant-a' })+ })++ it('lets a per-request override win over the env var', () => {+ process.env.FEATURE_FLAG_OVERRIDES = JSON.stringify({ 'mcp-render-ui': false })+ expect(resolveFeatureFlagOverrides(JSON.stringify({ 'mcp-render-ui': true }))).toEqual({+ 'mcp-render-ui': true,+ })+ })++ it('ignores non-boolean/string values, arrays, and malformed JSON', () => {+ process.env.FEATURE_FLAG_OVERRIDES = JSON.stringify({ a: 1, b: true, c: null, d: { nested: 1 } })+ expect(resolveFeatureFlagOverrides('not-json')).toEqual({ b: true })+ expect(resolveFeatureFlagOverrides('[1,2,3]')).toEqual({ b: true })+ })++ it('is a no-op in production, even with overrides set', () => {+ process.env.NODE_ENV = 'production'+ process.env.FEATURE_FLAG_OVERRIDES = JSON.stringify({ 'mcp-render-ui': true })+ expect(resolveFeatureFlagOverrides(JSON.stringify({ x: true }))).toEqual({})+ })++ it('fails closed when NODE_ENV is unset, even with overrides set', () => {+ delete process.env.NODE_ENV+ process.env.FEATURE_FLAG_OVERRIDES = JSON.stringify({ 'mcp-render-ui': true })+ expect(resolveFeatureFlagOverrides(JSON.stringify({ x: true }))).toEqual({})+ })++ it('returns an empty object when nothing is set', () => {+ expect(resolveFeatureFlagOverrides()).toEqual({})+ })+})diff --git a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts b/services/mcp/tests/unit/instructions-formatter-snapshot.test.tsindex a07c2a5c03d0..89b21deffbf8 100644--- a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts+++ b/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts@@ -41,7 +41,8 @@ const STATIC_CTX: InstructionsContext = {metadata: STATIC_METADATA,tools: STATIC_TOOLS,queryTools: STATIC_QUERY_TOOLS,- featureFlags: { 'mcp-feedback-tool': true },+ featureFlags: { 'mcp-feedback-tool': true, 'mcp-render-ui': true },+ renderUiEnabled: true,}const __dirname = path.dirname(fileURLToPath(import.meta.url))diff --git a/services/mcp/tests/unit/instructions-formatter.test.ts b/services/mcp/tests/unit/instructions-formatter.test.tsindex b4c93b26b565..900c3e1c48e6 100644--- a/services/mcp/tests/unit/instructions-formatter.test.ts+++ b/services/mcp/tests/unit/instructions-formatter.test.ts@@ -34,7 +34,8 @@ const fullCtx: InstructionsContext = {metadata: realisticMetadata,tools: realisticTools,queryTools: realisticQueryTools,- featureFlags: { 'mcp-feedback-tool': true },+ featureFlags: { 'mcp-feedback-tool': true, 'mcp-render-ui': true },+ renderUiEnabled: true,}describe('InstructionsFormatter', () => {@@ -202,6 +203,22 @@ describe('InstructionsFormatter', () => {expect(withoutFeedback).not.toContain('### Sharing feedback on this MCP server')}})++ it('includes the rendering section only when render-ui is available for the client', () => {+ const formatter = new InstructionsFormatter()+ for (const stripEnvContext of [true, false]) {+ const withRendering = formatter.buildExecCommandReference(fullCtx, { stripEnvContext })+ expect(withRendering).toContain('### Rendering visualizations')++ // The raw flag being on isn't enough — a non-UI-host client (e.g. Claude Code)+ // resolves `renderUiEnabled` to false and must not see the rendering section.+ const withoutRendering = formatter.buildExecCommandReference(+ { ...fullCtx, renderUiEnabled: false },+ { stripEnvContext }+ )+ expect(withoutRendering).not.toContain('### Rendering visualizations')+ }+ })})// Mirrors the single-exec wiring in `src/mcp.ts`. When the client honors the MCPdiff --git a/services/mcp/tests/unit/protocol-types.test.ts b/services/mcp/tests/unit/protocol-types.test.tsindex 8068a0ebb9c3..d8a4487420d2 100644--- a/services/mcp/tests/unit/protocol-types.test.ts+++ b/services/mcp/tests/unit/protocol-types.test.ts@@ -11,6 +11,7 @@ describe('resolveMode', () => {const base = {mode: undefined as undefined,clientProfile: profile(),+ renderUiFlagEnabled: false,}it('defaults to tools mode, no single exec', () => {@@ -61,4 +62,44 @@ describe('resolveMode', () => {})expect(result.useSingleExec).toBe(true)})++ it('Claude web/desktop activates single exec when render-ui is enabled', () => {+ const result = resolveMode({+ ...base,+ clientProfile: profile({ vendorClient: 'ClaudeAI' }),+ renderUiFlagEnabled: true,+ })+ expect(result).toEqual({ mode: 'cli', useSingleExec: true })+ })++ it('Claude web/desktop detected via User-Agent activates single exec when render-ui is enabled', () => {+ const result = resolveMode({+ ...base,+ clientProfile: profile({ userAgent: 'Claude-User' }),+ renderUiFlagEnabled: true,+ })+ expect(result.useSingleExec).toBe(true)+ })++ it('Claude web/desktop detected via User-Agent stays in tools mode when render-ui is disabled', () => {+ // A `ClaudeAI` vendor header is unconditionally single-exec, so the render-ui+ // gate only observably matters on the User-Agent-only path, where the client+ // isn't otherwise a CLI-mode client.+ const result = resolveMode({+ ...base,+ clientProfile: profile({ userAgent: 'Claude-User' }),+ renderUiFlagEnabled: false,+ })+ expect(result.useSingleExec).toBe(false)+ })++ it('explicit mode=tools wins over Claude UI host even with render-ui enabled', () => {+ const result = resolveMode({+ ...base,+ mode: 'tools',+ clientProfile: profile({ vendorClient: 'ClaudeAI' }),+ renderUiFlagEnabled: true,+ })+ expect(result.useSingleExec).toBe(false)+ })})diff --git a/services/mcp/tests/unit/render-ui.test.ts b/services/mcp/tests/unit/render-ui.test.tsnew file mode 100644index 000000000000..b417d8ce267a--- /dev/null+++ b/services/mcp/tests/unit/render-ui.test.ts@@ -0,0 +1,91 @@+import { describe, expect, it } from 'vitest'+import { z } from 'zod'++import { isToolCallPayload, type ToolResultPayload } from '@/lib/build-tool-result'+import { RENDER_UI_RESOURCE_URI, URI_MAP } from '@/resources/ui-apps.generated'+import { createRenderUiTool, getRenderableToolNames, RENDER_UI_TOOL_NAME } from '@/tools/render-ui'+import { type Context, type Tool, type ZodObjectAny } from '@/tools/types'++const mockContext = {+ getDistinctId: async () => 'test-distinct-id',+} as unknown as Context++function makeTool(name: string, resourceUri?: string): Tool<ZodObjectAny> {+ return {+ name,+ title: name,+ description: `Tool ${name}`,+ schema: z.object({}),+ scopes: [],+ annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: false, readOnlyHint: true },+ handler: async () => ({ ok: true }),+ ...(resourceUri ? { _meta: { ui: { resourceUri } } } : {}),+ }+}++// A detail app (`survey`) is dispatchable; a custom app (`debug`) is not.+const surveyTool = makeTool('survey-get', URI_MAP['survey'])+const debugTool = makeTool('debug-tool', URI_MAP['debug'])+const plainTool = makeTool('plain-tool')++describe('render-ui tool', () => {+ it('only counts tools whose UI app has a generated view as renderable', () => {+ expect(getRenderableToolNames([surveyTool, debugTool, plainTool])).toEqual(['survey-get'])+ })++ it('excludes non-read-only tools so render-ui cannot dispatch mutating tools', () => {+ const mutatingTool = makeTool('survey-launch', URI_MAP['survey'])+ mutatingTool.annotations.readOnlyHint = false+ expect(getRenderableToolNames([mutatingTool])).toEqual([])+ })++ it('returns null when no tool has a renderable UI app', () => {+ expect(createRenderUiTool([debugTool, plainTool], mockContext)).toBeNull()+ })++ it('restricts tool_name to the renderable tools', () => {+ const tool = createRenderUiTool([surveyTool, debugTool, plainTool], mockContext)+ expect(tool).not.toBeNull()+ const schema = tool!.schema++ expect(schema.safeParse({ tool_name: 'survey-get', tool_input: { surveyId: 'abc' } }).success).toBe(true)+ // Non-UI and custom-app tools are not valid enum members.+ expect(schema.safeParse({ tool_name: 'plain-tool' }).success).toBe(false)+ expect(schema.safeParse({ tool_name: 'debug-tool' }).success).toBe(false)+ })++ it('emits a render directive payload with the envelope and render-ui resourceUri', async () => {+ const tool = createRenderUiTool([surveyTool, debugTool, plainTool], mockContext)!+ const result = (await tool.handler(mockContext, {+ tool_name: 'survey-get',+ tool_input: { surveyId: 'abc' },+ })) as ToolResultPayload++ expect(isToolCallPayload(result)).toBe(true)+ expect(result.structuredContent).toEqual({+ tool_name: 'survey-get',+ tool_input: { surveyId: 'abc' },+ app_key: 'survey',+ _analytics: { distinctId: 'test-distinct-id', toolName: RENDER_UI_TOOL_NAME },+ })+ expect(result._meta?.ui).toEqual({ resourceUri: RENDER_UI_RESOURCE_URI })+ })++ it('defaults tool_input to an empty object when omitted', async () => {+ const tool = createRenderUiTool([surveyTool], mockContext)!+ const result = (await tool.handler(mockContext, { tool_name: 'survey-get' })) as ToolResultPayload+ expect((result.structuredContent as Record<string, unknown>).tool_input).toEqual({})+ })++ it('does not execute the inner tool — it only emits a render directive', async () => {+ let innerCalled = false+ const spyTool = makeTool('survey-get', URI_MAP['survey'])+ spyTool.handler = async () => {+ innerCalled = true+ return { ok: true }+ }+ const tool = createRenderUiTool([spyTool], mockContext)!+ await tool.handler(mockContext, { tool_name: 'survey-get' })+ expect(innerCalled).toBe(false)+ })+})diff --git a/services/mcp/tests/unit/ui-apps.test.ts b/services/mcp/tests/unit/ui-apps.test.tsindex 91463fc3cffd..ae4352b1e2ce 100644--- a/services/mcp/tests/unit/ui-apps.test.ts+++ b/services/mcp/tests/unit/ui-apps.test.ts@@ -1,7 +1,9 @@import { describe, expect, it, vi } from 'vitest'import { buildAppStubHtml } from '@/resources/ui-apps'-import { UI_APPS, URI_MAP } from '@/resources/ui-apps.generated'+import { DISPATCHABLE_APP_KEYS, UI_APPS, URI_MAP } from '@/resources/ui-apps.generated'++import { generateDispatchModule, resolveDetailApp, resolveListApp } from '../../scripts/generate-ui-apps'describe('ui-apps', () => {describe('buildAppStubHtml', () => {@@ -205,4 +207,44 @@ describe('ui-apps', () => {expect(result.contents[0].mimeType).toBe('text/html;profile=mcp-app')})})++ describe('render-ui dispatch', () => {+ it('DISPATCHABLE_APP_KEYS excludes custom apps', () => {+ expect(DISPATCHABLE_APP_KEYS).toContain('survey')+ expect(DISPATCHABLE_APP_KEYS).toContain('survey-list')+ for (const customKey of ['debug', 'query-results', 'render-ui', 'visual-review-snapshots']) {+ expect(DISPATCHABLE_APP_KEYS).not.toContain(customKey)+ }+ })++ it('generates a dispatch entry per detail/list app and a Content component for list apps', () => {+ const code = generateDispatchModule([+ {+ appKey: 'survey',+ type: 'detail',+ config: resolveDetailApp(+ 'survey',+ { type: 'detail', view_prop: 'survey' },+ 'products/surveys/mcp/apps'+ ),+ },+ {+ appKey: 'survey-list',+ type: 'list',+ config: resolveListApp(+ 'survey-list',+ { type: 'list', detail_tool: 'survey-get' },+ 'products/surveys/mcp/apps'+ ),+ },+ ])++ expect(code).toContain("'survey': ({ data }) => <SurveyView survey={data as SurveyData} />")+ expect(code).toContain(+ "'survey-list': ({ data, app }) => <SurveyListContent data={data as SurveyListData} app={app} />"+ )+ expect(code).toContain('function SurveyListContent(')+ expect(code).toContain("name: 'survey-get'")+ })+ })})