Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

4.7 KB
Raw Blame
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 { capture } from '../analytics/posthog'
import { AppErrorState } from '../components/AppErrorState'
import { AppLoadingState } from '../components/AppLoadingState'
import { AppWrapper } from '../components/AppWrapper'
import { RENDER_DISPATCH } from '../generated/render-dispatch.generated'
import { loadRenderUiData } from './render-ui-data'

/**
 * Envelope emitted by the `render-ui` server tool. It carries the tool to render
 * and its input, never the data itself. The data arrives preloaded on the result's
 * app-only `_meta`, or the app fetches it via `callServerTool`, then 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, resultMeta, app, openLink }) => (
                <RenderUiContent envelope={data!} resultMeta={resultMeta} app={app} openLink={openLink} />
            )}
        </AppWrapper>
    )
}

function RenderUiContent({
    envelope,
    resultMeta,
    app,
    openLink,
}: {
    envelope: RenderUiEnvelope
    resultMeta: Record<string, unknown> | null
    app: App | null
    openLink: (url: string) => void
}): JSX.Element {
    const [data, setData] = useState<unknown>(null)
    const [error, setError] = useState<{
        reason: string
        message: string
        errorName?: string
        errorCode?: number
    } | 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 appKey = envelope.app_key
    const toolInputJson = JSON.stringify(envelope.tool_input ?? {})
    useEffect(() => {
        capture('mcp_ui_app_render_requested', { rendered_tool_name: toolName, app_key: envelope.app_key })
    }, [toolName, envelope.app_key])
    useEffect(() => {
        if (!app) {
            setError({ reason: 'no_app', message: 'Visualization unavailable: app context not provided.' })
            return
        }
        let cancelled = false
        setData(null)
        setError(null)
        loadRenderUiData(app, toolName, JSON.parse(toolInputJson) as Record<string, unknown>, appKey, resultMeta)
            .then((result) => {
                if (cancelled) {
                    return
                }
                if (result.isError || !result.structuredContent) {
                    setError({ reason: 'tool_error', message: `Could not load data for ${toolName}.` })
                    return
                }
                setData(result.structuredContent)
            })
            .catch((e: unknown) => {
                if (!cancelled) {
                    // Analytics gets only the name and JSON-RPC code: the message can quote response content.
                    const code = (e as { code?: unknown } | null)?.code
                    setError({
                        reason: 'exception',
                        message: e instanceof Error ? e.message : String(e),
                        errorName: e instanceof Error ? e.name : typeof e,
                        errorCode: typeof code === 'number' ? code : undefined,
                    })
                }
            })
        return () => {
            cancelled = true
        }
    }, [app, toolName, toolInputJson, appKey, resultMeta])

    const render = RENDER_DISPATCH[envelope.app_key]
    const failureReason = render ? error?.reason : 'no_visualization'
    const errorName = render ? error?.errorName : undefined
    const errorCode = render ? error?.errorCode : undefined
    useEffect(() => {
        if (failureReason) {
            capture('mcp_ui_app_render_failed', {
                rendered_tool_name: toolName,
                app_key: envelope.app_key,
                reason: failureReason,
                error_name: errorName,
                error_code: errorCode,
            })
        }
    }, [failureReason, errorName, errorCode, toolName, envelope.app_key])

    if (!render) {
        return <AppErrorState message={`No visualization is available for ${envelope.tool_name}.`} />
    }
    if (error) {
        return <AppErrorState message={error.message} />
    }
    if (data === null) {
        return <AppLoadingState />
    }
    return render({ data, app, openLink })
}

const container = document.getElementById('root')
if (container) {
    createRoot(container).render(<RenderUiApp />)
}