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.

7.7 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path } from 'kea'
import posthog from 'posthog-js'

import { preflightLogic } from 'lib/logic/preflightLogic'
import { sceneRenderedLogic } from 'lib/logic/sceneRenderedLogic'
import { retryImport } from 'lib/utils/retryImport'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'

import type { PreflightStatus, UserType } from '~/types'

import { webmcpExecCreate } from '../generated/api'
import type { WebMCPExecResultApi } from '../generated/api.schemas'
import { WebMCPToolError } from '../webmcpToolError'

interface WebMCPToolAnnotations {
    readOnlyHint?: boolean
    untrustedContentHint?: boolean
    consequentialHint?: boolean
}

interface WebMCPTool {
    name: string
    title?: string
    description: string
    inputSchema?: Record<string, unknown>
    annotations?: WebMCPToolAnnotations
    execute: (input: Record<string, unknown>, options?: { signal?: AbortSignal }) => Promise<string>
}

interface ModelContext {
    // Aborting the signal unregisters the tool.
    registerTool: (tool: WebMCPTool, options?: { signal?: AbortSignal }) => Promise<void>
}

export function getModelContext(): ModelContext | null {
    // Chrome 150 deprecates navigator.modelContext in favor of document.modelContext, so read both.
    const fromDocument = (document as Document & { modelContext?: ModelContext }).modelContext
    const fromNavigator = (navigator as Navigator & { modelContext?: ModelContext }).modelContext
    return fromDocument ?? fromNavigator ?? null
}

export function fillPlaceholders<T>(value: T, replacements: Record<string, string>): T {
    let json = JSON.stringify(value)
    for (const [placeholder, replacement] of Object.entries(replacements)) {
        json = json.replaceAll(placeholder, JSON.stringify(replacement).slice(1, -1))
    }
    return JSON.parse(json) as T
}

export function formatExecResult(result: WebMCPExecResultApi): string {
    return result.content
        .map((block) => (block.type === 'text' && typeof block.text === 'string' ? block.text : JSON.stringify(block)))
        .join('\n\n')
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface webmcpLogicValues {
    preflight: PreflightStatus | null // preflightLogic
    sceneHasRendered: boolean // sceneRenderedLogic
    currentTeamId: number | null // teamLogic
    user: UserType | null // userLogic
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface webmcpLogicActions {
    loadPreflightSuccess: (
        preflight: PreflightStatus,
        payload?: any
    ) => {
        payload?: any
        preflight: PreflightStatus
    } // preflightLogic
    sceneRendered: () => {
        value: true
    } // sceneRenderedLogic
    loadCurrentTeamSuccess: (
        currentTeam: null | import('~/types').TeamPublicType,
        payload?: any
    ) => {
        currentTeam: null | import('~/types').TeamPublicType
        payload?: any
    } // teamLogic
    registerTool: () => {
        value: true
    }
}

export type webmcpLogicType = MakeLogicType<webmcpLogicValues, webmcpLogicActions>

export const webmcpLogic = kea<webmcpLogicType>([
    path(['products', 'webmcp', 'frontend', 'logics', 'webmcpLogic']),
    connect(() => ({
        values: [
            preflightLogic,
            ['preflight'],
            teamLogic,
            ['currentTeamId'],
            userLogic,
            ['user'],
            sceneRenderedLogic,
            ['sceneHasRendered'],
        ],
        actions: [
            preflightLogic,
            ['loadPreflightSuccess'],
            teamLogic,
            ['loadCurrentTeamSuccess'],
            sceneRenderedLogic,
            ['sceneRendered'],
        ],
    })),
    actions({
        registerTool: true,
    }),
    listeners(({ actions, cache, values }) => ({
        // The preflight and the team can arrive after mount, and the tool needs both.
        // No part of the first paint uses the tool, so its chunk also waits for the scene's own requests.
        sceneRendered: () => {
            actions.registerTool()
        },
        loadPreflightSuccess: () => {
            actions.registerTool()
        },
        loadCurrentTeamSuccess: () => {
            actions.registerTool()
        },
        registerTool: () => {
            const modelContext = getModelContext()
            // Without an MCP server every proxy call fails, and the backend refuses impersonated sessions.
            if (
                !modelContext ||
                !values.sceneHasRendered ||
                !values.preflight?.webmcp_available ||
                values.user?.is_impersonated ||
                !values.currentTeamId ||
                cache.toolRegistered
            ) {
                return
            }
            cache.toolRegistered = true
            const teamId = values.currentTeamId

            const register = async (signal: AbortSignal): Promise<void> => {
                // A separate chunk keeps the long description out of the main bundle.
                const generated = await retryImport(() => import('../execTool.generated'))
                const tool = fillPlaceholders(generated.WEBMCP_EXEC_TOOL, {
                    [generated.APP_ORIGIN_PLACEHOLDER]: window.location.origin,
                    [generated.PROJECT_ID_PLACEHOLDER]: String(teamId),
                })
                if (signal.aborted) {
                    return
                }
                await modelContext.registerTool(
                    {
                        name: tool.name,
                        title: 'PostHog',
                        description: tool.description,
                        inputSchema: tool.inputSchema,
                        annotations: {
                            // Event and person properties come from end users, so results can carry prompt injection.
                            untrustedContentHint: true,
                            // One tool runs every PostHog command, including the ones that write.
                            consequentialHint: true,
                        },
                        execute: async (input, options) => {
                            const result = await webmcpExecCreate(
                                String(values.currentTeamId ?? teamId),
                                { command: String(input.command ?? '') },
                                { signal: options?.signal }
                            )
                            const text = formatExecResult(result)
                            if (result.is_error) {
                                throw new WebMCPToolError(text)
                            }
                            return text
                        },
                    },
                    { signal }
                )
                posthog.capture('webmcp tool registered')
            }

            cache.disposables.add(
                () => {
                    const controller = new AbortController()
                    // A failed registration only means no tool, so it must not surface as an app error.
                    // Clearing the flag lets the next team load try again.
                    register(controller.signal).catch(() => {
                        if (!controller.signal.aborted) {
                            cache.toolRegistered = false
                        }
                    })
                    return () => controller.abort()
                },
                'webmcpTool',
                // Browser agents can drive a tab in the background, so the tool stays registered while hidden.
                { pauseOnPageHidden: false }
            )
        },
    })),
    afterMount(({ actions }) => {
        actions.registerTool()
    }),
])