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.

5.0 KB
Raw Blame
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
import { setupServer } from 'msw/node'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'

import { createApp } from '@/hono/app'
import type { RedisLike } from '@/hono/cache/RedisCache'

import {
    defineAuthTests,
    defineCatalogFilterTests,
    defineExecModeTests,
    defineHttpRouteTests,
    defineJsonRpcEdgeCaseTests,
    defineMcpProtocolTests,
    defineResilienceTests,
    defineResourceCatalogTests,
    defineSessionLifecycleTests,
    defineSessionTrackingTests,
    defineStatelessProtocolTests,
    type ProtocolTestHarness,
} from '../integration/mcp-protocol-suite'
import { handlers, contextMillHandler } from '../workers/fixtures/handlers'
import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'

const mswServer = setupServer(...handlers, contextMillHandler)

function createInMemoryRedis(): RedisLike & {
    ping(): Promise<string>
    incrby(key: string, increment: number): Promise<number>
} {
    const store = new Map<string, string>()
    return {
        get: async (key) => store.get(key) ?? null,
        set: async (key, value) => {
            store.set(key, String(value))
            return 'OK'
        },
        del: async (...keys) => {
            let removed = 0
            for (const key of keys) {
                if (store.delete(key)) {
                    removed++
                }
            }
            return removed
        },
        scan: async (cursor) => {
            const cur = String(cursor)
            return [cur === '0' ? 'next' : '0', cur === '0' ? Array.from(store.keys()) : []] as [string, string[]]
        },
        ...makeRedisRateLimitStubs(store),
        ping: async () => 'PONG',
    }
}

let app: ReturnType<typeof createApp>['app']

beforeAll(async () => {
    process.env.TEST = '1'
    process.env.MCP_APPS_BASE_URL = 'https://apps.test'
    mswServer.listen({ onUnhandledRequest: 'bypass' })
    const created = createApp(createInMemoryRedis())
    app = created.app
    await created.warmup()
})

afterAll(() => {
    mswServer.close()
})

const fetchViaApp: typeof fetch = async (input, init) => {
    const url = input instanceof URL ? input : new URL(typeof input === 'string' ? input : input.url)
    return app.request(url.pathname + url.search, init ?? {})
}

const harness = (): ProtocolTestHarness => ({
    baseUrl: new URL('http://hono.test'),
    fetch: fetchViaApp,
    token: 'phx_integration_test_token',
    stateless: true,
    gracefulUnknown: true,
    publicRoutes: true,
})

defineMcpProtocolTests('Hono', harness)
defineResilienceTests('Hono', harness)
defineHttpRouteTests('Hono', harness)
defineAuthTests('Hono', harness)
defineJsonRpcEdgeCaseTests('Hono', harness)
defineSessionLifecycleTests('Hono', harness)
defineResourceCatalogTests('Hono', harness)
defineCatalogFilterTests('Hono', harness)
defineExecModeTests('Hono', harness)
defineSessionTrackingTests('Hono', harness)
defineStatelessProtocolTests('Hono', harness)

describe.each(['2025-11-25', '2026-07-28'] as const)('MCP UI capability negotiation on %s', (version) => {
    it.each([
        { name: 'example-client', mimeTypes: ['text/html;profile=mcp-app'], supported: true },
        { name: 'openai-mcp', mimeTypes: undefined, supported: true },
        { name: 'example-client', mimeTypes: undefined, supported: false },
        { name: 'ChatGPT', mimeTypes: ['text/html'], supported: false },
    ])('gates tool discovery and cached calls for %j', async ({ name, mimeTypes, supported }) => {
        const client = new Client(
            { name, version: '1.0' },
            {
                capabilities: { extensions: mimeTypes ? { 'io.modelcontextprotocol/ui': { mimeTypes } } : {} },
                versionNegotiation: { mode: version === '2026-07-28' ? { pin: version } : 'legacy' },
            }
        )
        const transport = new StreamableHTTPClientTransport(new URL('https://hono.test/mcp'), {
            fetch: async (input, init) =>
                app.fetch(
                    new Request(input, {
                        ...init,
                        headers: {
                            ...Object.fromEntries(new Headers(init?.headers)),
                            Authorization: 'Bearer phx_integration_test_token',
                        },
                    })
                ),
        })
        try {
            await client.connect(transport)
            const { tools } = await client.listTools()
            expect(tools.some((tool) => tool.name === 'render-ui')).toBe(supported)

            const result = await client.callTool({
                name: 'render-ui',
                arguments: { tool_name: 'survey-get', tool_input: { surveyId: 'synthetic-survey' } },
            })
            expect(result.isError === true).toBe(!supported)
            if (supported) {
                expect(result._meta).toMatchObject({ ui: { resourceUri: 'ui://posthog/render-ui.html' } })
            }
        } finally {
            await client.close()
        }
    })
})