: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
import { describe, expect, it, vi } from 'vitest'
import { buildAppStubHtml } from '@/resources/ui-apps'
import { DISPATCHABLE_APP_KEYS, UI_APPS, URI_MAP } from '@/resources/ui-apps.generated'
import {
generateDispatchModule,
resolveCustomApp,
resolveDetailApp,
resolveListApp,
} from '../../scripts/generate-ui-apps'
describe('ui-apps', () => {
describe('buildAppStubHtml', () => {
it('generates correct stub HTML for production base URL', () => {
const html = buildAppStubHtml('debug', 'https://mcp.posthog.com')
expect(html).toMatchInlineSnapshot(`
"<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://mcp.posthog.com/ui-apps/debug/styles.css">
</head><body>
<div id="root"></div>
<script src="https://mcp.posthog.com/ui-apps/debug/main.js"></script>
</body></html>"
`)
})
it('generates correct stub HTML for local development', () => {
const html = buildAppStubHtml('query-results', 'http://localhost:8787')
expect(html).toMatchInlineSnapshot(`
"<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="http://localhost:8787/ui-apps/query-results/styles.css">
</head><body>
<div id="root"></div>
<script src="http://localhost:8787/ui-apps/query-results/main.js"></script>
</body></html>"
`)
})
it('handles hyphenated app names', () => {
const html = buildAppStubHtml('error-issue-list', 'https://mcp.posthog.com')
expect(html).toContain('href="https://mcp.posthog.com/ui-apps/error-issue-list/styles.css"')
expect(html).toContain('src="https://mcp.posthog.com/ui-apps/error-issue-list/main.js"')
})
it('produces valid HTML structure', () => {
const html = buildAppStubHtml('debug', 'https://example.com')
expect(html).toMatch(/^<!DOCTYPE html>/)
expect(html).toContain('<html lang="en">')
expect(html).toContain('<meta charset="UTF-8">')
expect(html).toContain('<div id="root"></div>')
expect(html).toContain('</body></html>')
})
it('uses script tag without type=module (IIFE format)', () => {
const html = buildAppStubHtml('debug', 'https://example.com')
expect(html).toContain('<script src=')
expect(html).not.toContain('type="module"')
})
})
describe('registerUiAppResources', () => {
function createMockServer(): {
registerResource: ReturnType<typeof vi.fn>
} {
return { registerResource: vi.fn() }
}
function createMockContext(env: Record<string, string | undefined> = {}): {
env: Record<string, string | undefined>
} {
return {
env: {
MCP_APPS_BASE_URL: undefined,
POSTHOG_MCP_APPS_ANALYTICS_BASE_URL: undefined,
POSTHOG_UI_APPS_TOKEN: undefined,
POSTHOG_API_BASE_URL: undefined,
POSTHOG_ANALYTICS_API_KEY: undefined,
POSTHOG_ANALYTICS_HOST: undefined,
...env,
},
}
}
it('skips registration when MCP_APPS_BASE_URL is not set', async () => {
const { registerUiAppResources } = await import('@/resources/ui-apps')
const server = createMockServer()
const context = createMockContext()
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
await registerUiAppResources(server as any, context as any)
expect(server.registerResource).not.toHaveBeenCalled()
expect(warnSpy).toHaveBeenCalledWith(
'MCP_APPS_BASE_URL is not set — UI app resources will not be registered'
)
warnSpy.mockRestore()
})
it('registers all apps when MCP_APPS_BASE_URL is set', async () => {
const { registerUiAppResources } = await import('@/resources/ui-apps')
const server = createMockServer()
const context = createMockContext({ MCP_APPS_BASE_URL: 'https://mcp.posthog.com' })
await registerUiAppResources(server as any, context as any)
expect(server.registerResource).toHaveBeenCalledTimes(UI_APPS.length)
})
it('registers apps with correct names and URIs', async () => {
const { registerUiAppResources } = await import('@/resources/ui-apps')
const server = createMockServer()
const context = createMockContext({ MCP_APPS_BASE_URL: 'https://mcp.posthog.com' })
await registerUiAppResources(server as any, context as any)
const registeredNames = server.registerResource.mock.calls.map((call: unknown[]) => call[0])
expect(registeredNames).toContain('MCP Apps Debug')
expect(registeredNames).toContain('Query Results')
expect(registeredNames).toContain('PostHog Feature Flag')
expect(registeredNames).toContain('PostHog Feature Flag Testing')
expect(registeredNames).toContain('PostHog Experiment Results')
expect(URI_MAP['feature-flag-testing']).toBe('ui://posthog/feature-flag-testing.html')
})
it('includes base URL in CSP resourceDomains', async () => {
const { registerUiAppResources } = await import('@/resources/ui-apps')
const server = createMockServer()
const context = createMockContext({ MCP_APPS_BASE_URL: 'https://mcp.posthog.com' })
await registerUiAppResources(server as any, context as any)
// Call the resource handler for the first registered app
const handler = server.registerResource.mock.calls[0]![3]
const result = await handler(new URL('ui://posthog/debug.html'))
expect(result.contents[0]._meta.ui.csp.resourceDomains).toContain('https://mcp.posthog.com')
expect(result.contents[0]._meta['openai/widgetCSP'].resource_domains).toContain('https://mcp.posthog.com')
})
it('advertises the CSP on the registration so resources/list carries it', async () => {
const { registerUiAppResources } = await import('@/resources/ui-apps')
const server = createMockServer()
const context = createMockContext({ MCP_APPS_BASE_URL: 'https://mcp.posthog.com' })
await registerUiAppResources(server as any, context as any)
const registration = server.registerResource.mock.calls[0]![2]
expect(registration._meta.ui.csp.resourceDomains).toContain('https://mcp.posthog.com')
expect(registration._meta['openai/widgetCSP'].resource_domains).toContain('https://mcp.posthog.com')
})
it('allows Visual Review artifacts without widening other app CSPs', async () => {
const { registerUiAppResources } = await import('@/resources/ui-apps')
const server = createMockServer()
const context = createMockContext({ MCP_APPS_BASE_URL: 'https://mcp.posthog.com' })
await registerUiAppResources(server as any, context as any)
const visualReviewRegistration = server.registerResource.mock.calls.find(
(call: unknown[]) => call[1] === URI_MAP['visual-review-snapshots']
)
const debugRegistration = server.registerResource.mock.calls.find(
(call: unknown[]) => call[1] === URI_MAP.debug
)
const artifactSource =
'https://s3.us-east-1.amazonaws.com/posthog-cloud-prod-us-east-1-app-assets/visual_review/'
expect(visualReviewRegistration![2]._meta.ui.csp.resourceDomains).toContain(artifactSource)
expect(visualReviewRegistration![2]._meta['openai/widgetCSP'].resource_domains).toContain(artifactSource)
expect(debugRegistration![2]._meta.ui.csp.resourceDomains).not.toContain(artifactSource)
})
it('includes analytics URL in CSP when set', async () => {
const { registerUiAppResources } = await import('@/resources/ui-apps')
const server = createMockServer()
const context = createMockContext({
MCP_APPS_BASE_URL: 'https://mcp.posthog.com',
POSTHOG_MCP_APPS_ANALYTICS_BASE_URL: 'https://us.i.posthog.com',
})
await registerUiAppResources(server as any, context as any)
const handler = server.registerResource.mock.calls[0]![3]
const result = await handler(new URL('ui://posthog/debug.html'))
expect(result.contents[0]._meta.ui.csp.resourceDomains).toContain('https://us.i.posthog.com')
expect(result.contents[0]._meta.ui.csp.connectDomains).toContain('https://us.i.posthog.com')
expect(result.contents[0]._meta['openai/widgetCSP'].resource_domains).toContain('https://us.i.posthog.com')
expect(result.contents[0]._meta['openai/widgetCSP'].connect_domains).toContain('https://us.i.posthog.com')
})
it('omits analytics URL from CSP when not set', async () => {
const { registerUiAppResources } = await import('@/resources/ui-apps')
const server = createMockServer()
const context = createMockContext({ MCP_APPS_BASE_URL: 'https://mcp.posthog.com' })
await registerUiAppResources(server as any, context as any)
const handler = server.registerResource.mock.calls[0]![3]
const result = await handler(new URL('ui://posthog/debug.html'))
expect(result.contents[0]._meta.ui.csp.resourceDomains).toEqual(['https://mcp.posthog.com'])
expect(result.contents[0]._meta.ui.csp.connectDomains).toEqual([])
expect(result.contents[0]._meta['openai/widgetCSP'].resource_domains).toEqual(['https://mcp.posthog.com'])
expect(result.contents[0]._meta['openai/widgetCSP'].connect_domains).toEqual([])
})
it('resource handler returns stub HTML with correct base URL', async () => {
const { registerUiAppResources } = await import('@/resources/ui-apps')
const server = createMockServer()
const context = createMockContext({ MCP_APPS_BASE_URL: 'https://mcp.posthog.com' })
await registerUiAppResources(server as any, context as any)
// Find the debug app registration
const debugCall = server.registerResource.mock.calls.find((call: unknown[]) => call[0] === 'MCP Apps Debug')
const handler = debugCall![3]
const result = await handler(new URL('ui://posthog/debug.html'))
expect(result.contents[0].text).toMatchInlineSnapshot(`
"<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://mcp.posthog.com/ui-apps/debug/styles.css">
</head><body>
<div id="root"></div>
<script src="https://mcp.posthog.com/ui-apps/debug/main.js"></script>
</body></html>"
`)
})
it('resource handler returns correct MIME type', async () => {
const { registerUiAppResources } = await import('@/resources/ui-apps')
const server = createMockServer()
const context = createMockContext({ MCP_APPS_BASE_URL: 'https://mcp.posthog.com' })
await registerUiAppResources(server as any, context as any)
const handler = server.registerResource.mock.calls[0]![3]
const result = await handler(new URL('ui://posthog/debug.html'))
expect(result.contents[0].mimeType).toBe('text/html;profile=mcp-app')
})
})
describe('render-ui dispatch', () => {
it('DISPATCHABLE_APP_KEYS includes opted-in custom apps', () => {
expect(DISPATCHABLE_APP_KEYS).toContain('survey')
expect(DISPATCHABLE_APP_KEYS).toContain('survey-list')
expect(DISPATCHABLE_APP_KEYS).toContain('query-results')
for (const customKey of ['debug', 'render-ui', 'visual-review-snapshots']) {
expect(DISPATCHABLE_APP_KEYS).not.toContain(customKey)
}
})
it('generates dispatch entries for reusable views and a Content component for list apps', () => {
const queryResultsConfig = resolveCustomApp({
type: 'custom',
app_name: 'Query Results',
description: 'Interactive query results',
render_ui: {
component_import: '../components/Component',
view_component: 'Component',
view_prop: 'data',
},
})
if (!queryResultsConfig.render_ui) {
throw new Error('Expected query results to configure render-ui dispatch')
}
const storyConfig = resolveCustomApp({
type: 'custom',
app_name: 'Chart Explanation',
description: 'An explanation of a chart',
render_ui: {
component_import: '../components/ExplainChart',
view_component: 'ExplainChart',
view_prop: 'data',
data_type: 'ExplainChartData',
link_prop: 'openLink',
app_prop: 'app',
},
})
if (!storyConfig.render_ui) {
throw new Error('Expected the explanation to configure render-ui dispatch')
}
const code = generateDispatchModule([
{
appKey: 'survey',
type: 'detail',
config: resolveDetailApp(
'survey',
{ type: 'detail', view_prop: 'survey' },
'products/surveys/mcp/apps'
),
},
{
appKey: 'query-results',
type: 'custom',
config: { ...queryResultsConfig, render_ui: queryResultsConfig.render_ui },
},
{
appKey: 'explain-chart',
type: 'custom',
config: { ...storyConfig, render_ui: storyConfig.render_ui },
},
{
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("import { Component } from '../components/Component'")
expect(code).toContain("'query-results': ({ data }) => <Component data={data} />")
expect(code).toContain(
"'explain-chart': ({ data, openLink, app }) => <ExplainChart data={data as ExplainChartData} openLink={openLink} app={app} />"
)
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'")
})
})
})