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.

chore(mcp): broaden integration test coverage (#59770)

Joshua Snydere974788fab9e
diff --git a/services/mcp/tests/hono/mcp-protocol.test.ts b/services/mcp/tests/hono/mcp-protocol.test.ts
index 424ed8207747..0a6800252e97 100644
--- a/services/mcp/tests/hono/mcp-protocol.test.ts
+++ b/services/mcp/tests/hono/mcp-protocol.test.ts
@@ -4,7 +4,17 @@ import { afterAll, beforeAll } from 'vitest'
import { createApp } from '@/hono/app'
import type { RedisLike } from '@/hono/cache/RedisCache'
-import { defineMcpProtocolTests, defineResilienceTests, type ProtocolTestHarness } from '../integration/mcp-protocol-suite'
+import {
+ defineAuthTests,
+ defineCatalogFilterTests,
+ defineHttpRouteTests,
+ defineJsonRpcEdgeCaseTests,
+ defineMcpProtocolTests,
+ defineResilienceTests,
+ defineResourceCatalogTests,
+ defineSessionLifecycleTests,
+ type ProtocolTestHarness,
+} from '../integration/mcp-protocol-suite'
import { handlers, contextMillHandler } from '../workers/fixtures/handlers'
const mswServer = setupServer(...handlers, contextMillHandler)
@@ -59,7 +69,15 @@ const harness = (): ProtocolTestHarness => ({
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)
diff --git a/services/mcp/tests/integration/mcp-protocol-suite.ts b/services/mcp/tests/integration/mcp-protocol-suite.ts
index 4c913f8f6561..d0c9cbc9f4aa 100644
--- a/services/mcp/tests/integration/mcp-protocol-suite.ts
+++ b/services/mcp/tests/integration/mcp-protocol-suite.ts
@@ -25,6 +25,15 @@ export type ProtocolTestHarness = {
/** Whether the runtime returns empty results for unknown resources/prompts
* instead of throwing errors. The Hono dispatcher does this; the CF SDK doesn't. */
gracefulUnknown?: boolean | undefined
+ /** Optional org/project ids — only set when the harness runs against the real
+ * PostHog API. Tests that hit the upstream API (projects-get, switch-project,
+ * organization-get response shape) skip when these are missing. */
+ orgId?: string | undefined
+ projectId?: string | undefined
+ /** Whether public HTTP routes (/health, /readyz, /.well-known/...) are wired
+ * up on this runtime. The Hono entrypoint exposes them; the in-process mock
+ * harness may bypass them. Defaults to true. */
+ publicRoutes?: boolean | undefined
}
function buildStreamableClient(
@@ -396,3 +405,1051 @@ export function defineResilienceTests(
})
})
}
+
+// Raw JSON-RPC dispatcher behavior that bypasses the SDK client. The SDK
+// normalizes / hides a lot of the wire format, so we drop down to fetch() to
+// assert on the contract MCP clients in the wild actually depend on:
+// - parse errors return JSON-RPC `error` payloads (code -32700) at HTTP 200
+// - notifications (no `id`) return 202 No Content
+// - `ping` returns an empty result
+// - batch requests return an array, single request returns an object
+// - body / batch size limits are enforced before reaching tool dispatch
+// - unknown methods return `MethodNotFound` (-32601) rather than 500
+//
+// Each test sends a complete JSON-RPC envelope so a regression in the
+// dispatcher (e.g. dropping the `id` echo, changing the error code, returning
+// 500 instead of 200) shows up here rather than as a vague client-side timeout.
+export function defineJsonRpcEdgeCaseTests(
+ label: string,
+ getHarness: () => Promise<ProtocolTestHarness> | ProtocolTestHarness
+): void {
+ describe(`MCP JSON-RPC edge cases (${label})`, () => {
+ async function postMcp(
+ harness: ProtocolTestHarness,
+ body: string | Uint8Array,
+ extraHeaders: Record<string, string> = {}
+ ): Promise<Response> {
+ return harness.fetch(new URL('/mcp', harness.baseUrl), {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${harness.token}`,
+ 'Content-Type': 'application/json',
+ Accept: 'application/json, text/event-stream',
+ ...extraHeaders,
+ },
+ // Cast to BodyInit because Node's `fetch` accepts both string and Uint8Array.
+ body: body as unknown as BodyInit,
+ })
+ }
+
+ it('returns a JSON-RPC parse error for a malformed body', async () => {
+ const harness = await getHarness()
+ const res = await postMcp(harness, '{not-json')
+ expect(res.status).toBe(200)
+ const json = (await res.json()) as {
+ jsonrpc?: string
+ error?: { code?: number; message?: string }
+ }
+ expect(json.jsonrpc).toBe('2.0')
+ expect(json.error?.code).toBe(-32700)
+ })
+
+ it('returns a JSON-RPC parse error for an empty body', async () => {
+ const harness = await getHarness()
+ const res = await postMcp(harness, '')
+ expect(res.status).toBe(200)
+ const json = (await res.json()) as { error?: { code?: number } }
+ expect(json.error?.code).toBe(-32700)
+ })
+
+ // A notification has no `id`. Per the JSON-RPC spec the server must not
+ // respond with a result envelope — the dispatcher returns 202 No Content
+ // (matches MCP streamable-http behavior). A regression that started
+ // sending a JSON body back would make some clients (notably the SDK
+ // transport) raise on the unexpected response.
+ it('returns 202 with no body for a JSON-RPC notification', async () => {
+ const harness = await getHarness()
+ const res = await postMcp(
+ harness,
+ JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized', params: {} })
+ )
+ expect(res.status).toBe(202)
+ const text = await res.text()
+ expect(text).toBe('')
+ })
+
+ it('responds to ping with an empty result', async () => {
+ const harness = await getHarness()
+ const res = await postMcp(harness, JSON.stringify({ jsonrpc: '2.0', id: 'ping-1', method: 'ping' }))
+ expect(res.status).toBe(200)
+ const json = (await res.json()) as { id?: string; result?: Record<string, unknown> }
+ expect(json.id).toBe('ping-1')
+ expect(json.result).toBeTruthy()
+ expect(json.result).toEqual({})
+ })
+
+ it('returns MethodNotFound for an unknown method', async () => {
+ const harness = await getHarness()
+ const res = await postMcp(harness, JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'no/such/method' }))
+ expect(res.status).toBe(200)
+ const json = (await res.json()) as { error?: { code?: number; message?: string } }
+ expect(json.error?.code).toBe(-32601)
+ })
+
+ // Batch requests are a JSON-RPC feature MCP clients use to bundle
+ // initialize + tools/list (saves a round-trip on cold start). The
+ // dispatcher must return an array when given an array, regardless of
+ // batch size — including the degenerate single-element array.
+ it('returns an array response for a batch with one request', async () => {
+ const harness = await getHarness()
+ const res = await postMcp(harness, JSON.stringify([{ jsonrpc: '2.0', id: 'batch-1', method: 'ping' }]))
+ expect(res.status).toBe(200)
+ const json = (await res.json()) as unknown
+ expect(Array.isArray(json)).toBe(true)
+ expect((json as unknown[]).length).toBe(1)
+ })
+
+ it('returns each request id in a multi-request batch', async () => {
+ const harness = await getHarness()
+ const res = await postMcp(
+ harness,
+ JSON.stringify([
+ { jsonrpc: '2.0', id: 'a', method: 'ping' },
+ { jsonrpc: '2.0', id: 'b', method: 'ping' },
+ { jsonrpc: '2.0', id: 'c', method: 'ping' },
+ ])
+ )
+ expect(res.status).toBe(200)
+ const json = (await res.json()) as Array<{ id: string }>
+ expect(json.length).toBe(3)
+ expect(json.map((r) => r.id).sort()).toEqual(['a', 'b', 'c'])
+ })
+
+ it('returns 202 for a batch composed entirely of notifications', async () => {
+ const harness = await getHarness()
+ const res = await postMcp(
+ harness,
+ JSON.stringify([
+ { jsonrpc: '2.0', method: 'notifications/initialized' },
+ { jsonrpc: '2.0', method: 'notifications/initialized' },
+ ])
+ )
+ expect(res.status).toBe(202)
+ })
+
+ // The dispatcher caps batches at MAX_BATCH_SIZE (100). Anything bigger
+ // returns InvalidRequest — the cap exists so a buggy client can't
+ // amplify a single connection into 10k Promise dispatches.
+ it('rejects an oversized batch with InvalidRequest', async () => {
+ const harness = await getHarness()
+ const messages = Array.from({ length: 101 }, (_, i) => ({
+ jsonrpc: '2.0',
+ id: i,
+ method: 'ping',
+ }))
+ const res = await postMcp(harness, JSON.stringify(messages))
+ expect(res.status).toBe(200)
+ const json = (await res.json()) as { error?: { code?: number } }
+ expect(json.error?.code).toBe(-32600)
+ })
+
+ // The body limit (MAX_BODY_BYTES = 1 MiB) is enforced based on
+ // Content-Length. We send an actual oversized body so undici accepts
+ // the request, and pass Content-Length explicitly so transports that
+ // don't auto-set it (Hono's in-process `app.request`) still hit the
+ // dispatcher's size guard.
+ it('rejects a body larger than the size cap', async () => {
+ const harness = await getHarness()
+ const padding = 'a'.repeat(1_572_864) // 1.5 MiB
+ const oversizedBody = JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'ping',
+ params: { padding },
+ })
+ const res = await postMcp(harness, oversizedBody, {
+ 'Content-Length': String(oversizedBody.length),
+ })
+ expect(res.status).toBe(200)
+ const json = (await res.json()) as { error?: { code?: number } }
+ expect(json.error?.code).toBe(-32600)
+ })
+ })
+}
+
+// Public HTTP routes (everything that isn't /mcp). These are how kube probes,
+// load balancers, OAuth clients, and OpenAI's MCP marketplace verifier discover
+// and validate the server. They have to work even if /mcp is broken, so they
+// get their own test group.
+//
+// Cases:
+// - /, /health, /healthz, /readyz, /metrics — kubelet + monitoring
+// - /.well-known/openai-apps-challenge — OpenAI marketplace identity proof
+// - /.well-known/oauth-protected-resource{,/mcp} — RFC 9728 metadata that
+// clients use to discover the authorization server
+// - /sse → /mcp 308 (also covered in resilience tests, asserted here against
+// the real listener so we know the redirect is wired in the routing chain)
+// - GET / PUT / DELETE on /mcp → 405 (only POST is supported)
+// - 404 for unknown paths
+// - Security headers on every response
+//
+// This suite assumes the harness has `publicRoutes: true` (the Hono runtime
+// does — the CF runtime serves public routes via the Workers Static Assets
+// binding which has different semantics, so it gets its own suite).
+export function defineHttpRouteTests(
+ label: string,
+ getHarness: () => Promise<ProtocolTestHarness> | ProtocolTestHarness
+): void {
+ describe(`MCP HTTP routes (${label})`, () => {
+ it('redirects GET / to the docs', async () => {
+ const harness = await getHarness()
+ const res = await harness.fetch(new URL('/', harness.baseUrl), { redirect: 'manual' })
+ expect([301, 302, 307, 308]).toContain(res.status)
+ expect(res.headers.get('location')).toContain('posthog.com')
+ })
+
+ it.each(['/health', '/healthz'])('returns 200 ok on %s', async (path) => {
+ const harness = await getHarness()
+ const res = await harness.fetch(new URL(path, harness.baseUrl))
+ expect(res.status).toBe(200)
+ const json = (await res.json()) as { status?: string }
+ expect(json.status).toBe('ok')
+ })
+
+ // /readyz piggy-backs on Redis health. With Redis up we expect 200;
+ // with Redis down we expect a 5xx. The harness boots a healthy
+ // Redis, so we assert success here — a regression that started
+ // ignoring the Redis ping would surface as the wrong status code.
+ it('returns 200 on /readyz when the stack is healthy', async () => {
+ const harness = await getHarness()
+ const res = await harness.fetch(new URL('/readyz', harness.baseUrl))
+ expect(res.status).toBe(200)
+ const json = (await res.json()) as { status?: string; redis?: string }
+ expect(json.status).toBe('ok')
+ expect(json.redis).toBe('healthy')
+ })
+
+ it('serves Prometheus metrics on /metrics', async () => {
+ const harness = await getHarness()
+ const res = await harness.fetch(new URL('/metrics', harness.baseUrl))
+ expect(res.status).toBe(200)
+ const ctype = res.headers.get('content-type') || ''
+ expect(ctype).toContain('text/plain')
+ const body = await res.text()
+ // Prom client always emits a process_* family — assert on it so we
+ // know the registry was actually rendered.
+ expect(body).toMatch(/# HELP\s/)
+ expect(body).toMatch(/# TYPE\s/)
+ })
+
+ it('returns the openai apps challenge token', async () => {
+ const harness = await getHarness()
+ const res = await harness.fetch(new URL('/.well-known/openai-apps-challenge', harness.baseUrl))
+ expect(res.status).toBe(200)
+ const body = await res.text()
+ // The challenge token is a fixed value — if a refactor accidentally
+ // changes it, OpenAI's marketplace listing will silently break.
+ expect(body).toBe('pRLV9JYbPOF5Dy039v3Rn3-qrMuKqZ2_4SsX9GoL9aU')
+ })
+
+ it('returns RFC 9728 OAuth protected resource metadata', async () => {
+ const harness = await getHarness()
+ const res = await harness.fetch(new URL('/.well-known/oauth-protected-resource/mcp', harness.baseUrl))
+ expect(res.status).toBe(200)
+ const json = (await res.json()) as {
+ resource?: string
+ authorization_servers?: string[]
+ scopes_supported?: string[]
+ bearer_methods_supported?: string[]
+ }
+ expect(json.resource).toMatch(/\/mcp$/)
+ expect(Array.isArray(json.authorization_servers)).toBe(true)
+ expect((json.authorization_servers ?? []).length).toBeGreaterThan(0)
+ expect(json.bearer_methods_supported).toEqual(['header'])
+ expect(Array.isArray(json.scopes_supported)).toBe(true)
+ expect((json.scopes_supported ?? []).length).toBeGreaterThan(0)
+ // The metadata is meant to be cached aggressively — verify the
+ // Cache-Control header is set so reverse proxies treat it right.
+ expect(res.headers.get('cache-control') || '').toMatch(/max-age=\d+/)
+ })
+
+ it('redirects /.well-known/oauth-authorization-server to the authorization server', async () => {
+ const harness = await getHarness()
+ const res = await harness.fetch(new URL('/.well-known/oauth-authorization-server', harness.baseUrl), {
+ redirect: 'manual',
+ })
+ expect([301, 302]).toContain(res.status)
+ // The destination origin varies by environment (prod uses
+ // `oauth.posthog.com`, CI runs a local auth server at
+ // `localhost:8000`). Just check the redirect is to a different
+ // origin than the MCP server itself — that's the contract.
+ const location = res.headers.get('location') || ''
+ expect(location).toBeTruthy()
+ const target = new URL(location)
+ expect(target.origin).not.toBe(harness.baseUrl.origin)
+ })
+
+ // /register and /token are MCP-spec fallback endpoints. They have to
+ // 307 (not 302) so the client preserves the POST + body across the hop
+ // — anything else loses the registration / token-exchange payload.
+ it.each(['/register', '/token'])('redirects POST %s with 307 to preserve the request body', async (path) => {
+ const harness = await getHarness()
+ const res = await harness.fetch(new URL(path, harness.baseUrl), {
+ method: 'POST',
+ redirect: 'manual',
+ })
+ expect(res.status).toBe(307)
+ expect(res.headers.get('location') || '').toContain('/oauth/')
+ })
+
+ it.each(['GET', 'PUT', 'DELETE', 'PATCH'])(
+ 'rejects %s on /mcp with 405 (POST-only endpoint)',
+ async (method) => {
+ const harness = await getHarness()
+ const res = await harness.fetch(new URL('/mcp', harness.baseUrl), {
+ method,
+ headers: { Authorization: `Bearer ${harness.token}` },
+ })
+ expect(res.status).toBe(405)
+ }
+ )
+
+ it('returns 404 for unknown paths', async () => {
+ const harness = await getHarness()
+ const res = await harness.fetch(new URL('/this-path-does-not-exist', harness.baseUrl))
+ expect(res.status).toBe(404)
+ })
+
+ // Defense-in-depth security headers must be on every response, not just
+ // /mcp. Reverse proxies can override these, but the server should set
+ // sensible defaults so a misconfigured proxy doesn't expose us.
+ it('sets X-Content-Type-Options and X-Frame-Options on responses', async () => {
+ const harness = await getHarness()
+ const res = await harness.fetch(new URL('/healthz', harness.baseUrl))
+ expect(res.headers.get('X-Content-Type-Options')).toBe('nosniff')
+ expect(res.headers.get('X-Frame-Options')).toBe('DENY')
+ })
+ })
+}
+
+// Authentication enforcement at the /mcp boundary. The streamable handler is
+// the only path that accepts unauthenticated public traffic, so all rejection
+// paths run through one chokepoint. These tests use raw fetch so we can poke
+// at the WWW-Authenticate header (which the SDK strips off).
+export function defineAuthTests(
+ label: string,
+ getHarness: () => Promise<ProtocolTestHarness> | ProtocolTestHarness
+): void {
+ describe(`MCP auth (${label})`, () => {
+ async function postUnauthed(
+ harness: ProtocolTestHarness,
+ headers: Record<string, string> = {}
+ ): Promise<Response> {
+ return harness.fetch(new URL('/mcp', harness.baseUrl), {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Accept: 'application/json, text/event-stream',
+ ...headers,
+ },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' }),
+ })
+ }
+
+ it('returns 401 with WWW-Authenticate when the Authorization header is missing', async () => {
+ const harness = await getHarness()
+ const res = await postUnauthed(harness)
+ expect(res.status).toBe(401)
+ const wwwAuth = res.headers.get('WWW-Authenticate') || ''
+ expect(wwwAuth.toLowerCase()).toContain('bearer')
+ // The challenge points clients at the protected-resource metadata
+ // — that's how RFC 9728 discovery bootstraps from a 401.
+ expect(wwwAuth).toContain('oauth-protected-resource')
+ })
+
+ it('returns 401 for a bearer with no token value', async () => {
+ const harness = await getHarness()
+ const res = await postUnauthed(harness, { Authorization: 'Bearer' })
+ expect(res.status).toBe(401)
+ })
+
+ it('returns 401 for a token that does not look like a PostHog API key', async () => {
+ const harness = await getHarness()
+ const res = await postUnauthed(harness, { Authorization: 'Bearer not_a_phx_or_pha_token' })
+ expect(res.status).toBe(401)
+ const body = await res.text()
+ // The format-check rejection has a distinctive body so a regression
+ // that started letting bad-prefix tokens through to PostHog would
+ // surface here as a different status / body.
+ expect(body.toLowerCase()).toContain('invalid token')
+ })
+
+ it('returns 401 for a non-Bearer auth scheme', async () => {
+ const harness = await getHarness()
+ const res = await postUnauthed(harness, { Authorization: 'Basic dXNlcjpwYXNz' })
+ expect(res.status).toBe(401)
+ })
+
+ // (The valid-token success path is implicitly covered by every test in
+ // `defineMcpProtocolTests` — every SDK client.connect() call exercises
+ // it. We deliberately don't repeat it here with raw fetch because the
+ // CF Workers runtime returns SSE bodies instead of plain JSON, so a
+ // single raw-fetch assertion wouldn't work across both runtimes.)
+ })
+}
+
+// Tool behavior against the real PostHog API. These tests assert on the actual
+// response shape rather than just "the call didn't error" — that way a
+// regression in the API client (wrong path, dropped query param) shows up here
+// instead of as a vague "the agent gave a weird answer" bug report.
+//
+// All tests in this group skip if the harness wasn't given orgId / projectId.
+export function defineToolBehaviorTests(
+ label: string,
+ getHarness: () => Promise<ProtocolTestHarness> | ProtocolTestHarness
+): void {
+ describe(`MCP tool behavior (${label})`, () => {
+ let client: Client
+ let harness: ProtocolTestHarness
+
+ beforeEach(async () => {
+ harness = await getHarness()
+ const built = buildStreamableClient(harness)
+ client = built.client
+ await client.connect(built.transport as ConnectableTransport)
+ })
+
+ afterEach(async () => {
+ await safeClose(client)
+ })
+
+ function decodeText(content: unknown): string {
+ if (!Array.isArray(content) || content.length === 0) {
+ return ''
+ }
+ return content
+ .map((block) => {
+ if (block && typeof block === 'object' && 'text' in block) {
+ return String((block as { text: unknown }).text ?? '')
+ }
+ return ''
+ })
+ .join('\n')
+ }
+
+ it('projects-get returns the test project among the results', async ({ skip }) => {
+ if (!harness.projectId) {
+ skip('Set TEST_PROJECT_ID to run the projects-get behavior test.')
+ return
+ }
+ const result = await client.callTool({ name: 'projects-get', arguments: {} })
+ if (result.isError) {
+ throw new Error(`projects-get errored: ${decodeText(result.content)}`)
+ }
+ const text = decodeText(result.content)
+ // The tool serializes the project list as text; assert the test
+ // project's id is referenced so we know the upstream call really
+ // talked to the configured org.
+ expect(text).toContain(harness.projectId)
+ })
+
+ it('switch-project succeeds for the configured project id', async ({ skip }) => {
+ if (!harness.projectId) {
+ skip('Set TEST_PROJECT_ID to run the switch-project behavior test.')
+ return
+ }
+ const result = await client.callTool({
+ name: 'switch-project',
+ arguments: { projectId: Number(harness.projectId) },
+ })
+ expect(result.isError).toBeFalsy()
+ const text = decodeText(result.content)
+ expect(text.toLowerCase()).toContain('switched')
+ expect(text).toContain(String(harness.projectId))
+ })
+
+ // After context switch the tool catalog should remain stable — a
+ // regression that re-ran the dispatcher's warmup on every call would
+ // surface as a missing tool here.
+ it('tools/list returns the same set before and after a switch-project call', async ({ skip }) => {
+ if (!harness.projectId) {
+ skip('Set TEST_PROJECT_ID to run the catalog-stability test.')
+ return
+ }
+ const before = await client.listTools()
+ await client.callTool({
+ name: 'switch-project',
+ arguments: { projectId: Number(harness.projectId) },
+ })
+ const after = await client.listTools()
+ const beforeNames = new Set(before.tools.map((t) => t.name))
+ const afterNames = new Set(after.tools.map((t) => t.name))
+ expect(afterNames).toEqual(beforeNames)
+ })
+
+ // Tool-input validation lives in the executor (zod safeParse). A
+ // validation failure has to come back as an in-band `isError: true`
+ // result, NOT a JSON-RPC error — otherwise SDK clients would tear down
+ // the session.
+ it('returns an isError payload for invalid tool arguments', async () => {
+ const result = await client.callTool({
+ name: 'switch-project',
+ arguments: { projectId: 'not-a-number' as unknown as number },
+ })
+ expect(result.isError).toBe(true)
+ const text = decodeText(result.content)
+ expect(text.toLowerCase()).toContain('invalid')
+ })
+
+ it('switch-project does a soft switch: a non-existent project id still resolves', async () => {
+ // switch-project writes the requested id to the cache before
+ // calling PostHog to fetch project metadata. When the project
+ // doesn't exist the metadata fetch fails, but the cache write
+ // has already landed — so the tool returns success and the
+ // content references the requested id. This is the documented
+ // soft-switch contract: agents pinning to an id they don't
+ // strictly own won't get a hard error.
+ const result = await client.callTool({
+ name: 'switch-project',
+ arguments: { projectId: 999_999_999 },
+ })
+ expect(result.isError).toBeFalsy()
+ const text = decodeText(result.content)
+ expect(text).toContain('999999999')
+ })
+
+ // organization-get is the canonical "is the upstream reachable" probe.
+ // We hit it through the MCP layer and assert the org id we read back
+ // matches the configured one — that exercises the full chain: SDK
+ // client → streamable transport → dispatcher → tool executor → API
+ // client → PostHog.
+ it('organization-get returns the configured org id', async ({ skip }) => {
+ if (!harness.orgId) {
+ skip('Set TEST_ORG_ID to run the organization-get behavior test.')
+ return
+ }
+ const result = await client.callTool({ name: 'organization-get', arguments: {} })
+ if (result.isError) {
+ throw new Error(`organization-get errored: ${decodeText(result.content)}`)
+ }
+ const text = decodeText(result.content)
+ expect(text).toContain(harness.orgId)
+ })
+
+ // Multi-step flow: switch-project sets the active project in the
+ // per-user cache, and a subsequent project-scoped tool reads from
+ // that cache. If the cache write doesn't land before the next
+ // request resolves state (e.g. a Redis write that didn't await),
+ // the second call would either error out with "missing project
+ // context" or read from a stale project.
+ //
+ // We assert the second call succeeds without error — that's enough
+ // to know the active-project context flowed across the two
+ // requests on the same MCP session.
+ it('switch-project then a project-scoped tool call resolves the active project', async ({ skip }) => {
+ if (!harness.projectId) {
+ skip('Set TEST_PROJECT_ID to run the multi-step context test.')
+ return
+ }
+ const switchResult = await client.callTool({
+ name: 'switch-project',
+ arguments: { projectId: Number(harness.projectId) },
+ })
+ expect(switchResult.isError).toBeFalsy()
+ // feature-flag-get-all needs an active project context. It
+ // doesn't take a projectId argument — it reads from the cache
+ // populated by switch-project.
+ const listResult = await client.callTool({
+ name: 'feature-flag-get-all',
+ arguments: {},
+ })
+ if (listResult.isError) {
+ throw new Error(`feature-flag-get-all errored after switch-project: ${decodeText(listResult.content)}`)
+ }
+ })
+
+ // Multiple sequential calls on the same session should each see a
+ // fresh per-request context but the same cached active project.
+ // A regression that started rebuilding the API client per call
+ // (dropping the cached org/project) would surface as either
+ // missing-context errors or differing org ids across calls.
+ it('reads the same active context across multiple sequential calls', async ({ skip }) => {
+ if (!harness.orgId) {
+ skip('Set TEST_ORG_ID to run the sequential-context test.')
+ return
+ }
+ const a = await client.callTool({ name: 'organization-get', arguments: {} })
+ const b = await client.callTool({ name: 'organization-get', arguments: {} })
+ expect(a.isError).toBeFalsy()
+ expect(b.isError).toBeFalsy()
+ expect(decodeText(a.content)).toContain(harness.orgId)
+ expect(decodeText(b.content)).toContain(harness.orgId)
+ })
+
+ // Concurrent tool calls on the same session must not interfere with
+ // each other. The SDK transport multiplexes them over one HTTP
+ // connection; the dispatcher must keep their per-call state
+ // independent (no shared mutable buffers, no cross-talk between
+ // tool args).
+ it('handles concurrent tool calls on the same session without cross-talk', async ({ skip }) => {
+ if (!harness.orgId || !harness.projectId) {
+ skip('Set TEST_ORG_ID and TEST_PROJECT_ID to run the concurrent-call test.')
+ return
+ }
+ const [orgRes, projectsRes] = await Promise.all([
+ client.callTool({ name: 'organization-get', arguments: {} }),
+ client.callTool({ name: 'projects-get', arguments: {} }),
+ ])
+ expect(orgRes.isError).toBeFalsy()
+ expect(projectsRes.isError).toBeFalsy()
+ expect(decodeText(orgRes.content)).toContain(harness.orgId)
+ expect(decodeText(projectsRes.content)).toContain(harness.projectId)
+ })
+
+ // A tool error (validation or upstream 4xx) must come back as an
+ // in-band `isError: true` result. The session must remain usable
+ // for the next call — otherwise an agent that hits one bad arg
+ // would lose its whole session.
+ it('recovers cleanly: a valid tool call works after an isError result', async ({ skip }) => {
+ if (!harness.orgId) {
+ skip('Set TEST_ORG_ID to run the error-recovery test.')
+ return
+ }
+ const bad = await client.callTool({
+ name: 'switch-project',
+ arguments: { projectId: 'definitely-not-a-number' as unknown as number },
+ })
+ expect(bad.isError).toBe(true)
+ const good = await client.callTool({ name: 'organization-get', arguments: {} })
+ expect(good.isError).toBeFalsy()
+ expect(decodeText(good.content)).toContain(harness.orgId)
+ })
+
+ // Tools wrapped with `withUiApp(...)` ship a `structuredContent`
+ // payload on per-call results. The MCP client uses that
+ // structured payload (alongside the tool-definition's
+ // `_meta.ui.resourceUri`) to render the UI app for the call.
+ //
+ // The UI metadata itself only flows back through `_meta` in
+ // single-exec mode (see `buildToolResultPayload`'s
+ // `includeUiResponseMeta` flag) — so for the default tool-call
+ // path the assertion that matters is "structuredContent is
+ // populated".
+ it('returns structuredContent on a UI-app tool call', async () => {
+ const { tools } = await client.listTools()
+ const debugTool = tools.find((t) => t.name === 'debug-mcp-ui-apps')
+ if (!debugTool) {
+ throw new Error('debug-mcp-ui-apps tool is missing — expected it for the UI-app per-call probe')
+ }
+ // Sanity check that the tool definition still has the UI
+ // metadata wired (otherwise structuredContent wouldn't be
+ // populated even with a working pipeline).
+ const meta = (debugTool as { _meta?: { ui?: { resourceUri?: string } } })._meta
+ expect(meta?.ui?.resourceUri).toBeTruthy()
+
+ const result = await client.callTool({ name: 'debug-mcp-ui-apps', arguments: {} })
+ if (result.isError) {
+ throw new Error(`debug-mcp-ui-apps errored: ${decodeText(result.content)}`)
+ }
+ const structured = (result as { structuredContent?: Record<string, unknown> }).structuredContent
+ expect(structured).toBeTruthy()
+ // The debug handler emits `message` and `sdkInfo` — check at
+ // least one survives the pipeline so we know the payload
+ // wasn't replaced with an empty object.
+ expect(structured?.message).toBeTruthy()
+ })
+
+ // switch-organization is symmetric with switch-project — same cache-
+ // write pattern, same expected flow. Worth its own test because the
+ // two go through different code paths (different cache keys, different
+ // upstream endpoints) and could regress independently.
+ it('switch-organization succeeds for the configured org id', async ({ skip }) => {
+ if (!harness.orgId) {
+ skip('Set TEST_ORG_ID to run the switch-organization behavior test.')
+ return
+ }
+ const result = await client.callTool({
+ name: 'switch-organization',
+ arguments: { orgId: harness.orgId },
+ })
+ expect(result.isError).toBeFalsy()
+ const text = decodeText(result.content)
+ expect(text.toLowerCase()).toContain('switched')
+ expect(text).toContain(harness.orgId)
+ })
+
+ it('organization-get reflects a fresh switch-organization', async ({ skip }) => {
+ if (!harness.orgId) {
+ skip('Set TEST_ORG_ID to run the org-context multi-step test.')
+ return
+ }
+ const switchResult = await client.callTool({
+ name: 'switch-organization',
+ arguments: { orgId: harness.orgId },
+ })
+ expect(switchResult.isError).toBeFalsy()
+ const orgResult = await client.callTool({ name: 'organization-get', arguments: {} })
+ expect(orgResult.isError).toBeFalsy()
+ expect(decodeText(orgResult.content)).toContain(harness.orgId)
+ })
+
+ // ?projectId=N in the URL pins the active project for the whole
+ // session — agents pass this to avoid needing a switch-project
+ // tool call first. The state resolver writes it to the cache on
+ // every request, so a project-scoped tool should resolve it
+ // without an explicit switch.
+ it('reads the active project pinned via ?projectId= URL param', async ({ skip }) => {
+ if (!harness.projectId) {
+ skip('Set TEST_PROJECT_ID to run the pinned-project URL-param test.')
+ return
+ }
+ // Open a fresh client targeted at `/mcp?projectId=<id>` so the
+ // pin is set before the first tool call.
+ const url = new URL('/mcp', harness.baseUrl)
+ url.searchParams.set('projectId', String(harness.projectId))
+ const transport = new StreamableHTTPClientTransport(url, {
+ fetch: harness.fetch,
+ requestInit: { headers: { Authorization: `Bearer ${harness.token}` } },
+ })
+ const pinnedClient = new Client(
+ { name: 'pinned-project-test', version: '0.0.0' },
+ { capabilities: {} }
+ )
+ try {
+ await pinnedClient.connect(transport as ConnectableTransport)
+ const result = await pinnedClient.callTool({ name: 'feature-flag-get-all', arguments: {} })
+ if (result.isError) {
+ throw new Error(
+ `feature-flag-get-all errored with pinned projectId: ${decodeText(result.content)}`
+ )
+ }
+ } finally {
+ await safeClose(pinnedClient)
+ }
+ })
+
+ // execute-sql is the heaviest upstream call surface in the MCP server:
+ // it crosses the API client, the PostHog `/api/environments/<id>/mcp_tools/execute_sql/`
+ // endpoint, and ClickHouse via HogQL. If this works end-to-end, the
+ // whole query path is wired up.
+ //
+ // `SELECT 1 AS one` doesn't depend on any ingested data, so it works
+ // against a freshly-booted local stack with no seed data.
+ //
+ // The tool is gated by `query:read` + `insight:read` scopes — if the
+ // test API key doesn't carry them, execute-sql won't be in the
+ // catalog and we skip rather than fail (a different test would
+ // catch the scope-filter regression).
+ it('execute-sql runs a trivial HogQL query against the upstream', async ({ skip }) => {
+ if (!harness.projectId) {
+ skip('Set TEST_PROJECT_ID to run the execute-sql roundtrip test.')
+ return
+ }
+ const { tools } = await client.listTools()
+ if (!tools.some((t) => t.name === 'execute-sql')) {
+ skip('execute-sql not in catalog for this token — needs query:read + insight:read scopes.')
+ return
+ }
+ await client.callTool({
+ name: 'switch-project',
+ arguments: { projectId: Number(harness.projectId) },
+ })
+ const result = await client.callTool({
+ name: 'execute-sql',
+ arguments: { query: 'SELECT 1 AS one' },
+ })
+ if (result.isError) {
+ throw new Error(`execute-sql errored: ${decodeText(result.content)}`)
+ }
+ // The exact serialization is at the upstream's discretion (CSV,
+ // markdown, etc.) so we don't pin to a specific format. We just
+ // check the query output landed in the response body.
+ const text = decodeText(result.content)
+ expect(text.length).toBeGreaterThan(0)
+ })
+ })
+}
+
+// Catalog filtering by query-param. The MCP server reads `?features=` and
+// `?tools=` from the URL to let agents pin themselves to a narrower set of
+// capabilities — this is how the OpenAI marketplace, Cursor, and Claude
+// Desktop pre-select a vertical (analytics, flags, etc.) rather than serving
+// the whole 392-tool catalog.
+//
+// A regression that dropped the filter would silently inflate every
+// agent's available toolset, which is hard to spot without an integration
+// test. We use a single `?features=flags` request and assert that the
+// returned `tools/list` is (a) non-empty, and (b) a strict subset of the
+// unfiltered list.
+export function defineCatalogFilterTests(
+ label: string,
+ getHarness: () => Promise<ProtocolTestHarness> | ProtocolTestHarness
+): void {
+ describe(`MCP catalog filtering (${label})`, () => {
+ async function listToolsWithQuery(
+ harness: ProtocolTestHarness,
+ search: string
+ ): Promise<{ tools: Array<{ name: string }> }> {
+ const url = new URL('/mcp', harness.baseUrl)
+ url.search = search
+ const transport = new StreamableHTTPClientTransport(url, {
+ fetch: harness.fetch,
+ requestInit: { headers: { Authorization: `Bearer ${harness.token}` } },
+ })
+ const client = new Client({ name: 'filter-test', version: '0.0.0' }, { capabilities: {} })
+ try {
+ await client.connect(transport as ConnectableTransport)
+ const result = await client.listTools()
+ return result
+ } finally {
+ await safeClose(client)
+ }
+ }
+
+ it('returns the full catalog when no filter is set', async () => {
+ const harness = await getHarness()
+ const { tools } = await listToolsWithQuery(harness, '')
+ expect(tools.length).toBeGreaterThan(10)
+ // organization-get is part of the platform-features catalog and
+ // doesn't get filtered out by any feature flag — it's a stable
+ // anchor for "this is the full set".
+ expect(tools.map((t) => t.name)).toContain('organization-get')
+ })
+
+ it('narrows the catalog when ?features= is set', async () => {
+ const harness = await getHarness()
+ const { tools: full } = await listToolsWithQuery(harness, '')
+ const { tools: filtered } = await listToolsWithQuery(harness, '?features=flags')
+ expect(filtered.length).toBeGreaterThan(0)
+ expect(filtered.length).toBeLessThan(full.length)
+ // Every filtered tool must also appear in the full list — the
+ // filter is a subset operation, never a superset / replacement.
+ const fullNames = new Set(full.map((t) => t.name))
+ for (const t of filtered) {
+ expect(fullNames.has(t.name)).toBe(true)
+ }
+ // The `flags` feature group must include the flag tools by name.
+ expect(filtered.map((t) => t.name)).toContain('feature-flag-get-all')
+ })
+
+ it('pins the catalog to specific tools when ?tools= is set', async () => {
+ const harness = await getHarness()
+ const { tools } = await listToolsWithQuery(
+ harness,
+ '?tools=organization-get,projects-get'
+ )
+ expect(tools.length).toBeGreaterThan(0)
+ const names = tools.map((t) => t.name)
+ // Pinned tools must appear; non-pinned ones must not.
+ expect(names).toContain('organization-get')
+ expect(names).toContain('projects-get')
+ expect(names).not.toContain('feature-flag-get-all')
+ })
+
+ // An unknown feature yields no tools after filtering. The Hono
+ // runtime hands back an empty `tools/list` result; the CF
+ // Workers runtime's agents SDK doesn't register the `tools/list`
+ // method when there are zero tools to expose, so the same
+ // request gets back `Method not found` instead. Both are valid
+ // runtime choices — we gate this assertion on the
+ // `gracefulUnknown` flag that the Hono harness sets.
+ it('returns an empty (but well-formed) list for an unknown feature', async ({ skip }) => {
+ const harness = await getHarness()
+ if (!harness.gracefulUnknown) {
+ skip('Empty-catalog handling is runtime-specific; only the graceful-unknown runtime returns []')
+ return
+ }
+ const { tools } = await listToolsWithQuery(harness, '?features=this-feature-does-not-exist')
+ expect(Array.isArray(tools)).toBe(true)
+ expect(tools.length).toBe(0)
+ })
+
+ // Read-only mode is the safety toggle agents flip when they want
+ // to expose the catalog to a read-only chat persona. The filter
+ // is at the tool-definition level (`annotations.readOnlyHint`)
+ // and any tool without that hint must be dropped. Without this
+ // test, a write tool that loses its annotation would still ship
+ // to read-only consumers.
+ it('drops write tools when ?readonly=true is set', async () => {
+ const harness = await getHarness()
+ const { tools: full } = await listToolsWithQuery(harness, '')
+ const { tools: readonly } = await listToolsWithQuery(harness, '?readonly=true')
+ expect(readonly.length).toBeGreaterThan(0)
+ expect(readonly.length).toBeLessThan(full.length)
+ const readonlyNames = new Set(readonly.map((t) => t.name))
+ // The CRUD-y get variants stay; the create / delete / update
+ // variants must be gone.
+ expect(readonlyNames.has('feature-flag-get-all')).toBe(true)
+ expect(readonlyNames.has('create-feature-flag')).toBe(false)
+ expect(readonlyNames.has('dashboard-create')).toBe(false)
+ })
+ })
+}
+
+// Initialize-handshake details and session lifecycle. The SDK client hides
+// most of the negotiation logic; these tests drop down to raw fetch so we can
+// assert on the protocol-version negotiation and capability advertisement.
+export function defineSessionLifecycleTests(
+ label: string,
+ getHarness: () => Promise<ProtocolTestHarness> | ProtocolTestHarness
+): void {
+ describe(`MCP session lifecycle (${label})`, () => {
+ async function initialize(harness: ProtocolTestHarness, protocolVersion?: string): Promise<Response> {
+ return harness.fetch(new URL('/mcp', harness.baseUrl), {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${harness.token}`,
+ 'Content-Type': 'application/json',
+ Accept: 'application/json, text/event-stream',
+ },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 'init-1',
+ method: 'initialize',
+ params: {
+ protocolVersion,
+ capabilities: {},
+ clientInfo: { name: 'lifecycle-test', version: '0.0.1' },
+ },
+ }),
+ })
+ }
+
+ it('advertises tools, resources, and prompts capabilities on initialize', async () => {
+ const harness = await getHarness()
+ const res = await initialize(harness)
+ expect(res.status).toBe(200)
+ const json = (await res.json()) as {
+ result?: {
+ serverInfo?: { name?: string; version?: string }
+ capabilities?: {
+ tools?: { listChanged?: boolean }
+ resources?: { listChanged?: boolean }
+ prompts?: { listChanged?: boolean }
+ }
+ protocolVersion?: string
+ instructions?: string
+ }
+ }
+ expect(json.result?.serverInfo?.name).toBe('PostHog')
+ expect(json.result?.serverInfo?.version).toBeTruthy()
+ expect(json.result?.capabilities?.tools).toBeTruthy()
+ expect(json.result?.capabilities?.resources).toBeTruthy()
+ expect(json.result?.capabilities?.prompts).toBeTruthy()
+ expect(json.result?.protocolVersion).toBeTruthy()
+ })
+
+ // Clients sometimes pin a protocol version. If we know it, we echo it
+ // back; if it's unknown we fall back to the latest supported version.
+ // A regression that started rejecting unknown versions would break
+ // older SDK clients in the wild.
+ it('falls back to the latest protocol version for an unknown request', async () => {
+ const harness = await getHarness()
+ const res = await initialize(harness, '1999-01-01')
+ expect(res.status).toBe(200)
+ const json = (await res.json()) as { result?: { protocolVersion?: string } }
+ expect(json.result?.protocolVersion).toBeTruthy()
+ expect(json.result?.protocolVersion).not.toBe('1999-01-01')
+ })
+
+ it('echoes a supported protocol version back unchanged', async () => {
+ const harness = await getHarness()
+ // The current LATEST_PROTOCOL_VERSION is what the SDK requests by
+ // default — read it back from a no-pin initialize and re-use it.
+ const probe = await initialize(harness)
+ const probeJson = (await probe.json()) as { result?: { protocolVersion?: string } }
+ const supported = probeJson.result?.protocolVersion
+ expect(supported).toBeTruthy()
+
+ const res = await initialize(harness, supported)
+ const json = (await res.json()) as { result?: { protocolVersion?: string } }
+ expect(json.result?.protocolVersion).toBe(supported)
+ })
+
+ // Reinitialize from the same connection should succeed (some clients
+ // re-init after detecting a session was reaped). The dispatcher is
+ // stateless on the Hono runtime so this is a no-op contract: it must
+ // not 4xx, and must hand back fresh capabilities.
+ it('handles a repeated initialize on the same connection', async () => {
+ const harness = await getHarness()
+ const a = await initialize(harness)
+ const b = await initialize(harness)
+ expect(a.status).toBe(200)
+ expect(b.status).toBe(200)
+ const aJson = (await a.json()) as { result?: { serverInfo?: { name?: string } } }
+ const bJson = (await b.json()) as { result?: { serverInfo?: { name?: string } } }
+ expect(aJson.result?.serverInfo?.name).toBe('PostHog')
+ expect(bJson.result?.serverInfo?.name).toBe('PostHog')
+ })
+ })
+}
+
+// Resource catalog assertions that go beyond "list isn't empty". The catalog
+// has two distinct sources (UI apps + context-mill manifest) and prompts — a
+// regression that dropped one source would show up here.
+export function defineResourceCatalogTests(
+ label: string,
+ getHarness: () => Promise<ProtocolTestHarness> | ProtocolTestHarness
+): void {
+ describe(`MCP resource catalog (${label})`, () => {
+ let client: Client
+ let harness: ProtocolTestHarness
+
+ beforeEach(async () => {
+ harness = await getHarness()
+ const built = buildStreamableClient(harness)
+ client = built.client
+ await client.connect(built.transport as ConnectableTransport)
+ })
+
+ afterEach(async () => {
+ await safeClose(client)
+ })
+
+ it('lists both UI app and context-mill resources', async () => {
+ const { resources } = await client.listResources()
+ const uris = resources.map((r) => r.uri)
+ expect(uris.some((u) => u.startsWith('ui://') || u.startsWith('mcp-ext-app://'))).toBe(true)
+ expect(uris.some((u) => u.startsWith('posthog://'))).toBe(true)
+ })
+
+ it('every resource entry has a uri, name, and mimeType', async () => {
+ const { resources } = await client.listResources()
+ expect(resources.length).toBeGreaterThan(0)
+ const malformed = resources.filter((r) => !r.uri || !r.name || !r.mimeType)
+ expect(malformed).toEqual([])
+ })
+
+ // Reading two different resources in sequence — catches a regression
+ // where one read mutates shared catalog state and corrupts the next
+ // lookup.
+ it('reads two distinct resources without cross-contamination', async () => {
+ const { resources } = await client.listResources()
+ const ui = resources.find((r) => r.uri.startsWith('ui://') || r.uri.startsWith('mcp-ext-app://'))
+ const cm = resources.find((r) => r.uri.startsWith('posthog://'))
+ if (!ui || !cm) {
+ throw new Error('expected at least one ui:// and one posthog:// resource')
+ }
+ const uiRead = await client.readResource({ uri: ui.uri })
+ const cmRead = await client.readResource({ uri: cm.uri })
+ expect(uiRead.contents[0]?.uri).toBe(ui.uri)
+ expect(cmRead.contents[0]?.uri).toBe(cm.uri)
+ })
+
+ // The prompts list may be empty on some manifest revisions (the
+ // context-mill manifest doesn't always ship prompts), so this is a
+ // shape check rather than a content check — we don't assert
+ // length > 0. What we DO require: anything that comes back has
+ // a non-empty `name`.
+ it('lists prompts as a well-formed array where every entry has a name', async ({ skip }) => {
+ if (!harness.gracefulUnknown) {
+ skip('Prompts endpoint is wired only on the graceful-unknown runtime.')
+ return
+ }
+ const { prompts } = await client.listPrompts()
+ expect(Array.isArray(prompts)).toBe(true)
+ const unnamed = prompts.filter((p) => !p.name)
+ expect(unnamed).toEqual([])
+ })
+ })
+}
diff --git a/services/mcp/tests/integration/mcp-protocol.cf.integration.test.ts b/services/mcp/tests/integration/mcp-protocol.cf.integration.test.ts
index c49577615824..fd8b1cc1325c 100644
--- a/services/mcp/tests/integration/mcp-protocol.cf.integration.test.ts
+++ b/services/mcp/tests/integration/mcp-protocol.cf.integration.test.ts
@@ -2,7 +2,16 @@ import { afterAll, beforeAll } from 'vitest'
import { startCfHarness } from './harness/cf'
import { loadIntegrationEnv, type IntegrationEnv, type IntegrationHarness } from './harness/types'
-import { defineMcpProtocolTests, defineResilienceTests, defineUiAppProtocolTests } from './mcp-protocol-suite'
+import {
+ defineAuthTests,
+ defineCatalogFilterTests,
+ defineMcpProtocolTests,
+ defineResilienceTests,
+ defineResourceCatalogTests,
+ defineToolBehaviorTests,
+ defineUiAppProtocolTests,
+ type ProtocolTestHarness,
+} from './mcp-protocol-suite'
// End-to-end MCP protocol test against the Cloudflare Workers runtime.
// - Real workerd via `wrangler unstable_dev` (DurableObjects, agents SDK,
@@ -11,6 +20,18 @@ import { defineMcpProtocolTests, defineResilienceTests, defineUiAppProtocolTests
// - Real personal API key from `TEST_POSTHOG_PERSONAL_API_KEY`
//
// Boot the local PostHog stack with `./bin/start` before running this suite.
+//
+// What runs here vs Hono-only:
+// - SDK-based suites work on both runtimes because the SDK client handles
+// CF's SSE-streaming responses and Durable Object session lifecycle.
+// - Raw-fetch JSON-asserting suites (defineHttpRouteTests,
+// defineJsonRpcEdgeCaseTests, defineSessionLifecycleTests) are Hono-only:
+// CF returns SSE bodies and requires an initialized DO session before
+// it'll dispatch arbitrary JSON-RPC methods, which the raw assertions
+// don't account for. These behaviors are still covered against the Hono
+// runtime — both runtimes share the same dispatcher / catalog code.
+// - defineAuthTests is shared because every test in it asserts on a 401
+// rejection that fires before the dispatcher / session layer.
let env: IntegrationEnv
let harness: IntegrationHarness
@@ -24,18 +45,20 @@ afterAll(async () => {
await harness?.stop()
})
-const harnessFor = (): {
- baseUrl: URL
- fetch: typeof fetch
- token: string
- token2: string | undefined
-} => ({
+const harnessFor = (): ProtocolTestHarness => ({
baseUrl: harness.baseUrl,
fetch: globalThis.fetch,
token: env.apiToken,
token2: env.apiToken2,
+ orgId: env.orgId,
+ projectId: env.projectId,
+ publicRoutes: false,
})
defineMcpProtocolTests('Cloudflare Workers (real stack)', harnessFor)
defineResilienceTests('Cloudflare Workers (real stack)', harnessFor)
defineUiAppProtocolTests('Cloudflare Workers (real stack)', harnessFor)
+defineAuthTests('Cloudflare Workers (real stack)', harnessFor)
+defineResourceCatalogTests('Cloudflare Workers (real stack)', harnessFor)
+defineToolBehaviorTests('Cloudflare Workers (real stack)', harnessFor)
+defineCatalogFilterTests('Cloudflare Workers (real stack)', harnessFor)
diff --git a/services/mcp/tests/integration/mcp-protocol.hono.integration.test.ts b/services/mcp/tests/integration/mcp-protocol.hono.integration.test.ts
index c3e140dd52d2..1cc82931ac25 100644
--- a/services/mcp/tests/integration/mcp-protocol.hono.integration.test.ts
+++ b/services/mcp/tests/integration/mcp-protocol.hono.integration.test.ts
@@ -2,7 +2,19 @@ import { afterAll, beforeAll } from 'vitest'
import { startHonoHarness } from './harness/hono'
import { loadIntegrationEnv, type IntegrationEnv, type IntegrationHarness } from './harness/types'
-import { defineMcpProtocolTests, defineResilienceTests, defineUiAppProtocolTests } from './mcp-protocol-suite'
+import {
+ defineAuthTests,
+ defineCatalogFilterTests,
+ defineHttpRouteTests,
+ defineJsonRpcEdgeCaseTests,
+ defineMcpProtocolTests,
+ defineResilienceTests,
+ defineResourceCatalogTests,
+ defineSessionLifecycleTests,
+ defineToolBehaviorTests,
+ defineUiAppProtocolTests,
+ type ProtocolTestHarness,
+} from './mcp-protocol-suite'
// End-to-end MCP protocol test against the Hono runtime.
// - Real `@hono/node-server` listener (TCP + HTTP semantics, not `app.request`)
@@ -12,6 +24,18 @@ import { defineMcpProtocolTests, defineResilienceTests, defineUiAppProtocolTests
// Boot the local PostHog stack with `./bin/start` before running this suite.
// Ensure `.env.test` defines TEST_POSTHOG_PERSONAL_API_KEY / TEST_ORG_ID /
// TEST_PROJECT_ID — matching the existing `tests/tools/*.integration.test.ts`.
+//
+// Suites wired here, each focused on a slice of MCP server behavior:
+// - `defineMcpProtocolTests` — SDK-level initialize / list / call / read
+// - `defineResilienceTests` — /sse redirects, unknown Mcp-Session-Id behavior
+// - `defineUiAppProtocolTests` — ext-app metadata, HTML stub, static asset serving
+// - `defineHttpRouteTests` — public routes (health, oauth, openai challenge, 405s)
+// - `defineAuthTests` — bearer enforcement at the /mcp boundary
+// - `defineJsonRpcEdgeCaseTests` — raw JSON-RPC (parse errors, batches, notifications, ping)
+// - `defineSessionLifecycleTests` — initialize negotiation + repeated init
+// - `defineResourceCatalogTests` — both UI and context-mill resources present and readable
+// - `defineToolBehaviorTests` — real PostHog tool calls and multi-step interactions
+// - `defineCatalogFilterTests` — ?features= and ?tools= query-param filtering
let env: IntegrationEnv
let harness: IntegrationHarness
@@ -25,22 +49,25 @@ afterAll(async () => {
await harness?.stop()
})
-const harnessFor = (): {
- baseUrl: URL
- fetch: typeof fetch
- token: string
- token2: string | undefined
- stateless: boolean
- gracefulUnknown: boolean
-} => ({
+const harnessFor = (): ProtocolTestHarness => ({
baseUrl: harness.baseUrl,
fetch: globalThis.fetch,
token: env.apiToken,
token2: env.apiToken2,
stateless: true,
gracefulUnknown: true,
+ orgId: env.orgId,
+ projectId: env.projectId,
+ publicRoutes: true,
})
defineMcpProtocolTests('Hono (real stack)', harnessFor)
defineResilienceTests('Hono (real stack)', harnessFor)
defineUiAppProtocolTests('Hono (real stack)', harnessFor)
+defineHttpRouteTests('Hono (real stack)', harnessFor)
+defineAuthTests('Hono (real stack)', harnessFor)
+defineJsonRpcEdgeCaseTests('Hono (real stack)', harnessFor)
+defineSessionLifecycleTests('Hono (real stack)', harnessFor)
+defineResourceCatalogTests('Hono (real stack)', harnessFor)
+defineToolBehaviorTests('Hono (real stack)', harnessFor)
+defineCatalogFilterTests('Hono (real stack)', harnessFor)