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.

feat(mcp): refactor hono mcp server (#59368)

Joshua Snyderbfb633a85ed1
diff --git a/services/mcp/package.json b/services/mcp/package.json
index b7e15e2eec4c..321a2709bf0e 100644
--- a/services/mcp/package.json
+++ b/services/mcp/package.json
@@ -28,6 +28,7 @@
"test": "vitest",
"test:integration": "vitest run --config vitest.integration.config.mts",
"test:hono": "vitest run --config vitest.hono.config.mts",
+ "test:perf": "vitest run --config vitest.perf.config.mts",
"test:watch": "vitest watch",
"typecheck": "tsc --noEmit",
"generate-mcp-types": "node scripts/generate-mcp-types.mjs",
diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.ts
new file mode 100644
index 000000000000..aa872df18c2f
--- /dev/null
+++ b/services/mcp/src/hono/analytics.ts
@@ -0,0 +1,97 @@
+import { getPostHogClient } from '@/lib/posthog'
+import {
+ AnalyticsEvent,
+ buildMCPAnalyticsGroups,
+ buildMCPContextProperties,
+ type MCPAnalyticsContext,
+} from '@/lib/posthog/analytics'
+import type { RequestProperties } from '@/lib/request-properties'
+
+import type { ResolvedState } from './request-state-resolver'
+
+function buildBaseProperties(
+ state: ResolvedState,
+ props: RequestProperties,
+ analyticsContext: MCPAnalyticsContext | undefined
+): {
+ properties: Record<string, unknown>
+ groups: Record<string, string>
+} {
+ const properties: Record<string, unknown> = {
+ mcp_runtime: 'hono',
+ ...(props.mcpClientName ? { mcp_client_name: props.mcpClientName } : {}),
+ ...(props.mcpClientVersion ? { mcp_client_version: props.mcpClientVersion } : {}),
+ ...(props.mcpProtocolVersion ? { mcp_protocol_version: props.mcpProtocolVersion } : {}),
+ ...(props.mcpConsumer ? { mcp_consumer: props.mcpConsumer } : {}),
+ ...(props.transport ? { mcp_transport: props.transport } : {}),
+ ...(props.mcpSessionId ? { mcp_session_id: props.mcpSessionId } : {}),
+ ...(props.mcpConversationId ? { mcp_conversation_id: props.mcpConversationId } : {}),
+ ...(props.mode ? { mcp_mode: props.mode } : {}),
+ ...(state.version !== undefined ? { mcp_version: state.version } : {}),
+ ...(analyticsContext ? buildMCPContextProperties(analyticsContext) : {}),
+ }
+ const groups = analyticsContext ? buildMCPAnalyticsGroups(analyticsContext) : {}
+ return { properties, groups }
+}
+
+export async function trackInitEvent(props: RequestProperties, state: ResolvedState): Promise<void> {
+ try {
+ const analyticsContext = await state.reqCtx.getAnalyticsContextSafe(state.context)
+ const initDurationMs = props.requestStartTime ? Date.now() - props.requestStartTime : undefined
+ const sessionUuid = props.sessionId ? await state.reqCtx.getSessionUuid(props.sessionId) : undefined
+
+ const { properties, groups } = buildBaseProperties(state, props, analyticsContext)
+
+ getPostHogClient().capture({
+ distinctId: state.distinctId,
+ event: AnalyticsEvent.MCP_INIT,
+ ...(Object.keys(groups).length > 0 ? { groups } : {}),
+ properties: {
+ ...properties,
+ tool_count: state.allTools.length,
+ has_organization_id: !!props.organizationId,
+ has_project_id: !!props.projectId,
+ read_only: !!props.readOnly,
+ via_sse_redirect: !!props.viaSseRedirect,
+ ...(props.mode ? { mcp_mode_explicit: props.mode } : {}),
+ ...(initDurationMs !== undefined ? { init_duration_ms: initDurationMs } : {}),
+ ...(sessionUuid ? { $session_id: sessionUuid } : {}),
+ },
+ })
+ } catch {
+ // never break the request for analytics
+ }
+}
+
+export async function trackToolCall(
+ toolName: string,
+ durationMs: number,
+ isError: boolean,
+ props: RequestProperties,
+ state: ResolvedState,
+ extraProperties?: Record<string, unknown>
+): Promise<void> {
+ try {
+ const analyticsContext = await state.reqCtx.getAnalyticsContextSafe(state.context)
+ const sessionUuid = props.sessionId ? await state.reqCtx.getSessionUuid(props.sessionId) : undefined
+
+ const { properties, groups } = buildBaseProperties(state, props, analyticsContext)
+
+ getPostHogClient().capture({
+ distinctId: state.distinctId,
+ event: AnalyticsEvent.MCP_TOOL_CALL,
+ ...(Object.keys(groups).length > 0 ? { groups } : {}),
+ properties: {
+ ...properties,
+ tool_name: toolName,
+ $mcp_tool_name: toolName,
+ $mcp_duration_ms: durationMs,
+ $mcp_is_error: isError,
+ ...(sessionUuid ? { $session_id: sessionUuid } : {}),
+ ...extraProperties,
+ },
+ })
+ } catch {
+ // never break the request for analytics
+ }
+}
diff --git a/services/mcp/src/hono/app.ts b/services/mcp/src/hono/app.ts
index 5ce631f40e9a..57ecf2ab7ab6 100644
--- a/services/mcp/src/hono/app.ts
+++ b/services/mcp/src/hono/app.ts
@@ -1,45 +1,47 @@
-import { Hono } from 'hono'
+import { Hono } from "hono";
-import { httpMetrics, securityHeaders } from './middleware'
-import { registerPublicRoutes } from './public-routes'
-import { StreamableMcpHandler } from './streamable-handler'
-import type { HonoCtx, RedisWithPing } from './types'
+import { httpMetrics, securityHeaders } from "./middleware";
+import { registerPublicRoutes } from "./public-routes";
+import { StreamableMcpHandler } from "./streamable-handler";
+import type { HonoCtx, RedisWithPing } from "./types";
-export type Lifecycle = { shuttingDown: boolean }
+export type Lifecycle = { shuttingDown: boolean };
export type App = {
- app: Hono
- lifecycle: Lifecycle
- warmup: () => Promise<void>
-}
+ app: Hono;
+ lifecycle: Lifecycle;
+ warmup: () => Promise<void>;
+};
+
+const sseRedirect = (c: HonoCtx): Response => {
+ const target = new URL(c.req.url);
+ target.pathname = "/mcp" + target.pathname.slice("/sse".length);
+ target.searchParams.set("_deprecated", "sse");
+ return c.redirect(target.toString(), 308) as unknown as Response;
+};
export function createApp(redis: RedisWithPing): App {
- const app = new Hono()
- const lifecycle: Lifecycle = { shuttingDown: false }
+ const app = new Hono();
+ const lifecycle: Lifecycle = { shuttingDown: false };
+
+ app.use("*", securityHeaders);
+ app.use("*", httpMetrics);
- app.use('*', securityHeaders)
- app.use('*', httpMetrics)
+ registerPublicRoutes(app, redis, lifecycle);
- registerPublicRoutes(app, redis, lifecycle)
+ app.all("/sse", sseRedirect);
+ app.all("/sse/*", sseRedirect);
- const sseRedirect = (c: HonoCtx): Response => {
- const target = new URL(c.req.url)
- target.pathname = '/mcp' + target.pathname.slice('/sse'.length)
- target.searchParams.set('_deprecated', 'sse')
- return c.redirect(target.toString(), 308) as unknown as Response
- }
- app.all('/sse', sseRedirect)
- app.all('/sse/*', sseRedirect)
+ const streamable = new StreamableMcpHandler(redis, lifecycle);
- const streamable = new StreamableMcpHandler(redis, lifecycle)
- app.all('/mcp', streamable.fetch)
- app.all('/mcp/*', streamable.fetch)
+ app.all("/mcp", streamable.fetch);
+ app.all("/mcp/*", streamable.fetch);
- app.all('*', (c) => c.notFound())
+ app.all("*", (c) => c.notFound());
return {
app,
lifecycle,
warmup: () => streamable.warmup(),
- }
+ };
}
diff --git a/services/mcp/src/hono/dispatcher.ts b/services/mcp/src/hono/dispatcher.ts
new file mode 100644
index 000000000000..86a29d7ff9af
--- /dev/null
+++ b/services/mcp/src/hono/dispatcher.ts
@@ -0,0 +1,226 @@
+import {
+ ErrorCode,
+ JSONRPC_VERSION,
+ LATEST_PROTOCOL_VERSION,
+ SUPPORTED_PROTOCOL_VERSIONS,
+} from '@modelcontextprotocol/sdk/types.js'
+import type {
+ CallToolRequest,
+ GetPromptRequest,
+ InitializeRequest,
+ InitializeResult,
+ JSONRPCMessage,
+ JSONRPCRequest,
+ ListPromptsRequest,
+ ListResourcesRequest,
+ ListToolsRequest,
+ PingRequest,
+ ReadResourceRequest,
+} from '@modelcontextprotocol/sdk/types.js'
+
+import type { RequestProperties } from '@/lib/request-properties'
+
+import type { RedisLike } from './cache/RedisCache'
+import { getEnv } from './constants'
+import { initDurationSeconds } from './metrics'
+import { ToolCatalog } from './tool-catalog'
+
+import { trackInitEvent } from './analytics'
+import { InstructionsBuilder } from './instructions'
+import { RequestStateResolver, type ResolvedState } from './request-state-resolver'
+import { ResourceCatalog } from './resource-catalog'
+import { ToolExecutor } from './tool-executor'
+
+export { McpDispatcher }
+export type { ResolvedState } from './request-state-resolver'
+
+function loadGuidelines(): string {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const mod = require('@shared/guidelines.md')
+ return typeof mod === 'string' ? mod : (mod?.default ?? '')
+ } catch {
+ // @shared alias only resolves in the esbuild production bundle.
+ // Fall back to reading from disk (works in Vitest/test contexts).
+ }
+ try {
+ const fs = require('node:fs')
+ const path = require('node:path')
+ return fs.readFileSync(path.resolve(process.cwd(), 'shared/guidelines.md'), 'utf-8')
+ } catch {
+ return ''
+ }
+}
+
+const MAX_BATCH_SIZE = 100
+const MAX_BODY_BYTES = 1_048_576
+
+const Method = {
+ Initialize: 'initialize' as InitializeRequest['method'],
+ ToolsList: 'tools/list' as ListToolsRequest['method'],
+ ToolsCall: 'tools/call' as CallToolRequest['method'],
+ ResourcesList: 'resources/list' as ListResourcesRequest['method'],
+ ResourcesRead: 'resources/read' as ReadResourceRequest['method'],
+ PromptsList: 'prompts/list' as ListPromptsRequest['method'],
+ PromptsGet: 'prompts/get' as GetPromptRequest['method'],
+ Ping: 'ping' as PingRequest['method'],
+} as const
+
+const TRACKED_METHODS: Set<string> = new Set([Method.Initialize, Method.ToolsList, Method.ToolsCall])
+
+function isRequest(msg: JSONRPCMessage): msg is JSONRPCRequest {
+ return typeof msg === 'object' && msg !== null && 'id' in msg && typeof (msg as { method?: unknown }).method === 'string'
+}
+
+type JsonRpcResultResponse = { jsonrpc: typeof JSONRPC_VERSION; id: number | string; result: unknown }
+type JsonRpcErrorResponse = { jsonrpc: typeof JSONRPC_VERSION; id: number | string; error: { code: number; message: string } }
+type JsonRpcResponse = JsonRpcResultResponse | JsonRpcErrorResponse
+
+function jsonRpcResult(id: number | string, result: unknown): JsonRpcResultResponse {
+ return { jsonrpc: JSONRPC_VERSION, id, result }
+}
+
+function jsonRpcMethodError(id: number | string, code: number, message: string): JsonRpcErrorResponse {
+ return { jsonrpc: JSONRPC_VERSION, id, error: { code, message } }
+}
+
+function jsonRpcErrorResponse(id: unknown, code: number, message: string): Response {
+ return new Response(
+ JSON.stringify({ jsonrpc: JSONRPC_VERSION, id: id ?? null, error: { code, message } }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } }
+ )
+}
+
+class McpDispatcher {
+ private readonly catalog: ToolCatalog
+ private readonly resourceCatalog: ResourceCatalog
+ private readonly stateResolver: RequestStateResolver
+ private readonly toolExecutor: ToolExecutor
+ private readonly instructionsBuilder: InstructionsBuilder
+
+ private warmupPromise: Promise<void> | undefined
+
+ constructor(catalog: ToolCatalog, redis: RedisLike) {
+ const env = getEnv()
+ this.catalog = catalog
+ this.resourceCatalog = new ResourceCatalog(env)
+ this.stateResolver = new RequestStateResolver(catalog, redis, env)
+ this.instructionsBuilder = new InstructionsBuilder(loadGuidelines())
+ this.toolExecutor = new ToolExecutor(catalog, this.instructionsBuilder)
+ }
+
+ async warmup(): Promise<void> {
+ this.warmupPromise ??= this.doWarmup()
+ await this.warmupPromise
+ }
+
+ private async doWarmup(): Promise<void> {
+ await this.catalog.warmup()
+ await this.resourceCatalog.warmup()
+ }
+
+ async handleRequest(req: Request, props: RequestProperties): Promise<Response> {
+ const contentLength = req.headers.get('content-length')
+ if (contentLength && parseInt(contentLength, 10) > MAX_BODY_BYTES) {
+ return jsonRpcErrorResponse(null, ErrorCode.InvalidRequest, 'Request body too large')
+ }
+
+ let body: unknown
+ try {
+ body = await req.json()
+ } catch {
+ return jsonRpcErrorResponse(null, ErrorCode.ParseError, 'Parse error: Invalid JSON')
+ }
+
+ const wasArray = Array.isArray(body)
+ const messages: JSONRPCMessage[] = wasArray ? (body as JSONRPCMessage[]) : [body as JSONRPCMessage]
+
+ if (messages.length > MAX_BATCH_SIZE) {
+ return jsonRpcErrorResponse(null, ErrorCode.InvalidRequest, 'Batch too large')
+ }
+
+ const requests = messages.filter(isRequest)
+ if (requests.length === 0) {
+ return new Response(null, { status: 202 })
+ }
+
+ const needsState = requests.some((r) => TRACKED_METHODS.has(r.method))
+ const state = needsState ? await this.stateResolver.resolve(props) : undefined
+
+ if (!wasArray && requests.length === 1) {
+ const result = await this.dispatch(requests[0]!, props, state)
+ return new Response(JSON.stringify(result), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ })
+ }
+
+ const results = await Promise.all(requests.map((r) => this.dispatch(r, props, state)))
+ return new Response(JSON.stringify(results), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ })
+ }
+
+ private async dispatch(
+ request: JSONRPCRequest,
+ props: RequestProperties,
+ state: ResolvedState | undefined
+ ): Promise<JsonRpcResponse> {
+ const { id, method, params } = request
+
+ try {
+ switch (method) {
+ case Method.Initialize:
+ return jsonRpcResult(id, await this.handleInitialize(params, props, state!))
+ case Method.ToolsList:
+ return jsonRpcResult(id, await this.toolExecutor.handleToolsList(state!, props))
+ case Method.ToolsCall:
+ return jsonRpcResult(id, await this.toolExecutor.handleToolCall(params, props, state!))
+ case Method.ResourcesList:
+ return jsonRpcResult(id, this.resourceCatalog.getResourcesList())
+ case Method.ResourcesRead:
+ return jsonRpcResult(id, this.resourceCatalog.readResource(params))
+ case Method.PromptsList:
+ return jsonRpcResult(id, this.resourceCatalog.getPromptsList())
+ case Method.PromptsGet:
+ return jsonRpcResult(id, this.resourceCatalog.getPrompt(params))
+ case Method.Ping:
+ return jsonRpcResult(id, {})
+ default:
+ return jsonRpcMethodError(id, ErrorCode.MethodNotFound, 'Method not found')
+ }
+ } catch (error) {
+ console.error('[McpDispatcher] Internal error:', error)
+ return jsonRpcMethodError(id, ErrorCode.InternalError, 'Internal error')
+ }
+ }
+
+ private async handleInitialize(
+ params: Record<string, unknown> | undefined,
+ props: RequestProperties,
+ state: ResolvedState
+ ): Promise<InitializeResult> {
+ const requestedVersion = (params?.protocolVersion as string) ?? LATEST_PROTOCOL_VERSION
+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)
+ ? requestedVersion
+ : LATEST_PROTOCOL_VERSION
+
+ const instructions = await this.instructionsBuilder.build(props, state)
+
+ initDurationSeconds.observe(props.requestStartTime ? (Date.now() - props.requestStartTime) / 1000 : 0)
+
+ void trackInitEvent(props, state)
+
+ return {
+ protocolVersion,
+ capabilities: {
+ tools: { listChanged: false },
+ resources: { listChanged: false },
+ prompts: { listChanged: false },
+ },
+ serverInfo: { name: 'PostHog', version: '1.0.0' },
+ ...(instructions ? { instructions } : {}),
+ }
+ }
+}
diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.ts
new file mode 100644
index 000000000000..4a9dc1a52a4d
--- /dev/null
+++ b/services/mcp/src/hono/instructions.ts
@@ -0,0 +1,105 @@
+import { hasScope } from '@/lib/api'
+import type { QueryToolInfo } from '@/lib/instructions'
+import { type InstructionsContext, InstructionsFormatter } from '@/lib/instructions-formatter'
+import type { RequestProperties } from '@/lib/request-properties'
+import { formatPrompt } from '@/lib/utils'
+import EXECUTE_SQL_PROMPT from '@/templates/execute-sql-prompt.md'
+import { getToolDefinition } from '@/tools/toolDefinitions'
+
+import type { Tool as McpTool } from '@modelcontextprotocol/sdk/types.js'
+
+import type { ResolvedState } from './request-state-resolver'
+
+export class InstructionsBuilder {
+ private readonly formatter: InstructionsFormatter
+ private readonly guidelines: string
+
+ constructor(guidelines: string, formatter?: InstructionsFormatter) {
+ this.guidelines = guidelines
+ this.formatter = formatter ?? new InstructionsFormatter()
+ }
+
+ async build(props: RequestProperties, state: ResolvedState): Promise<string> {
+ const supportsInstructions = state.clientProfile.capabilities.supportsInstructions
+ if (!supportsInstructions) {return ''}
+
+ const { projectId } = props
+ const resolvedProjectId = projectId || (await state.reqCtx.cache.get('projectId'))
+ const [groupTypes, metadata] = await Promise.all([
+ resolvedProjectId && hasScope(state.apiKeyScopes, 'group:read')
+ ? state.context.stateManager.getOrFetchGroupTypes(resolvedProjectId)
+ : undefined,
+ state.context.stateManager.getEnvironmentPrompt(),
+ ])
+
+ const ctx: InstructionsContext = {
+ ...this.buildContext(state),
+ groupTypes,
+ metadata,
+ }
+
+ if (state.useSingleExec) {
+ return this.formatter.buildExecInstructions(ctx)
+ } else if (state.version === 2) {
+ return this.formatter.buildV2Instructions(ctx)
+ }
+ return this.formatter.buildV1Instructions(metadata)
+ }
+
+ buildContext(state: ResolvedState): InstructionsContext {
+ return {
+ guidelines: this.guidelines,
+ tools: state.allTools.map((t) => ({
+ name: t.name,
+ category: getToolDefinition(t.name, state.version).category,
+ })),
+ queryTools: state.allTools
+ .filter((t) => t.name.startsWith('query-'))
+ .map((t) => {
+ const def = getToolDefinition(t.name, state.version)
+ return {
+ name: t.name,
+ title: def.title,
+ ...(def.system_prompt_hint ? { systemPromptHint: def.system_prompt_hint } : {}),
+ } as QueryToolInfo
+ }),
+ featureFlags: state.toolFeatureFlags,
+ }
+ }
+
+ buildExecToolEntry(state: ResolvedState, _props: RequestProperties): McpTool {
+ const supportsInstructions = state.clientProfile.capabilities.supportsInstructions
+ const ctx = this.buildContext(state)
+ const commandReference = this.formatter.buildExecCommandReference(ctx, {
+ stripEnvContext: supportsInstructions,
+ })
+ const ExecSchema = { command: { type: 'string', description: commandReference } }
+
+ return {
+ name: 'exec',
+ title: 'Execute PostHog command',
+ description: this.formatter.buildExecToolDescription(),
+ inputSchema: { type: 'object', properties: ExecSchema, required: ['command'] },
+ }
+ }
+
+ buildExecCommandReference(state: ResolvedState): string {
+ const supportsInstructions = state.clientProfile.capabilities.supportsInstructions
+ const ctx = this.buildContext(state)
+ return this.formatter.buildExecCommandReference(ctx, {
+ stripEnvContext: supportsInstructions,
+ })
+ }
+
+ buildExecToolDescription(): string {
+ return this.formatter.buildExecToolDescription()
+ }
+
+ getGuidelines(): string {
+ return this.guidelines
+ }
+
+ formatExecuteSqlDescription(): string {
+ return formatPrompt(EXECUTE_SQL_PROMPT, { guidelines: this.guidelines.trim() })
+ }
+}
diff --git a/services/mcp/src/hono/mcp-server.ts b/services/mcp/src/hono/mcp-server.ts
deleted file mode 100644
index 7754800c41c5..000000000000
--- a/services/mcp/src/hono/mcp-server.ts
+++ /dev/null
@@ -1,740 +0,0 @@
-import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'
-import { McpServer, type ToolCallback } from '@modelcontextprotocol/sdk/server/mcp.js'
-import type { z } from 'zod'
-
-import { ApiClient } from '@/api/client'
-import { hasScope } from '@/lib/api'
-import { buildToolResultPayload, isToolCallPayload } from '@/lib/build-tool-result'
-import { MCPClientProfile } from '@/lib/client-detection'
-import { handleToolError, wrapError } from '@/lib/errors'
-import { type QueryToolInfo } from '@/lib/instructions'
-import { InstructionsFormatter } from '@/lib/instructions-formatter'
-import { getPostHogClient } from '@/lib/posthog'
-import {
- AnalyticsEvent,
- buildMCPAnalyticsGroups,
- buildMCPContextProperties,
- initMcpAnalytics,
- type MCPAnalyticsContext,
-} from '@/lib/posthog/analytics'
-import { evaluateFeatureFlags, type FlagGroups, isFeatureFlagEnabled } from '@/lib/posthog/flags'
-import { type RequestProperties } from '@/lib/request-properties'
-import { SessionManager } from '@/lib/SessionManager'
-import { StateManager } from '@/lib/StateManager'
-import { formatPrompt, type McpMode } from '@/lib/utils'
-import { registerPrompts } from '@/prompts'
-import { registerResources } from '@/resources'
-import type { ContextMillResource } from '@/resources/manifest-types'
-import { registerUiAppResources } from '@/resources/ui-apps'
-import EXECUTE_SQL_PROMPT from '@/templates/execute-sql-prompt.md'
-import { createExecInnerToolCallResolver, createExecTool, type ExecInnerCallTracker } from '@/tools/exec'
-import { getToolDefinition } from '@/tools/toolDefinitions'
-import { type Context, type Env, type State, type Tool } from '@/tools/types'
-
-import { RedisCache, type RedisLike } from './cache/RedisCache'
-import { getCustomApiBaseUrl, getEnv } from './constants'
-import { initDurationSeconds, toolCallDurationSeconds, toolCallsTotal } from './metrics'
-import type { ToolCatalog, ToolCatalogFilterOptions } from './tool-catalog'
-
-export interface WarmupData {
- catalog: ToolCatalog
- resourceEntries: readonly ContextMillResource[]
-}
-
-export type { RequestProperties }
-
-const instructionsFormatter = new InstructionsFormatter()
-
-type HonoRequestProperties = RequestProperties & {
- mcpAnalyticsInitAction?: 'initialized' | 'skipped' | 'failed' | undefined
- mcpAnalyticsInitReason?: string | undefined
- mcpAnalyticsInitErrorName?: string | undefined
- mcpAnalyticsInitErrorMessage?: string | undefined
-}
-
-// Guidelines are generated at build time; optional import so tests and
-// unbundled dev runs don't explode when the file is absent.
-let _guidelines = ''
-try {
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const mod = require('@shared/guidelines.md')
- _guidelines = typeof mod === 'string' ? mod : (mod?.default ?? '')
-} catch {
- _guidelines = ''
-}
-
-export class HonoMcpServer {
- server: McpServer
-
- private props: HonoRequestProperties
-
- private _cache: RedisCache<State> | undefined
-
- private _api: ApiClient | undefined
-
- private _sessionManager: SessionManager | undefined
-
- private redis: RedisLike
-
- private env: Env
-
- private clientInfoResolved = false
- private mcpClientName: string | undefined
- private mcpClientVersion: string | undefined
- private mcpProtocolVersion: string | undefined
- private mcpMode: McpMode | undefined
- private mcpVersion: number | undefined
- private _warmup: WarmupData | undefined
-
- constructor(redis: RedisLike, props: RequestProperties, warmup?: WarmupData) {
- this.props = props
- this.redis = redis
- this.env = getEnv()
- this._warmup = warmup
- this.server = new McpServer(
- { name: 'PostHog', version: '1.0.0' },
- { instructions: instructionsFormatter.buildV1Instructions() }
- )
- }
-
- get requestProperties(): HonoRequestProperties {
- return this.props
- }
-
- get cache(): RedisCache<State> {
- if (!this.props.userHash) {
- throw new Error('User hash is required to use the cache')
- }
-
- if (!this._cache) {
- this._cache = new RedisCache<State>(this.props.userHash, this.redis)
- }
-
- return this._cache
- }
-
- get sessionManager(): SessionManager {
- if (!this._sessionManager) {
- this._sessionManager = new SessionManager(this.cache)
- }
-
- return this._sessionManager
- }
-
- async resolveClientInfo(): Promise<void> {
- if (this.clientInfoResolved) {
- return
- }
-
- const { mcpClientName, mcpClientVersion, mcpProtocolVersion } = this.props
- if (mcpClientName || mcpClientVersion) {
- this.mcpClientName = mcpClientName
- this.mcpClientVersion = mcpClientVersion
- this.mcpProtocolVersion = mcpProtocolVersion
- this.clientInfoResolved = true
- }
- }
-
- async getBaseUrl(): Promise<string> {
- const customApiBaseUrl = getCustomApiBaseUrl()
- if (customApiBaseUrl) {
- return customApiBaseUrl
- }
- if (process.env.NODE_ENV === 'production') {
- throw new Error(
- 'POSTHOG_API_BASE_URL must be set in production — Hono deployments are regional and do not auto-detect.'
- )
- }
- return 'http://localhost:8010'
- }
-
- async api(): Promise<ApiClient> {
- if (!this._api) {
- const baseUrl = await this.getBaseUrl()
- await this.resolveClientInfo()
- this._api = new ApiClient({
- apiToken: this.props.apiToken,
- baseUrl,
- clientUserAgent: this.props.clientUserAgent,
- mcpClientName: this.mcpClientName,
- mcpClientVersion: this.mcpClientVersion,
- mcpProtocolVersion: this.mcpProtocolVersion,
- mcpConsumer: this.props.mcpConsumer,
- })
- }
-
- return this._api
- }
-
- async getDistinctId(): Promise<string> {
- let _distinctId = await this.cache.get('distinctId')
-
- if (!_distinctId) {
- const userResult = await (await this.api()).users().me()
- if (!userResult.success) {
- throw wrapError(`Failed to get user: ${userResult.error.message}`, userResult.error)
- }
- await this.cache.set('distinctId', userResult.data.distinct_id)
- _distinctId = userResult.data.distinct_id as string
- }
-
- return _distinctId
- }
-
- async trackEvent(
- event: AnalyticsEvent,
- properties: Record<string, any> = {},
- options?: { context?: MCPAnalyticsContext; previousContext?: MCPAnalyticsContext }
- ): Promise<void> {
- try {
- const distinctId = await this.getDistinctId()
-
- await this.resolveClientInfo()
-
- const clientName = await this.cache.get('clientName')
-
- const contextProperties = options?.context ? buildMCPContextProperties(options.context) : {}
- const previousContextProperties = options?.previousContext
- ? buildMCPContextProperties(options.previousContext, { prefix: 'previous_' })
- : {}
- const groups = options?.context ? buildMCPAnalyticsGroups(options.context) : {}
-
- const client = getPostHogClient()
- client.capture({
- distinctId,
- event,
- ...(Object.keys(groups).length > 0 ? { groups } : {}),
- properties: {
- ...(this.props.sessionId
- ? {
- $session_id: await this.sessionManager.getSessionUuid(this.props.sessionId),
- }
- : {}),
- ...(clientName ? { mcp_oauth_client_name: clientName } : {}),
- ...(this.mcpClientName ? { mcp_client_name: this.mcpClientName } : {}),
- ...(this.mcpClientVersion ? { mcp_client_version: this.mcpClientVersion } : {}),
- ...(this.mcpProtocolVersion ? { mcp_protocol_version: this.mcpProtocolVersion } : {}),
- ...(this.props.mcpConsumer ? { mcp_consumer: this.props.mcpConsumer } : {}),
- ...(this.props.transport ? { mcp_transport: this.props.transport } : {}),
- ...(this.props.mcpSessionId ? { mcp_session_id: this.props.mcpSessionId } : {}),
- ...(this.props.mcpConversationId ? { mcp_conversation_id: this.props.mcpConversationId } : {}),
- ...(this.mcpMode ? { mcp_mode: this.mcpMode } : {}),
- ...(this.mcpVersion !== undefined ? { mcp_version: this.mcpVersion } : {}),
- mcp_runtime: 'hono',
- ...contextProperties,
- ...previousContextProperties,
- ...properties,
- },
- })
- } catch {
- // skip
- }
- }
-
- private async getAnalyticsContextSafe(
- context: Pick<Context, 'stateManager'>
- ): Promise<MCPAnalyticsContext | undefined> {
- try {
- return await context.stateManager.getAnalyticsContext()
- } catch {
- return undefined
- }
- }
-
- private async trackContextSwitchEvent(
- toolName: string,
- context: Context,
- previousContext: MCPAnalyticsContext | undefined
- ): Promise<void> {
- const resolvedContext = await this.getAnalyticsContextSafe(context)
- if (!resolvedContext) {
- return
- }
-
- const event =
- toolName === 'switch-project'
- ? AnalyticsEvent.MCP_PROJECT_SWITCHED
- : toolName === 'switch-organization'
- ? AnalyticsEvent.MCP_ORGANIZATION_SWITCHED
- : undefined
- if (!event) {
- return
- }
-
- await this.trackEvent(event, {}, { context: resolvedContext, ...(previousContext ? { previousContext } : {}) })
- }
-
- registerTool<TSchema extends z.ZodObject>(
- tool: Tool<TSchema>,
- handler: (params: z.infer<TSchema>) => Promise<any>
- ): void {
- const wrappedHandler = async (params: z.infer<TSchema>): Promise<any> => {
- const validation = tool.schema.safeParse(params)
-
- if (!validation.success) {
- toolCallsTotal.inc({ tool: tool.name, status: 'validation_error' })
- const errorOutput = `Invalid input: ${validation.error.message}`
-
- return {
- content: [
- {
- type: 'text',
- text: errorOutput,
- },
- ],
- }
- }
-
- const stop = toolCallDurationSeconds.startTimer({ tool: tool.name })
- try {
- const isContextSwitch = tool.name === 'switch-project' || tool.name === 'switch-organization'
- const previousContext = isContextSwitch
- ? await this.getAnalyticsContextSafe(await this.getContext())
- : undefined
- const handlerResult = await handler(params)
- if (isContextSwitch) {
- void this.trackContextSwitchEvent(tool.name, await this.getContext(), previousContext)
- }
- toolCallsTotal.inc({ tool: tool.name, status: 'success' })
- stop({ status: 'success' })
- if (isToolCallPayload(handlerResult)) {
- return handlerResult
- }
- const hasUiResource = !!tool._meta?.ui?.resourceUri
- const needsDistinctId = hasUiResource && typeof handlerResult !== 'string'
- const distinctId = needsDistinctId ? await this.getDistinctId() : undefined
-
- return buildToolResultPayload({
- handlerResult,
- toolMeta: tool._meta,
- toolName: tool.name,
- params,
- clientName: this.mcpClientName,
- distinctId,
- })
- } catch (error: any) {
- toolCallsTotal.inc({ tool: tool.name, status: 'error' })
- stop({ status: 'error' })
- const distinctId = await this.getDistinctId()
- return handleToolError(
- error,
- tool.name,
- distinctId,
- this.props.sessionId ? await this.sessionManager.getSessionUuid(this.props.sessionId) : undefined
- )
- }
- }
-
- let normalizedMeta = tool._meta
- if (tool._meta?.ui?.resourceUri && !tool._meta[RESOURCE_URI_META_KEY]) {
- normalizedMeta = {
- ...tool._meta,
- [RESOURCE_URI_META_KEY]: tool._meta.ui.resourceUri,
- }
- }
-
- this.server.registerTool(
- tool.name,
- {
- title: tool.title,
- description: tool.description,
- inputSchema: tool.schema.shape,
- annotations: tool.annotations,
- ...(normalizedMeta ? { _meta: normalizedMeta } : {}),
- },
- wrappedHandler as unknown as ToolCallback<TSchema['shape']>
- )
- }
-
- async getContext(): Promise<Context> {
- const api = await this.api()
- const stateManager = new StateManager(this.cache, api)
- const partialContext: Omit<Context, 'trackEvent'> = {
- api,
- cache: this.cache,
- env: this.env,
- stateManager,
- sessionManager: this.sessionManager,
- getDistinctId: () => this.getDistinctId(),
- }
- const trackEvent: Context['trackEvent'] = async (event, properties = {}) => {
- const analyticsContext = await this.getAnalyticsContextSafe(partialContext)
- await this.trackEvent(event, properties, analyticsContext ? { context: analyticsContext } : undefined)
- }
- return { ...partialContext, trackEvent }
- }
-
- async init(): Promise<void> {
- const stopInit = initDurationSeconds.startTimer()
- try {
- await this.initInner()
- } finally {
- stopInit()
- }
- }
-
- private async initInner(): Promise<void> {
- const _t0 = performance.now()
- const _lap = (label: string): void => {
- const elapsed = performance.now() - _t0
- // oxlint-disable-next-line no-console
- console.log(`[init-profile] ${label.padEnd(40)} +${elapsed.toFixed(0)}ms`)
- }
-
- const { features, tools, version: clientVersion, organizationId, projectId, readOnly, mode } = this.props
-
- await this.resolveClientInfo()
- _lap('resolveClientInfo')
-
- // User-level flags resolve in parallel with cache seeding. Tool flags are
- // deferred until orgId/projectUuid are known so group-scoped rollouts evaluate correctly.
- const flagPromise = this.resolveVersionFlag()
- const singleExecPromise = this.resolveSingleExecFlag()
-
- // Seed cache with header-provided IDs before any fetches
- if (organizationId) {
- await this.cache.set('orgId', organizationId)
- }
- let cachedProjectId: string | undefined
- if (projectId) {
- cachedProjectId = projectId
- await this.cache.set('projectId', projectId)
- }
- _lap('cache seeding')
-
- const context = await this.getContext()
- _lap('getContext')
-
- if (!cachedProjectId) {
- cachedProjectId = await this.cache.get('projectId')
- }
-
- // Initialize org and project
- if (!cachedProjectId) {
- await context.stateManager.setDefaultOrganizationAndProject()
- }
- _lap('setDefaultOrgAndProject')
-
- // Flag-eval groups mirror analytics `$groups` so per-organization and per-project
- // rollouts evaluate against the same entities — see `buildMCPAnalyticsGroups`.
- const flagAnalyticsContext = await this.getAnalyticsContextSafe(context)
- const flagGroups = flagAnalyticsContext ? buildMCPAnalyticsGroups(flagAnalyticsContext) : undefined
- const toolFlagsPromise = this.resolveToolFeatureFlags(clientVersion, flagGroups)
-
- const [flagVersion, toolFeatureFlags, singleExecFlagOn, _apiKey] = await Promise.all([
- flagPromise,
- toolFlagsPromise,
- singleExecPromise,
- context.stateManager.getApiKey(),
- ])
- _lap('flags + getApiKey')
-
- const oauthClientName = (await this.cache.get('clientName')) || undefined
-
- const clientProfile = new MCPClientProfile({
- clientName: this.mcpClientName,
- clientVersion: this.mcpClientVersion,
- consumer: this.props.mcpConsumer,
- oauthClientName,
- })
-
- const { useSingleExec, version } = this.resolveModeAndVersion({
- mode,
- singleExecFlagOn,
- clientProfile,
- flagVersion,
- clientVersion,
- })
-
- // Fetch group types, metadata, and AI consent in parallel (cache is now seeded)
- const resolvedProjectId = projectId || (await this.cache.get('projectId'))
- const apiKeyScopes = _apiKey?.scopes ?? []
- const [groupTypes, metadata, aiConsentGiven] = await Promise.all([
- resolvedProjectId && hasScope(apiKeyScopes, 'group:read')
- ? context.stateManager.getOrFetchGroupTypes(resolvedProjectId)
- : undefined,
- context.stateManager.getEnvironmentPrompt(),
- context.stateManager.getAiConsentGiven(),
- ])
- _lap('groupTypes + metadata')
-
- // When project ID is provided, both switch tools are removed (project implies org).
- // When only organization ID is provided, only switch-organization is removed.
- const excludeTools: string[] = []
- if (projectId) {
- excludeTools.push('switch-organization', 'switch-project')
- } else if (organizationId) {
- excludeTools.push('switch-organization')
- }
-
- // Resolve tools — use pre-built catalog when available, else fall back to full init
- const allTools = await this.resolveTools(context, {
- features,
- tools,
- version,
- excludeTools,
- readOnly,
- featureFlags: toolFeatureFlags,
- scopes: apiKeyScopes,
- aiConsentGiven: aiConsentGiven ?? undefined,
- })
- _lap(`resolveTools (${allTools.length} tools, catalog=${!!this._warmup?.catalog.warmedUp})`)
-
- if (oauthClientName && this._api) {
- this._api.config.oauthClientName = oauthClientName
- }
-
- const toolInfos = allTools.map((t) => ({
- name: t.name,
- category: getToolDefinition(t.name, version).category,
- }))
- const queryToolInfos: QueryToolInfo[] = allTools
- .filter((t) => t.name.startsWith('query-'))
- .map((t) => {
- const def = getToolDefinition(t.name, version)
- return {
- name: t.name,
- title: def.title,
- ...(def.system_prompt_hint ? { systemPromptHint: def.system_prompt_hint } : {}),
- }
- })
-
- const supportsInstructions = clientProfile.capabilities.supportsInstructions
-
- const instructionsContext = {
- guidelines: _guidelines,
- groupTypes,
- metadata,
- tools: toolInfos,
- queryTools: queryToolInfos,
- featureFlags: toolFeatureFlags,
- }
-
- let instructions = ''
- if (supportsInstructions) {
- if (useSingleExec) {
- instructions = instructionsFormatter.buildExecInstructions(instructionsContext)
- } else if (version === 2) {
- instructions = instructionsFormatter.buildV2Instructions(instructionsContext)
- } else {
- instructions = instructionsFormatter.buildV1Instructions(metadata)
- }
- }
-
- this.server = new McpServer({ name: 'PostHog', version: '1.0.0' }, { instructions })
- _lap('new McpServer + instructions')
-
- // Register prompts and resources — use pre-parsed entries when available
- await registerPrompts(this.server)
- if (this._warmup?.resourceEntries.length) {
- const { registerResourceEntries } = await import('@/resources')
- registerResourceEntries(this.server, this._warmup.resourceEntries)
- } else {
- await registerResources(this.server, context)
- }
- await registerUiAppResources(this.server, context)
- _lap('registerPrompts + registerResources')
-
- // execute-sql is v2-only. Swap its description with the rich SQL prompt.
- if (version === 2) {
- const sqlTool = allTools.find((t) => t.name === 'execute-sql')
- if (sqlTool) {
- sqlTool.description = formatPrompt(EXECUTE_SQL_PROMPT, { guidelines: _guidelines.trim() })
- }
- }
-
- // In single-exec mode, register one "posthog" tool that wraps all tools
- // behind a CLI-like interface. Otherwise, register each tool individually.
- if (useSingleExec) {
- // When the client honors the `instructions` field, env-context is already
- // delivered there — strip it from the command-parameter description.
- const commandReference = instructionsFormatter.buildExecCommandReference(instructionsContext, {
- stripEnvContext: supportsInstructions,
- })
-
- const trackInnerCall: ExecInnerCallTracker = (toolName, properties) => {
- void (async () => {
- const freshContext = await this.getAnalyticsContextSafe(await this.getContext())
- await this.trackEvent(
- AnalyticsEvent.MCP_TOOL_CALL,
- { tool_name: toolName, ...properties },
- freshContext ? { context: freshContext } : undefined
- )
- })()
- }
-
- const execTool = createExecTool(
- allTools,
- context,
- instructionsFormatter.buildExecToolDescription(),
- commandReference,
- this.props.mcpConsumer,
- trackInnerCall
- )
- const typedExecTool = execTool as Tool<z.ZodObject>
- this.registerTool(typedExecTool, async (params) => typedExecTool.handler(context, params))
- } else {
- for (const tool of allTools) {
- const typedTool = tool as Tool<z.ZodObject>
- this.registerTool(typedTool, async (params) => typedTool.handler(context, params))
- }
- }
-
- const mcpAnalyticsIdentity = {
- getDistinctId: () => this.getDistinctId(),
- getSessionUuid: async () =>
- this.props.sessionId ? this.sessionManager.getSessionUuid(this.props.sessionId) : undefined,
- getMcpClientName: async () => this.mcpClientName,
- getMcpClientVersion: async () => this.mcpClientVersion,
- getMcpProtocolVersion: async () => this.mcpProtocolVersion,
- // Prefer the cached region (set on init after detection) so we don't miss it
- // when the inbound request didn't include the `region` hint.
- getRegion: async () => (await this.cache.get('region')) ?? this.props.region,
- getAnalyticsContext: async () => this.getAnalyticsContextSafe(await this.getContext()),
- getClientUserAgent: async () => this.props.clientUserAgent,
- // Server-resolved version (may differ from the client-reported one because of
- // the `mcp-version-2` feature flag), so observability events line up with ours.
- getMcpVersion: async () => version,
- getOAuthClientName: async () => (await this.cache.get('clientName')) || undefined,
- getReadOnly: async () => readOnly,
- getTransport: async () => this.props.transport,
- getMcpConsumer: async () => this.props.mcpConsumer,
- getMcpMode: async () => this.mcpMode,
- getMcpSessionId: async () => this.props.mcpSessionId,
- getMcpConversationId: async () => this.props.mcpConversationId,
- }
-
- // In single-exec mode every event's `$mcp_tool_name` is `exec`, so the
- // SDK's `$mcp_tool_description` would be the dispatcher's static text on
- // every call. Resolve the inner tool the agent was actually invoking
- // from the command and surface its name + description as
- // `$mcp_exec_tool_call_name` / `$mcp_exec_tool_call_description`.
- const resolveExecInnerToolCall = useSingleExec ? createExecInnerToolCallResolver(allTools) : undefined
-
- // In single-exec mode the SDK's $mcp_listed_tool_names collapses to
- // just `exec`, so we can't compute "advertised but never called"
- // (zombie tools) from SDK data alone. Pass the inner-tool catalog
- // here so analytics can attach it as $mcp_exec_inner_tool_names on
- // mcp_tools_list events. Dashboards can then diff it against
- // $mcp_exec_tool_call_name from mcp_tool_call.
- const execInnerToolNames = useSingleExec ? allTools.map((t) => t.name) : undefined
-
- _lap('registerTools')
-
- const initResult = await initMcpAnalytics(this.server, mcpAnalyticsIdentity, {
- contextEnabled: true,
- resolveExecInnerToolCall,
- execInnerToolNames,
- // `get_more_tools` only earns its keep outside single-exec mode — there
- // it lets the model report a gap in our discrete tool catalog. In
- // single-exec mode the wrapper handles every call, so the missing-tool
- // signal has nothing to map to and the extra slot is pure noise.
- reportMissingEnabled: !useSingleExec,
- })
-
- Object.assign(this.props, {
- mcpAnalyticsInitAction: initResult.action,
- ...(initResult.action === 'skipped' ? { mcpAnalyticsInitReason: initResult.reason } : {}),
- ...(initResult.action === 'failed'
- ? {
- mcpAnalyticsInitErrorName: initResult.errorName,
- mcpAnalyticsInitErrorMessage: initResult.errorMessage,
- }
- : {}),
- } as HonoRequestProperties)
-
- const initDurationMs = this.props.requestStartTime ? Date.now() - this.props.requestStartTime : undefined
-
- // Resolve analytics context from the already-primed cache (getEnvironmentPrompt
- // above populated `cachedProject`/`cachedOrg`), so this is effectively free here.
- const analyticsContext = await this.getAnalyticsContextSafe(context)
-
- _lap('initMcpAnalytics')
-
- void this.trackEvent(
- AnalyticsEvent.MCP_INIT,
- {
- tool_count: allTools.length,
- has_organization_id: !!organizationId,
- has_project_id: !!projectId,
- read_only: !!readOnly,
- via_sse_redirect: !!this.props.viaSseRedirect,
- ...(mode ? { mcp_mode_explicit: mode } : {}),
- ...(initDurationMs !== undefined ? { init_duration_ms: initDurationMs } : {}),
- },
- analyticsContext ? { context: analyticsContext } : undefined
- )
- }
-
- /**
- * Decide single-exec mode and the protocol version for this connection,
- * stashing both on the instance so `trackEvent` and observability identity
- * provider can emit `mcp_mode` / `mcp_version` on every downstream event
- * without re-deriving them.
- */
- private resolveModeAndVersion(args: {
- mode: McpMode | undefined
- singleExecFlagOn: boolean
- clientProfile: MCPClientProfile
- flagVersion: number | undefined
- clientVersion: number | undefined
- }): { useSingleExec: boolean; version: number } {
- const { mode, singleExecFlagOn, clientProfile, flagVersion, clientVersion } = args
- const useSingleExec =
- mode === 'cli' ||
- (mode !== 'tools' &&
- singleExecFlagOn &&
- (clientProfile.isCodingAgent() ||
- clientProfile.isPostHogCodeConsumer() ||
- clientProfile.isVibeCodingClient()))
- const version = useSingleExec ? 2 : (flagVersion ?? clientVersion ?? 1)
-
- this.mcpMode = useSingleExec ? 'cli' : 'tools'
- this.mcpVersion = version
-
- return { useSingleExec, version }
- }
-
- private async resolveTools(context: Context, options: ToolCatalogFilterOptions): Promise<Tool<z.ZodObject>[]> {
- if (this._warmup?.catalog.warmedUp) {
- return this._warmup.catalog.getFilteredTools(options) as Tool<z.ZodObject>[]
- }
- const { getToolsFromContext } = await import('@/tools')
- return (await getToolsFromContext(context, options)) as Tool<z.ZodObject>[]
- }
-
- private async resolveVersionFlag(): Promise<number | undefined> {
- try {
- const distinctId = await this.getDistinctId()
- return (await isFeatureFlagEnabled('mcp-version-2', distinctId)) ? 2 : undefined
- } catch {
- return undefined
- }
- }
-
- private async resolveSingleExecFlag(): Promise<boolean> {
- try {
- const distinctId = await this.getDistinctId()
- return !!(await isFeatureFlagEnabled('mcp-single-exec-tool', distinctId))
- } catch {
- return false
- }
- }
-
- private async resolveToolFeatureFlags(
- version?: number,
- groups?: FlagGroups
- ): Promise<Record<string, boolean> | undefined> {
- try {
- const { getRequiredFeatureFlags } = await import('@/tools/toolDefinitions')
- const flagKeys = getRequiredFeatureFlags(version)
- if (flagKeys.length === 0) {
- return undefined
- }
- const distinctId = await this.getDistinctId()
- return await evaluateFeatureFlags(flagKeys, distinctId, groups)
- } catch {
- return undefined
- }
- }
-}
diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.ts
new file mode 100644
index 000000000000..3f1b0f0fc661
--- /dev/null
+++ b/services/mcp/src/hono/request-context.ts
@@ -0,0 +1,197 @@
+import { ApiClient } from '@/api/client'
+import { wrapError } from '@/lib/errors'
+import {
+ AnalyticsEvent,
+ buildMCPAnalyticsGroups,
+ buildMCPContextProperties,
+ type MCPAnalyticsContext,
+} from '@/lib/posthog/analytics'
+import { getPostHogClient } from '@/lib/posthog'
+import type { RequestProperties } from '@/lib/request-properties'
+import { SessionManager } from '@/lib/SessionManager'
+import { StateManager } from '@/lib/StateManager'
+import type { Context, Env, State } from '@/tools/types'
+
+import { RedisCache, type RedisLike } from './cache/RedisCache'
+import { getCustomApiBaseUrl } from './constants'
+
+export class RequestContext {
+ private cacheInstance: RedisCache<State> | undefined
+ private apiInstance: ApiClient | undefined
+ private sessionManagerInstance: SessionManager | undefined
+ private distinctIdPromise: Promise<string> | undefined
+ private readonly redis: RedisLike
+ private readonly env: Env
+ private readonly props: RequestProperties
+
+ constructor(redis: RedisLike, env: Env, props: RequestProperties) {
+ this.redis = redis
+ this.env = env
+ this.props = props
+ }
+
+ get cache(): RedisCache<State> {
+ if (!this.props.userHash) {
+ throw new Error('User hash is required to use the cache')
+ }
+ if (!this.cacheInstance) {
+ this.cacheInstance = new RedisCache<State>(this.props.userHash, this.redis)
+ }
+ return this.cacheInstance
+ }
+
+ private async api(): Promise<ApiClient> {
+ if (!this.apiInstance) {
+ const customApiBaseUrl = getCustomApiBaseUrl()
+ let baseUrl: string
+ if (customApiBaseUrl) {
+ baseUrl = customApiBaseUrl
+ } else if (process.env.NODE_ENV === 'production') {
+ throw new Error(
+ 'POSTHOG_API_BASE_URL must be set in production — Hono deployments are regional and do not auto-detect.'
+ )
+ } else {
+ baseUrl = 'http://localhost:8010'
+ }
+ this.apiInstance = new ApiClient({
+ apiToken: this.props.apiToken,
+ baseUrl,
+ clientUserAgent: this.props.clientUserAgent,
+ mcpClientName: this.props.mcpClientName,
+ mcpClientVersion: this.props.mcpClientVersion,
+ mcpProtocolVersion: this.props.mcpProtocolVersion,
+ mcpConsumer: this.props.mcpConsumer,
+ })
+ }
+ return this.apiInstance
+ }
+
+ get sessionManager(): SessionManager {
+ if (!this.sessionManagerInstance) {
+ this.sessionManagerInstance = new SessionManager(this.cache)
+ }
+ return this.sessionManagerInstance
+ }
+
+ async getSessionUuid(sessionId: string | undefined): Promise<string | undefined> {
+ if (!sessionId) {return undefined}
+ return this.sessionManager.getSessionUuid(sessionId)
+ }
+
+ getDistinctId(): Promise<string> {
+ if (!this.distinctIdPromise) {
+ this.distinctIdPromise = this.resolveDistinctId()
+ }
+ return this.distinctIdPromise
+ }
+
+ private async resolveDistinctId(): Promise<string> {
+ const cached = await this.cache.get('distinctId')
+ if (cached) {return cached}
+ const userResult = await (await this.api()).users().me()
+ if (!userResult.success) {
+ throw wrapError(`Failed to get user: ${userResult.error.message}`, userResult.error)
+ }
+ await this.cache.set('distinctId', userResult.data.distinct_id)
+ return userResult.data.distinct_id as string
+ }
+
+ async getContext(): Promise<Context> {
+ const api = await this.api()
+ const stateManager = new StateManager(this.cache, api)
+ const partialContext: Omit<Context, 'trackEvent'> = {
+ api,
+ cache: this.cache,
+ env: this.env,
+ stateManager,
+ sessionManager: this.sessionManager,
+ getDistinctId: () => this.getDistinctId(),
+ }
+ const trackEvent: Context['trackEvent'] = async (event, properties = {}) => {
+ const analyticsContext = await this.getAnalyticsContextSafe(partialContext)
+ const distinctId = await this.getDistinctId()
+ await this.trackEvent(event, properties, analyticsContext, undefined, distinctId, this.props)
+ }
+ return { ...partialContext, trackEvent }
+ }
+
+ async getAnalyticsContextSafe(
+ context: Pick<Context, 'stateManager'>
+ ): Promise<MCPAnalyticsContext | undefined> {
+ try {
+ return await context.stateManager.getAnalyticsContext()
+ } catch {
+ return undefined
+ }
+ }
+
+ async trackContextSwitchEvent(
+ toolName: string,
+ context: Context,
+ previousContext: MCPAnalyticsContext | undefined
+ ): Promise<void> {
+ const resolvedContext = await this.getAnalyticsContextSafe(context)
+ if (!resolvedContext) {return}
+
+ const event =
+ toolName === 'switch-project'
+ ? AnalyticsEvent.MCP_PROJECT_SWITCHED
+ : toolName === 'switch-organization'
+ ? AnalyticsEvent.MCP_ORGANIZATION_SWITCHED
+ : undefined
+ if (!event) {return}
+
+ const distinctId = await this.getDistinctId()
+ await this.trackEvent(event, {}, resolvedContext, previousContext, distinctId, this.props)
+ }
+
+ buildClientProperties(props?: RequestProperties): Record<string, unknown> {
+ const p = props ?? this.props
+ return {
+ mcp_runtime: 'hono',
+ ...(p.mcpClientName ? { mcp_client_name: p.mcpClientName } : {}),
+ ...(p.mcpClientVersion ? { mcp_client_version: p.mcpClientVersion } : {}),
+ ...(p.mcpProtocolVersion ? { mcp_protocol_version: p.mcpProtocolVersion } : {}),
+ ...(p.mcpConsumer ? { mcp_consumer: p.mcpConsumer } : {}),
+ ...(p.transport ? { mcp_transport: p.transport } : {}),
+ }
+ }
+
+ async trackEvent(
+ event: AnalyticsEvent,
+ properties: Record<string, unknown>,
+ analyticsContext?: MCPAnalyticsContext,
+ previousContext?: MCPAnalyticsContext,
+ distinctId?: string,
+ props?: RequestProperties
+ ): Promise<void> {
+ try {
+ const resolvedDistinctId = distinctId ?? (await this.getDistinctId())
+ const resolvedProps = props ?? this.props
+ const clientName = await this.cache.get('clientName')
+ const contextProperties = analyticsContext ? buildMCPContextProperties(analyticsContext) : {}
+ const previousContextProperties = previousContext
+ ? buildMCPContextProperties(previousContext, { prefix: 'previous_' })
+ : {}
+ const groups = analyticsContext ? buildMCPAnalyticsGroups(analyticsContext) : {}
+
+ getPostHogClient().capture({
+ distinctId: resolvedDistinctId,
+ event,
+ ...(Object.keys(groups).length > 0 ? { groups } : {}),
+ properties: {
+ ...this.buildClientProperties(resolvedProps),
+ ...(resolvedProps.sessionId
+ ? { $session_id: await this.getSessionUuid(resolvedProps.sessionId) }
+ : {}),
+ ...(clientName ? { mcp_oauth_client_name: clientName } : {}),
+ ...contextProperties,
+ ...previousContextProperties,
+ ...properties,
+ },
+ })
+ } catch {
+ // skip
+ }
+ }
+}
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
new file mode 100644
index 000000000000..4a90637c8d7d
--- /dev/null
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -0,0 +1,159 @@
+import { MCPClientProfile } from '@/lib/client-detection'
+import { buildMCPAnalyticsGroups } from '@/lib/posthog/analytics'
+import { evaluateFeatureFlags, type FlagGroups } from '@/lib/posthog/flags'
+import type { RequestProperties } from '@/lib/request-properties'
+import type { McpMode } from '@/lib/utils'
+import { getRequiredFeatureFlags } from '@/tools/toolDefinitions'
+import type { Context, Tool, Env, ZodObjectAny } from '@/tools/types'
+
+import type { RedisLike } from './cache/RedisCache'
+import { RequestContext } from './request-context'
+import type { ToolCatalog } from './tool-catalog'
+
+// ─── Per-request resolved state ───
+
+export interface ResolvedState {
+ reqCtx: RequestContext
+ context: Context
+ version: number
+ useSingleExec: boolean
+ toolFeatureFlags: Record<string, boolean> | undefined
+ apiKeyScopes: string[]
+ clientProfile: MCPClientProfile
+ allTools: Tool<ZodObjectAny>[]
+ distinctId: string
+}
+
+// ─── Pure helpers ───
+
+export function resolveModeAndVersion(args: {
+ mode: McpMode | undefined
+ singleExecFlagOn: boolean
+ clientProfile: MCPClientProfile
+ flagVersion: number | undefined
+ clientVersion: number | undefined
+}): { useSingleExec: boolean; version: number } {
+ const { mode, singleExecFlagOn, clientProfile, flagVersion, clientVersion } = args
+ const useSingleExec =
+ mode === 'cli' ||
+ (mode !== 'tools' &&
+ singleExecFlagOn &&
+ (clientProfile.isCodingAgent() ||
+ clientProfile.isPostHogCodeConsumer() ||
+ clientProfile.isVibeCodingClient()))
+ const version = useSingleExec ? 2 : (flagVersion ?? clientVersion ?? 1)
+ return { useSingleExec, version }
+}
+
+// ─── Resolver ───
+
+const SYSTEM_FLAGS = ['mcp-version-2', 'mcp-single-exec-tool'] as const
+
+export class RequestStateResolver {
+ private readonly catalog: ToolCatalog
+ private readonly redis: RedisLike
+ private readonly env: Env
+
+ constructor(catalog: ToolCatalog, redis: RedisLike, env: Env) {
+ this.catalog = catalog
+ this.redis = redis
+ this.env = env
+ }
+
+ async resolve(props: RequestProperties): Promise<ResolvedState> {
+ const reqCtx = new RequestContext(this.redis, this.env, props)
+ const context = await reqCtx.getContext()
+
+ const { features, tools, version: clientVersion, organizationId, projectId, readOnly, mode } = props
+
+ if (organizationId) {await reqCtx.cache.set('orgId', organizationId)}
+ if (projectId) {await reqCtx.cache.set('projectId', projectId)}
+
+ let cachedProjectId = projectId || (await reqCtx.cache.get('projectId'))
+ if (!cachedProjectId) {
+ await context.stateManager.setDefaultOrganizationAndProject()
+ cachedProjectId = (await reqCtx.cache.get('projectId')) ?? undefined
+ }
+
+ const toolFlagKeys = getRequiredFeatureFlags(clientVersion)
+ const allFlagKeys = [...SYSTEM_FLAGS, ...toolFlagKeys]
+
+ const flagAnalyticsContext = await reqCtx.getAnalyticsContextSafe(context)
+ const flagGroups = flagAnalyticsContext ? buildMCPAnalyticsGroups(flagAnalyticsContext) : undefined
+
+ const [allFlags, _apiKey, distinctId] = await Promise.all([
+ this.resolveAllFlags(reqCtx, allFlagKeys, flagGroups),
+ context.stateManager.getApiKey(),
+ reqCtx.getDistinctId(),
+ ])
+
+ const flagVersion = allFlags['mcp-version-2'] ? 2 : undefined
+ const singleExecFlagOn = !!allFlags['mcp-single-exec-tool']
+ const toolFeatureFlags = toolFlagKeys.length > 0
+ ? Object.fromEntries(toolFlagKeys.map((k) => [k, !!allFlags[k]]))
+ : undefined
+
+ const oauthClientName = (await reqCtx.cache.get('clientName')) || undefined
+ const clientProfile = new MCPClientProfile({
+ clientName: props.mcpClientName,
+ clientVersion: props.mcpClientVersion,
+ consumer: props.mcpConsumer,
+ oauthClientName,
+ })
+
+ const { useSingleExec, version } = resolveModeAndVersion({
+ mode,
+ singleExecFlagOn,
+ clientProfile,
+ flagVersion,
+ clientVersion,
+ })
+
+ const apiKeyScopes = _apiKey?.scopes ?? []
+ const aiConsentGiven = await context.stateManager.getAiConsentGiven()
+
+ const excludeTools: string[] = []
+ if (projectId) {
+ excludeTools.push('switch-organization', 'switch-project')
+ } else if (organizationId) {
+ excludeTools.push('switch-organization')
+ }
+
+ const allTools = this.catalog.getFilteredTools({
+ features,
+ tools,
+ version,
+ excludeTools,
+ readOnly,
+ featureFlags: toolFeatureFlags,
+ scopes: apiKeyScopes,
+ aiConsentGiven: aiConsentGiven ?? undefined,
+ })
+
+ return {
+ reqCtx,
+ context,
+ version,
+ useSingleExec,
+ toolFeatureFlags,
+ apiKeyScopes,
+ clientProfile,
+ allTools,
+ distinctId,
+ }
+ }
+
+ private async resolveAllFlags(
+ reqCtx: RequestContext,
+ flagKeys: string[],
+ groups?: FlagGroups
+ ): Promise<Record<string, boolean>> {
+ if (flagKeys.length === 0) {return {}}
+ try {
+ const distinctId = await reqCtx.getDistinctId()
+ return await evaluateFeatureFlags(flagKeys, distinctId, groups)
+ } catch {
+ return {}
+ }
+ }
+}
diff --git a/services/mcp/src/hono/resource-catalog.ts b/services/mcp/src/hono/resource-catalog.ts
new file mode 100644
index 000000000000..7e38eba6316f
--- /dev/null
+++ b/services/mcp/src/hono/resource-catalog.ts
@@ -0,0 +1,142 @@
+import { RESOURCE_MIME_TYPE } from '@modelcontextprotocol/ext-apps/server'
+import type { GetPromptResult, ListPromptsResult, ListResourcesResult, Prompt, ReadResourceResult, Resource, TextResourceContents } from '@modelcontextprotocol/sdk/types.js'
+
+import { fetchContextMillResources, filterValidEntries, loadManifestFromArchive, clearResourceCache } from '@/resources/internals'
+import { getPromptsFromManifest } from '@/resources'
+import { UI_APPS } from '@/resources/ui-apps.generated'
+import { buildAppStubHtml } from '@/resources/ui-apps'
+import type { ContextMillResource } from '@/resources/manifest-types'
+import type { Env } from '@/tools/types'
+
+export class ResourceCatalog {
+ private readonly env: Env
+
+ private resources: Resource[] = []
+ private resourcesByUri = new Map<string, TextResourceContents>()
+ private prompts: Prompt[] = []
+ private promptsByName = new Map<string, GetPromptResult>()
+ private uiAppResources: Resource[] = []
+ private uiAppReadEntries = new Map<string, TextResourceContents>()
+ private allResources: Resource[] = []
+ private contextMillData: readonly ContextMillResource[] = []
+
+ constructor(env: Env) {
+ this.env = env
+ }
+
+ get contextMillEntries(): readonly ContextMillResource[] {
+ return this.contextMillData
+ }
+
+ async warmup(): Promise<void> {
+ await Promise.all([this.warmupResources(), this.warmupUiApps()])
+ this.allResources = [...this.resources, ...this.uiAppResources]
+ }
+
+ getResourcesList(): ListResourcesResult {
+ return { resources: this.allResources }
+ }
+
+ readResource(params: Record<string, unknown> | undefined): ReadResourceResult {
+ const uri = (params?.uri as string) ?? ''
+ const entry = this.resourcesByUri.get(uri) ?? this.uiAppReadEntries.get(uri)
+ if (!entry) {
+ return { contents: [] }
+ }
+ return {
+ contents: [
+ {
+ uri: entry.uri,
+ mimeType: entry.mimeType,
+ text: entry.text,
+ ...(entry._meta ? { _meta: entry._meta } : {}),
+ },
+ ],
+ }
+ }
+
+ getPromptsList(): ListPromptsResult {
+ return { prompts: this.prompts }
+ }
+
+ getPrompt(params: Record<string, unknown> | undefined): GetPromptResult {
+ const name = (params?.name as string) ?? ''
+ const entry = this.promptsByName.get(name)
+ if (!entry) {
+ return { messages: [] }
+ }
+ return { messages: entry.messages }
+ }
+
+ private async warmupResources(): Promise<void> {
+ try {
+ const archive = await fetchContextMillResources()
+ const manifest = loadManifestFromArchive(archive)
+ this.contextMillData = filterValidEntries(manifest.resources, archive)
+ clearResourceCache()
+
+ for (const entry of this.contextMillEntries) {
+ this.resources.push({
+ name: entry.name,
+ uri: entry.uri,
+ mimeType: entry.resource.mimeType,
+ description: entry.resource.description,
+ })
+ this.resourcesByUri.set(entry.uri, {
+ uri: entry.uri,
+ mimeType: entry.resource.mimeType,
+ text: entry.resource.text,
+ })
+ }
+ } catch (error) {
+ console.error('[ResourceCatalog] Failed to pre-load context-mill resources:', error)
+ }
+
+ try {
+ const manifestPrompts = await getPromptsFromManifest()
+ for (const prompt of manifestPrompts) {
+ this.prompts.push({
+ name: prompt.name,
+ title: prompt.title,
+ description: prompt.description,
+ })
+ this.promptsByName.set(prompt.name, { messages: prompt.messages as GetPromptResult['messages'] })
+ }
+ } catch (error) {
+ console.error('[ResourceCatalog] Failed to pre-load prompts:', error)
+ }
+ }
+
+ private async warmupUiApps(): Promise<void> {
+ const baseUrl = this.env.MCP_APPS_BASE_URL
+ if (!baseUrl) {return}
+
+ const analyticsBaseUrl = this.env.POSTHOG_MCP_APPS_ANALYTICS_BASE_URL
+
+ for (const app of UI_APPS) {
+ const html = buildAppStubHtml(app.appDir, baseUrl)
+
+ const uiMetadata: Record<string, unknown> = {}
+ const resourceDomains = [baseUrl]
+ const connectDomains: string[] = []
+ if (analyticsBaseUrl) {
+ connectDomains.push(analyticsBaseUrl)
+ resourceDomains.push(analyticsBaseUrl)
+ }
+ uiMetadata.csp = { connectDomains, resourceDomains }
+
+ this.uiAppResources.push({
+ name: app.name,
+ uri: app.uri,
+ mimeType: RESOURCE_MIME_TYPE,
+ description: app.description,
+ })
+ this.uiAppReadEntries.set(app.uri, {
+ uri: app.uri,
+ mimeType: RESOURCE_MIME_TYPE,
+ text: html,
+ _meta: { ui: uiMetadata },
+ })
+ }
+ }
+}
diff --git a/services/mcp/src/hono/streamable-handler.ts b/services/mcp/src/hono/streamable-handler.ts
index c4b262e32eee..027ab584e624 100644
--- a/services/mcp/src/hono/streamable-handler.ts
+++ b/services/mcp/src/hono/streamable-handler.ts
@@ -1,43 +1,19 @@
-import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'
-
-import type { ContextMillResource } from '@/resources/manifest-types'
-
import type { Lifecycle } from './app'
import type { RedisLike } from './cache/RedisCache'
-import { HonoMcpServer } from './mcp-server'
-import { authenticateAndParse, handleCatchError, passThrough } from './request-utils'
+import { McpDispatcher } from './dispatcher'
+import { authenticateAndParse, handleCatchError } from './request-utils'
import { ToolCatalog } from './tool-catalog'
import type { HonoCtx } from './types'
export class StreamableMcpHandler {
- private readonly catalog = new ToolCatalog()
- private _resourceEntries: readonly ContextMillResource[] = []
+ private readonly dispatcher: McpDispatcher
- constructor(
- private readonly redis: RedisLike,
- private readonly lifecycle: Lifecycle
- ) {}
-
- get resourceEntries(): readonly ContextMillResource[] {
- return this._resourceEntries
+ constructor(redis: RedisLike, private readonly lifecycle: Lifecycle) {
+ this.dispatcher = new McpDispatcher(new ToolCatalog(), redis)
}
async warmup(): Promise<void> {
- await Promise.all([this.catalog.warmup(), this._warmupResources()])
- }
-
- private async _warmupResources(): Promise<void> {
- try {
- const { fetchContextMillResources, filterValidEntries, loadManifestFromArchive, clearResourceCache } =
- await import('@/resources/internals')
- const archive = await fetchContextMillResources()
- const manifest = loadManifestFromArchive(archive)
- this._resourceEntries = filterValidEntries(manifest.resources, archive)
- clearResourceCache()
- } catch (error) {
- console.error('[StreamableMcpHandler] Failed to pre-load context-mill resources:', error)
- this._resourceEntries = []
- }
+ await this.dispatcher.warmup()
}
fetch = async (c: HonoCtx): Promise<Response> => {
@@ -53,20 +29,10 @@ export class StreamableMcpHandler {
return auth.error
}
- let mcpServer: HonoMcpServer | undefined
try {
- mcpServer = new HonoMcpServer(this.redis, auth.props, {
- catalog: this.catalog,
- resourceEntries: this._resourceEntries,
- })
- await mcpServer.init()
- const transport = new WebStandardStreamableHTTPServerTransport({ enableJsonResponse: true })
- await mcpServer.server.connect(transport)
- return passThrough(await transport.handleRequest(c.req.raw))
+ return await this.dispatcher.handleRequest(c.req.raw, auth.props)
} catch (error) {
return handleCatchError(error, auth.props)
- } finally {
- await mcpServer?.server.close().catch(() => {})
}
}
}
diff --git a/services/mcp/src/hono/tool-catalog.ts b/services/mcp/src/hono/tool-catalog.ts
index a210659cd740..d233f0127631 100644
--- a/services/mcp/src/hono/tool-catalog.ts
+++ b/services/mcp/src/hono/tool-catalog.ts
@@ -1,3 +1,6 @@
+import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'
+import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js'
+
import { hasScopes } from '@/lib/api'
import {
type ToolDefinition,
@@ -7,6 +10,8 @@ import {
} from '@/tools/toolDefinitions'
import type { Tool, ToolBase, ZodObjectAny } from '@/tools/types'
+import type { Tool as McpTool } from '@modelcontextprotocol/sdk/types.js'
+
interface PreBuiltTool {
base: ToolBase<ZodObjectAny>
definitions: {
@@ -20,8 +25,14 @@ export interface ToolCatalogFilterOptions extends ToolFilterOptions {
excludeTools?: string[]
}
+export type { PreBuiltTool }
+
+const EMPTY_OBJECT_JSON_SCHEMA = { type: 'object' as const, properties: {} }
+
export class ToolCatalog {
private _preBuilt: Map<string, PreBuiltTool> = new Map()
+ private _entries: McpTool[] = []
+ private _entriesByName = new Map<string, McpTool>()
private _warmedUp = false
get warmedUp(): boolean {
@@ -59,12 +70,68 @@ export class ToolCatalog {
})
}
+ this._buildEntries()
+
this._warmedUp = true
console.info(
`[ToolCatalog] warmup complete: ${this._preBuilt.size} tools in ${(performance.now() - start).toFixed(0)}ms`
)
}
+ private _buildEntries(): void {
+ this._entries = []
+ this._entriesByName = new Map()
+
+ for (const [name, preBuilt] of this._preBuilt) {
+ const def = preBuilt.definitions.v1 ?? preBuilt.definitions.v2
+ if (!def) {continue}
+
+ let jsonSchema: Record<string, unknown>
+ try {
+ jsonSchema = toJsonSchemaCompat(preBuilt.base.schema, { strictUnions: true }) as Record<string, unknown>
+ delete jsonSchema['$schema']
+ delete jsonSchema['additionalProperties']
+ } catch {
+ jsonSchema = EMPTY_OBJECT_JSON_SCHEMA
+ }
+
+ let meta = preBuilt.base._meta as Record<string, unknown> | undefined
+ if (meta?.ui && typeof meta.ui === 'object' && 'resourceUri' in meta.ui && !meta[RESOURCE_URI_META_KEY]) {
+ meta = {
+ ...meta,
+ [RESOURCE_URI_META_KEY]: (meta.ui as Record<string, unknown>).resourceUri,
+ }
+ }
+
+ const entry: McpTool = {
+ name,
+ title: def.title,
+ description: def.description,
+ inputSchema: jsonSchema as McpTool['inputSchema'],
+ annotations: def.annotations as McpTool['annotations'],
+ ...(meta ? { _meta: meta } : {}),
+ }
+ this._entries.push(entry)
+ this._entriesByName.set(name, entry)
+ }
+ }
+
+ getAllPreBuilt(): ReadonlyMap<string, PreBuiltTool> {
+ return this._preBuilt
+ }
+
+ getToolByName(name: string): PreBuiltTool | undefined {
+ return this._preBuilt.get(name)
+ }
+
+ getPreBuiltEntries(): McpTool[] {
+ return this._entries
+ }
+
+ getPreBuiltEntry(name: string): McpTool | undefined {
+ return this._entriesByName.get(name)
+ }
+
getFilteredTools(options: ToolCatalogFilterOptions): Tool<ZodObjectAny>[] {
const { scopes = [], excludeTools = [], ...filterOptions } = options
const allowedToolNames = getToolsForFeatures(filterOptions).filter((name) => !excludeTools.includes(name))
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
new file mode 100644
index 000000000000..8a7683475454
--- /dev/null
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -0,0 +1,183 @@
+import type { ListToolsResult } from '@modelcontextprotocol/sdk/types.js'
+
+import { buildToolResultPayload, isToolCallPayload } from '@/lib/build-tool-result'
+import { handleToolError } from '@/lib/errors'
+import { AnalyticsEvent } from '@/lib/posthog/analytics'
+import type { RequestProperties } from '@/lib/request-properties'
+import { createExecTool, type ExecInnerCallTracker } from '@/tools/exec'
+import type { Context, ZodObjectAny } from '@/tools/types'
+
+import { trackToolCall } from './analytics'
+import type { InstructionsBuilder } from './instructions'
+import { toolCallDurationSeconds, toolCallsTotal } from './metrics'
+import type { ResolvedState } from './request-state-resolver'
+import type { ToolCatalog } from './tool-catalog'
+
+interface ResolvedTool {
+ name: string
+ schema: ZodObjectAny
+ handler: (ctx: Context, args: unknown) => Promise<unknown>
+ _meta?: { ui?: { resourceUri?: string }; [key: string]: unknown } | undefined
+}
+
+export class ToolExecutor {
+ private readonly catalog: ToolCatalog
+ private readonly instructionsBuilder: InstructionsBuilder
+
+ constructor(catalog: ToolCatalog, instructionsBuilder: InstructionsBuilder) {
+ this.catalog = catalog
+ this.instructionsBuilder = instructionsBuilder
+ }
+
+ async handleToolsList(state: ResolvedState, props: RequestProperties): Promise<ListToolsResult> {
+ if (state.useSingleExec) {
+ return { tools: [this.instructionsBuilder.buildExecToolEntry(state, props)] }
+ }
+
+ const nameSet = new Set(state.allTools.map((t) => t.name))
+ let filteredTools = this.catalog.getPreBuiltEntries().filter((e) => nameSet.has(e.name))
+
+ if (state.version === 2) {
+ filteredTools = filteredTools.map((entry) => {
+ if (entry.name === 'execute-sql') {
+ return { ...entry, description: this.instructionsBuilder.formatExecuteSqlDescription() }
+ }
+ return entry
+ })
+ }
+
+ return { tools: filteredTools }
+ }
+
+ async handleToolCall(
+ params: Record<string, unknown> | undefined,
+ props: RequestProperties,
+ state: ResolvedState
+ ): Promise<unknown> {
+ const toolName = params?.name as string
+ if (!toolName) {
+ return { content: [{ type: 'text', text: 'Missing tool name' }], isError: true }
+ }
+
+ if (state.useSingleExec && toolName === 'exec') {
+ return this.callTool(this.resolveExecTool(state, props), params, props, state)
+ }
+
+ if (!state.allTools.some((t) => t.name === toolName)) {
+ toolCallsTotal.inc({ tool: toolName, status: 'error' })
+ return { content: [{ type: 'text', text: `Tool ${toolName} not found` }], isError: true }
+ }
+
+ const preBuilt = this.catalog.getToolByName(toolName)
+ if (!preBuilt) {
+ toolCallsTotal.inc({ tool: toolName, status: 'error' })
+ return { content: [{ type: 'text', text: `Tool ${toolName} not found` }], isError: true }
+ }
+
+ return this.callTool(
+ {
+ name: toolName,
+ schema: preBuilt.base.schema,
+ handler: (ctx, args) => preBuilt.base.handler(ctx, args),
+ _meta: preBuilt.base._meta,
+ },
+ params,
+ props,
+ state
+ )
+ }
+
+ private async callTool(
+ tool: ResolvedTool,
+ params: Record<string, unknown> | undefined,
+ props: RequestProperties,
+ state: ResolvedState
+ ): Promise<unknown> {
+ const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>
+ const validation = tool.schema.safeParse(toolArgs)
+ if (!validation.success) {
+ toolCallsTotal.inc({ tool: tool.name, status: 'validation_error' })
+ return { content: [{ type: 'text', text: `Invalid input: ${validation.error.message}` }], isError: true }
+ }
+
+ const stop = toolCallDurationSeconds.startTimer({ tool: tool.name })
+ const startMs = Date.now()
+
+ try {
+ const isContextSwitch = tool.name === 'switch-project' || tool.name === 'switch-organization'
+ const previousContext = isContextSwitch
+ ? await state.reqCtx.getAnalyticsContextSafe(state.context)
+ : undefined
+
+ const handlerResult = await tool.handler(state.context, validation.data)
+
+ if (isContextSwitch) {
+ void state.reqCtx.trackContextSwitchEvent(tool.name, state.context, previousContext)
+ }
+
+ toolCallsTotal.inc({ tool: tool.name, status: 'success' })
+ stop({ status: 'success' })
+
+ void trackToolCall(tool.name, Date.now() - startMs, false, props, state)
+
+ if (isToolCallPayload(handlerResult)) {
+ return handlerResult
+ }
+
+ const hasUiResource = !!tool._meta?.ui?.resourceUri
+ const needsDistinctId = hasUiResource && typeof handlerResult !== 'string'
+ const distinctId = needsDistinctId ? state.distinctId : undefined
+
+ return buildToolResultPayload({
+ handlerResult,
+ toolMeta: tool._meta,
+ toolName: tool.name,
+ params: validation.data,
+ clientName: props.mcpClientName,
+ distinctId,
+ })
+ } catch (error: unknown) {
+ toolCallsTotal.inc({ tool: tool.name, status: 'error' })
+ stop({ status: 'error' })
+
+ void trackToolCall(tool.name, Date.now() - startMs, true, props, state)
+
+ const sessionUuid = await state.reqCtx.getSessionUuid(props.sessionId)
+ return handleToolError(error, tool.name, state.distinctId, sessionUuid)
+ }
+ }
+
+ private resolveExecTool(state: ResolvedState, props: RequestProperties): ResolvedTool {
+ const commandReference = this.instructionsBuilder.buildExecCommandReference(state)
+
+ const trackInnerCall: ExecInnerCallTracker = (toolName, properties) => {
+ void (async () => {
+ const freshContext = await state.reqCtx.getAnalyticsContextSafe(state.context)
+ await state.reqCtx.trackEvent(
+ AnalyticsEvent.MCP_TOOL_CALL,
+ { tool_name: toolName, ...properties },
+ freshContext,
+ undefined,
+ state.distinctId,
+ props
+ )
+ })().catch(() => {})
+ }
+
+ const execTool = createExecTool(
+ state.allTools,
+ state.context,
+ this.instructionsBuilder.buildExecToolDescription(),
+ commandReference,
+ props.mcpConsumer,
+ trackInnerCall
+ )
+
+ return {
+ name: 'exec',
+ schema: execTool.schema,
+ handler: (ctx, args) => execTool.handler(ctx, args as { command: string }),
+ _meta: execTool._meta,
+ }
+ }
+}
diff --git a/services/mcp/src/lib/posthog/analytics.ts b/services/mcp/src/lib/posthog/analytics.ts
index 07a89377fdb9..bcb61ac2792d 100644
--- a/services/mcp/src/lib/posthog/analytics.ts
+++ b/services/mcp/src/lib/posthog/analytics.ts
@@ -139,7 +139,7 @@ async function buildEventTags(identity: IdentityProvider): Promise<Record<string
}
}
-async function buildEventProperties(identity: IdentityProvider): Promise<Record<string, unknown>> {
+export async function buildEventProperties(identity: IdentityProvider): Promise<Record<string, unknown>> {
const [
mcpVersion,
clientUserAgent,
@@ -200,7 +200,7 @@ async function buildEventProperties(identity: IdentityProvider): Promise<Record<
}
}
-function redactSensitiveInformation(text: string): string {
+export function redactSensitiveInformation(text: string): string {
return text.replace(/Bearer\s?[\w\-.]+/g, '<redacted>')
}
diff --git a/services/mcp/src/lib/posthog/flags.ts b/services/mcp/src/lib/posthog/flags.ts
index 853ff9180fa3..6fec1a6cc42d 100644
--- a/services/mcp/src/lib/posthog/flags.ts
+++ b/services/mcp/src/lib/posthog/flags.ts
@@ -14,11 +14,6 @@ export async function isFeatureFlagEnabled(flagKey: string, distinctId: string,
}
}
-/**
- * Evaluate multiple feature flags in parallel for the given user.
- * Returns a map of flag key → boolean. `groups` is forwarded to posthog-node
- * so group-scoped rollouts (e.g. per-organization) evaluate correctly.
- */
export async function evaluateFeatureFlags(
flagKeys: string[],
distinctId: string,
@@ -28,12 +23,12 @@ export async function evaluateFeatureFlags(
return {}
}
- const results = await Promise.all(
- flagKeys.map(async (key) => {
- const enabled = await isFeatureFlagEnabled(key, distinctId, groups)
- return [key, enabled] as const
- })
- )
-
- return Object.fromEntries(results)
+ const client = getPostHogClient()
+ const hasGroups = groups && Object.keys(groups).length > 0
+ const allFlags = await client.getAllFlags(distinctId, { flagKeys, ...(hasGroups ? { groups } : {}) })
+ const result: Record<string, boolean> = {}
+ for (const key of flagKeys) {
+ result[key] = allFlags[key] === true
+ }
+ return result
}
diff --git a/services/mcp/tests/hono/dispatcher-profile.perf.ts b/services/mcp/tests/hono/dispatcher-profile.perf.ts
new file mode 100644
index 000000000000..4a48e2c81c16
--- /dev/null
+++ b/services/mcp/tests/hono/dispatcher-profile.perf.ts
@@ -0,0 +1,410 @@
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/lib/posthog', () => ({
+ getPostHogClient: () => ({
+ capture: vi.fn(),
+ shutdown: () => Promise.resolve(),
+ }),
+}))
+
+vi.mock('@/lib/posthog/flags', () => ({
+ isFeatureFlagEnabled: vi.fn().mockResolvedValue(false),
+ evaluateFeatureFlags: vi.fn().mockResolvedValue({}),
+}))
+
+vi.mock('@/resources/internals', () => ({
+ fetchContextMillResources: vi.fn().mockRejectedValue(new Error('mocked')),
+ filterValidEntries: vi.fn().mockReturnValue([]),
+ loadManifestFromArchive: vi.fn().mockReturnValue({ resources: [] }),
+ clearResourceCache: vi.fn(),
+}))
+
+vi.mock('@/resources', () => ({
+ getPromptsFromManifest: vi.fn().mockResolvedValue([]),
+}))
+
+import type { RequestProperties } from '@/lib/request-properties'
+import { McpDispatcher } from '@/hono/dispatcher'
+import { ToolCatalog } from '@/hono/tool-catalog'
+
+class MockRedis {
+ private store = new Map<string, string>()
+ async get(key: string): Promise<string | null> {
+ return this.store.get(key) ?? null
+ }
+ async set(key: string, value: string): Promise<'OK'> {
+ this.store.set(key, value)
+ return 'OK'
+ }
+ async del(key: string): Promise<number> {
+ return this.store.delete(key) ? 1 : 0
+ }
+ async expire(): Promise<number> {
+ return 1
+ }
+ async ttl(): Promise<number> {
+ return 3600
+ }
+}
+
+const mockUserResponse = {
+ uuid: 'test-uuid',
+ distinct_id: 'test-distinct-id',
+ first_name: 'Test',
+ last_name: 'User',
+ email: '[email protected]',
+}
+
+const mockOrgsResponse = {
+ results: [{ id: 'org-1', name: 'Test Org', slug: 'test' }],
+}
+
+const mockProjectsResponse = {
+ results: [{ id: 1, uuid: 'proj-1', name: 'Test Project', organization: 'org-1' }],
+}
+
+let fetchCallCount = 0
+
+function createMockFetch(): typeof fetch {
+ return async (input: string | URL | Request): Promise<Response> => {
+ fetchCallCount++
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url
+ const path = new URL(url).pathname
+
+ let body: unknown = {}
+ if (path.includes('/api/users/@me')) {body = mockUserResponse}
+ else if (path.includes('/api/organizations')) {body = mockOrgsResponse}
+ else if (path.includes('/api/projects') || path.includes('/api/environments')) {body = mockProjectsResponse}
+ else if (path.includes('/decide')) {body = { featureFlags: {} }}
+
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ })
+ }
+}
+
+const WARM_USER_HASH = 'warm-user-for-profiling'
+
+function makeProps(overrides: Partial<RequestProperties> = {}): RequestProperties {
+ return {
+ userHash: WARM_USER_HASH,
+ apiToken: 'phx_test_token',
+ sessionId: 'sess-warm',
+ mcpClientName: 'test-profiler',
+ mcpClientVersion: '1.0.0',
+ mcpProtocolVersion: '2025-03-26',
+ transport: 'streamable-http',
+ requestStartTime: Date.now(),
+ ...overrides,
+ }
+}
+
+function makeColdProps(): RequestProperties {
+ return makeProps({
+ userHash: `user-${Math.random().toString(36).slice(2, 10)}`,
+ sessionId: `sess-${Math.random().toString(36).slice(2, 10)}`,
+ })
+}
+
+function makeJsonRpcBody(method: string, params?: Record<string, unknown>): string {
+ return JSON.stringify({
+ jsonrpc: '2.0',
+ id: Math.floor(Math.random() * 1_000_000),
+ method,
+ ...(params ? { params } : {}),
+ })
+}
+
+function makeRequest(body: string): Request {
+ return new Request('http://localhost/mcp', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body,
+ })
+}
+
+function _fmt(bytes: number): string {
+ if (Math.abs(bytes) < 1024) {return `${bytes} B`}
+ const kb = bytes / 1024
+ if (Math.abs(kb) < 1024) {return `${kb.toFixed(1)} KB`}
+ return `${(kb / 1024).toFixed(2)} MB`
+}
+
+function gc(): void {
+ if (global.gc) {
+ global.gc()
+ global.gc()
+ }
+}
+
+function percentile(sorted: number[], p: number): number {
+ const idx = Math.ceil((p / 100) * sorted.length) - 1
+ return sorted[Math.max(0, idx)]!
+}
+
+function stats(timings: number[]): { min: number; p50: number; p95: number; p99: number; max: number; avg: number } {
+ const sorted = [...timings].sort((a, b) => a - b)
+ return {
+ min: sorted[0]!,
+ p50: percentile(sorted, 50),
+ p95: percentile(sorted, 95),
+ p99: percentile(sorted, 99),
+ max: sorted[sorted.length - 1]!,
+ avg: timings.reduce((a, b) => a + b, 0) / timings.length,
+ }
+}
+
+const INIT_PARAMS = {
+ protocolVersion: '2025-03-26',
+ capabilities: {},
+ clientInfo: { name: 'test', version: '1.0' },
+}
+
+describe('McpDispatcher profiling', () => {
+ let dispatcher: McpDispatcher
+ let catalog: ToolCatalog
+ let originalFetch: typeof fetch
+
+ beforeAll(async () => {
+ originalFetch = globalThis.fetch
+ globalThis.fetch = createMockFetch()
+
+ process.env.POSTHOG_API_BASE_URL = 'http://localhost:19876'
+ process.env.POSTHOG_ANALYTICS_API_KEY = 'phc_test'
+ process.env.POSTHOG_ANALYTICS_HOST = 'http://localhost:19876'
+
+ const redis = new MockRedis()
+ catalog = new ToolCatalog()
+ dispatcher = new McpDispatcher(catalog, redis as any)
+ await dispatcher.warmup()
+
+ // Prime the warm cache
+ await dispatcher.handleRequest(
+ makeRequest(makeJsonRpcBody('tools/list')),
+ makeProps()
+ )
+ })
+
+ afterAll(() => {
+ globalThis.fetch = originalFetch
+ })
+
+ it('reports warmup stats', () => {
+ const entries = catalog.getPreBuiltEntries()
+
+ expect(entries.length).toBeGreaterThan(0)
+ })
+
+ it('measures cold cache init latency', async () => {
+
+
+ const coldTimings: number[] = []
+ const coldFetchCounts: number[] = []
+
+ for (let i = 0; i < 20; i++) {
+ const before = fetchCallCount
+ const start = performance.now()
+ const resp = await dispatcher.handleRequest(
+ makeRequest(makeJsonRpcBody('initialize', INIT_PARAMS)),
+ makeColdProps()
+ )
+ const ms = performance.now() - start
+ const fetches = fetchCallCount - before
+
+ coldTimings.push(ms)
+ coldFetchCounts.push(fetches)
+ expect(resp.status).toBe(200)
+ }
+
+ const _s = stats(coldTimings)
+ const _avgFetches = coldFetchCounts.reduce((a, b) => a + b, 0) / coldFetchCounts.length
+
+
+
+
+ }, 30_000)
+
+ it('measures warm cache request latency', async () => {
+
+
+ for (const [_label, method, params] of [
+ ['initialize', 'initialize', INIT_PARAMS],
+ ['tools/list', 'tools/list', undefined],
+ ['tools/call', 'tools/call', { name: 'user-get', arguments: {} }],
+ ['resources/list', 'resources/list', undefined],
+ ['ping', 'ping', undefined],
+ ] as const) {
+ // JIT warmup
+ for (let i = 0; i < 10; i++) {
+ await dispatcher.handleRequest(
+ makeRequest(makeJsonRpcBody(method, params as Record<string, unknown> | undefined)),
+ makeProps()
+ )
+ }
+
+ const timings: number[] = []
+ for (let i = 0; i < 100; i++) {
+ const start = performance.now()
+ await dispatcher.handleRequest(
+ makeRequest(makeJsonRpcBody(method, params as Record<string, unknown> | undefined)),
+ makeProps()
+ )
+ timings.push(performance.now() - start)
+ }
+
+ const _s = stats(timings)
+
+ }
+ }, 120_000)
+
+ it('measures cold vs warm fetch overhead', async () => {
+
+
+ // Cold: new userHash
+ const coldBefore = fetchCallCount
+ await dispatcher.handleRequest(
+ makeRequest(makeJsonRpcBody('tools/call', { name: 'user-get', arguments: {} })),
+ makeColdProps()
+ )
+ const _coldFetches = fetchCallCount - coldBefore
+
+ // Warm: reused userHash (cache hit)
+ const warmBefore = fetchCallCount
+ await dispatcher.handleRequest(
+ makeRequest(makeJsonRpcBody('tools/call', { name: 'user-get', arguments: {} })),
+ makeProps()
+ )
+ const _warmFetches = fetchCallCount - warmBefore
+
+
+
+
+ }, 15_000)
+
+ it('measures per-request memory (cold cache)', async () => {
+
+ for (const N of [1, 10, 50]) {
+ gc()
+ await new Promise((r) => setTimeout(r, 30))
+ gc()
+
+ const before = process.memoryUsage().heapUsed
+ const start = performance.now()
+
+ for (let i = 0; i < N; i++) {
+ await dispatcher.handleRequest(
+ makeRequest(makeJsonRpcBody('tools/call', { name: 'user-get', arguments: {} })),
+ makeColdProps()
+ )
+ }
+
+ const _elapsed = performance.now() - start
+ gc()
+ const after = process.memoryUsage().heapUsed
+ const _delta = after - before
+ }
+ }, 120_000)
+
+ it('measures concurrent burst (warm cache)', async () => {
+ for (const burst of [10, 50, 100, 200]) {
+ gc()
+ await new Promise((r) => setTimeout(r, 50))
+ gc()
+ const before = process.memoryUsage().heapUsed
+ const burstStart = performance.now()
+
+ const results = await Promise.all(
+ Array.from({ length: burst }, () =>
+ dispatcher.handleRequest(
+ makeRequest(makeJsonRpcBody('tools/call', { name: 'user-get', arguments: {} })),
+ makeProps()
+ )
+ )
+ )
+
+ const _burstMs = performance.now() - burstStart
+ gc()
+ const after = process.memoryUsage().heapUsed
+ const _delta = after - before
+
+ for (const r of results) {
+ expect(r.status).toBe(200)
+ }
+ }
+ }, 60_000)
+
+ it('measures concurrent burst (cold cache)', async () => {
+ for (const burst of [10, 50, 100]) {
+ gc()
+ await new Promise((r) => setTimeout(r, 50))
+ gc()
+ const before = process.memoryUsage().heapUsed
+ const burstStart = performance.now()
+
+ const results = await Promise.all(
+ Array.from({ length: burst }, () =>
+ dispatcher.handleRequest(
+ makeRequest(makeJsonRpcBody('tools/call', { name: 'user-get', arguments: {} })),
+ makeColdProps()
+ )
+ )
+ )
+
+ const _burstMs = performance.now() - burstStart
+ gc()
+ const after = process.memoryUsage().heapUsed
+ const _delta = after - before
+
+ for (const r of results) {
+ expect(r.status).toBe(200)
+ }
+ }
+ }, 60_000)
+
+ it('measures batch JSON-RPC', async () => {
+ for (const batchSize of [5, 20, 50]) {
+ gc()
+ await new Promise((r) => setTimeout(r, 50))
+ gc()
+
+ const before = process.memoryUsage().heapUsed
+ const batchStart = performance.now()
+
+ const batch = Array.from({ length: batchSize }, (_, i) => ({
+ jsonrpc: '2.0' as const,
+ id: i + 1,
+ method: i === 0 ? 'initialize' : i === 1 ? 'tools/list' : 'tools/call',
+ params:
+ i === 0
+ ? INIT_PARAMS
+ : i === 1
+ ? {}
+ : { name: 'user-get', arguments: {} },
+ }))
+
+ const resp = await dispatcher.handleRequest(
+ new Request('http://localhost/mcp', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(batch),
+ }),
+ makeProps()
+ )
+
+ const results = (await resp.json()) as unknown[]
+ const _batchMs = performance.now() - batchStart
+
+ gc()
+ const after = process.memoryUsage().heapUsed
+ const _delta = after - before
+
+ expect(results.length).toBe(batchSize)
+ }
+ }, 60_000)
+
+ it('reports final memory', () => {
+ gc()
+ const _m = process.memoryUsage()
+ })
+})
diff --git a/services/mcp/tests/hono/mcp-protocol.test.ts b/services/mcp/tests/hono/mcp-protocol.test.ts
index 759945976e9d..424ed8207747 100644
--- a/services/mcp/tests/hono/mcp-protocol.test.ts
+++ b/services/mcp/tests/hono/mcp-protocol.test.ts
@@ -4,14 +4,10 @@ import { afterAll, beforeAll } from 'vitest'
import { createApp } from '@/hono/app'
import type { RedisLike } from '@/hono/cache/RedisCache'
-import { defineMcpProtocolTests } from '../integration/mcp-protocol-suite'
-import { handlers } from '../workers/fixtures/handlers'
+import { defineMcpProtocolTests, defineResilienceTests, type ProtocolTestHarness } from '../integration/mcp-protocol-suite'
+import { handlers, contextMillHandler } from '../workers/fixtures/handlers'
-// MSW intercepts the outbound PostHog API traffic the MCP server makes during
-// init() and tool calls, serving fixtures from the same set the workers harness
-// uses. Requests to our in-process Hono `app` go through `app.request()` and
-// don't touch globalThis.fetch, so we don't need a localhost passthrough rule.
-const mswServer = setupServer(...handlers)
+const mswServer = setupServer(...handlers, contextMillHandler)
function createInMemoryRedis(): RedisLike & { ping(): Promise<string> } {
const store = new Map<string, string>()
@@ -40,28 +36,30 @@ function createInMemoryRedis(): RedisLike & { ping(): Promise<string> } {
let app: ReturnType<typeof createApp>['app']
-beforeAll(() => {
+beforeAll(async () => {
process.env.TEST = '1'
+ process.env.MCP_APPS_BASE_URL = 'https://apps.test'
mswServer.listen({ onUnhandledRequest: 'bypass' })
- app = createApp(createInMemoryRedis()).app
+ const created = createApp(createInMemoryRedis())
+ app = created.app
+ await created.warmup()
})
afterAll(() => {
mswServer.close()
})
-// Custom fetch that routes through the Hono app's `request()` entry point —
-// the same WHATWG Request/Response pipeline the runtime uses, minus the TCP
-// socket. Keeps the test fully in-process so no port management or shutdown
-// races; still exercises every middleware, route, and the MCP transport.
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 ?? {})
}
-defineMcpProtocolTests('Hono', () => ({
- // baseUrl host is irrelevant — `fetchViaApp` extracts only path + query.
+const harness = (): ProtocolTestHarness => ({
baseUrl: new URL('http://hono.test'),
fetch: fetchViaApp,
token: 'phx_integration_test_token',
-}))
+ stateless: true,
+})
+
+defineMcpProtocolTests('Hono', harness)
+defineResilienceTests('Hono', harness)
diff --git a/services/mcp/tests/hono/mcp-server.test.ts b/services/mcp/tests/hono/mcp-server.test.ts
deleted file mode 100644
index 10fe228fd874..000000000000
--- a/services/mcp/tests/hono/mcp-server.test.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-
-import type { RedisLike } from '@/hono/cache/RedisCache'
-import { HonoMcpServer, type RequestProperties } from '@/hono/mcp-server'
-
-interface MockRedis extends RedisLike {
- _store: Map<string, string>
-}
-
-function createMockRedis(): MockRedis {
- const store = new Map<string, string>()
- return {
- get: vi.fn(async (key: string) => store.get(key) ?? null),
- set: vi.fn(async (key: string, value: string) => {
- store.set(key, value)
- return 'OK'
- }),
- del: vi.fn(async (...keys: string[]) => keys.length),
- scan: vi.fn(async () => ['0', []] as [string, string[]]),
- _store: store,
- }
-}
-
-describe('HonoMcpServer', () => {
- let mockRedis: MockRedis
- const baseProps: RequestProperties = {
- userHash: 'test-hash',
- apiToken: 'phx_test_token',
- version: 1,
- }
- const originalEnv = { ...process.env }
-
- beforeEach(() => {
- mockRedis = createMockRedis()
- delete process.env.POSTHOG_API_BASE_URL
- })
-
- afterEach(() => {
- process.env = { ...originalEnv }
- })
-
- describe('constructor', () => {
- it('should create a server instance', () => {
- const server = new HonoMcpServer(mockRedis, baseProps)
- expect(server.server).toBeTruthy()
- })
-
- it('should expose requestProperties', () => {
- const server = new HonoMcpServer(mockRedis, baseProps)
- expect(server.requestProperties.userHash).toBe('test-hash')
- expect(server.requestProperties.apiToken).toBe('phx_test_token')
- })
- })
-
- describe('getBaseUrl', () => {
- it('should return POSTHOG_API_BASE_URL from env', async () => {
- process.env.POSTHOG_API_BASE_URL = 'https://custom.posthog.com'
- const server = new HonoMcpServer(mockRedis, baseProps)
- const url = await server.getBaseUrl()
- expect(url).toBe('https://custom.posthog.com')
- })
-
- it('should default to localhost:8010 in dev when not set', async () => {
- delete process.env.POSTHOG_API_BASE_URL
- const server = new HonoMcpServer(mockRedis, baseProps)
- const url = await server.getBaseUrl()
- expect(url).toBe('http://localhost:8010')
- })
-
- it('should throw in production when not set', async () => {
- delete process.env.POSTHOG_API_BASE_URL
- process.env.NODE_ENV = 'production'
- const server = new HonoMcpServer(mockRedis, baseProps)
- await expect(server.getBaseUrl()).rejects.toThrow('POSTHOG_API_BASE_URL must be set')
- })
- })
-
- describe('sessionManager', () => {
- it('should return a SessionManager instance', () => {
- const server = new HonoMcpServer(mockRedis, baseProps)
- expect(server.sessionManager).toBeTruthy()
- })
-
- it('should return same instance on repeated access', () => {
- const server = new HonoMcpServer(mockRedis, baseProps)
- const sm1 = server.sessionManager
- const sm2 = server.sessionManager
- expect(sm1).toBe(sm2)
- })
- })
-
- describe('getContext', () => {
- it('should return a context with all required fields', async () => {
- const server = new HonoMcpServer(mockRedis, { ...baseProps, region: 'us' })
- vi.spyOn(server, 'getBaseUrl').mockResolvedValue('https://us.posthog.com')
- const ctx = await server.getContext()
- expect(ctx.api).toBeTruthy()
- expect(ctx.cache).toBeTruthy()
- expect(ctx.env).toBeTruthy()
- expect(ctx.stateManager).toBeTruthy()
- expect(ctx.sessionManager).toBeTruthy()
- expect(ctx.getDistinctId).toBeTruthy()
- })
- })
-
- describe('trackEvent', () => {
- it('should not throw on tracking errors', async () => {
- const server = new HonoMcpServer(mockRedis, baseProps)
- vi.spyOn(server, 'getDistinctId').mockRejectedValue(new Error('fail'))
-
- const { AnalyticsEvent } = await import('@/lib/posthog/analytics')
- await expect(server.trackEvent(AnalyticsEvent.MCP_INIT)).resolves.toBeUndefined()
- })
- })
-
- describe('api', () => {
- it('should cache the ApiClient instance', async () => {
- process.env.POSTHOG_API_BASE_URL = 'https://us.posthog.com'
- const server = new HonoMcpServer(mockRedis, baseProps)
- const api1 = await server.api()
- const api2 = await server.api()
- expect(api1).toBe(api2)
- })
- })
-})
diff --git a/services/mcp/tests/hono/request-context.test.ts b/services/mcp/tests/hono/request-context.test.ts
new file mode 100644
index 000000000000..671b81e35ab2
--- /dev/null
+++ b/services/mcp/tests/hono/request-context.test.ts
@@ -0,0 +1,168 @@
+import { describe, expect, it, vi } from 'vitest'
+
+const mockMe = vi.fn()
+
+vi.mock('@/api/client', () => ({
+ ApiClient: vi.fn().mockImplementation(() => ({
+ users: () => ({ me: mockMe }),
+ })),
+}))
+
+import type { RedisLike } from '@/hono/cache/RedisCache'
+import { RequestContext } from '@/hono/request-context'
+import type { RequestProperties } from '@/lib/request-properties'
+
+function fakeRedis(): RedisLike {
+ 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 n = 0
+ for (const k of keys) {
+ if (store.delete(k)) {
+ n++
+ }
+ }
+ return n
+ },
+ scan: async () => ['0', [...store.keys()]],
+ }
+}
+
+const env = {} as any
+
+function makeProps(overrides: Partial<RequestProperties> = {}): RequestProperties {
+ return {
+ userHash: 'test-user',
+ apiToken: 'phx_test',
+ sessionId: 'sess-1',
+ mcpClientName: 'test-client',
+ mcpClientVersion: '1.0',
+ mcpProtocolVersion: '2025-03-26',
+ transport: 'streamable-http',
+ requestStartTime: Date.now(),
+ ...overrides,
+ }
+}
+
+describe('RequestContext', () => {
+ describe('getDistinctId', () => {
+ it('deduplicates concurrent calls into a single API request', async () => {
+ mockMe.mockResolvedValue({ success: true, data: { distinct_id: 'user-123' } })
+ const ctx = new RequestContext(fakeRedis(), env, makeProps())
+
+ const [a, b, c] = await Promise.all([
+ ctx.getDistinctId(),
+ ctx.getDistinctId(),
+ ctx.getDistinctId(),
+ ])
+
+ expect(a).toBe('user-123')
+ expect(b).toBe('user-123')
+ expect(c).toBe('user-123')
+ expect(mockMe).toHaveBeenCalledTimes(1)
+ })
+
+ it('returns cached distinctId without calling API', async () => {
+ const redis = fakeRedis()
+ await redis.set('mcp:user:test-user:distinctId', JSON.stringify('cached-id'))
+ mockMe.mockClear()
+
+ const ctx = new RequestContext(redis, env, makeProps())
+ const result = await ctx.getDistinctId()
+
+ expect(result).toBe('cached-id')
+ expect(mockMe).not.toHaveBeenCalled()
+ })
+
+ it('caches the resolved distinctId for subsequent calls', async () => {
+ mockMe.mockResolvedValueOnce({ success: true, data: { distinct_id: 'fresh-id' } })
+ const redis = fakeRedis()
+ const ctx = new RequestContext(redis, env, makeProps())
+
+ await ctx.getDistinctId()
+ const cached = await redis.get('mcp:user:test-user:distinctId')
+ expect(JSON.parse(cached!)).toBe('fresh-id')
+ })
+
+ it('throws when API returns an error', async () => {
+ mockMe.mockResolvedValue({ success: false, error: { message: 'Unauthorized' } })
+ const ctx = new RequestContext(fakeRedis(), env, makeProps())
+
+ await expect(ctx.getDistinctId()).rejects.toThrow('Failed to get user')
+ })
+ })
+
+ describe('getSessionUuid', () => {
+ it('returns undefined when sessionId is undefined', async () => {
+ const ctx = new RequestContext(fakeRedis(), env, makeProps())
+ expect(await ctx.getSessionUuid(undefined)).toBeUndefined()
+ })
+
+ it('returns a stable UUID for the same sessionId', async () => {
+ const ctx = new RequestContext(fakeRedis(), env, makeProps())
+ const first = await ctx.getSessionUuid('sess-abc')
+ const second = await ctx.getSessionUuid('sess-abc')
+
+ expect(first).toBe(second)
+ expect(first).toMatch(/^[0-9a-f-]{36}$/)
+ })
+
+ it('returns different UUIDs for different sessionIds', async () => {
+ const ctx = new RequestContext(fakeRedis(), env, makeProps())
+ const a = await ctx.getSessionUuid('sess-1')
+ const b = await ctx.getSessionUuid('sess-2')
+
+ expect(a).not.toBe(b)
+ })
+ })
+
+ describe('buildClientProperties', () => {
+ it('includes all request properties', () => {
+ const ctx = new RequestContext(fakeRedis(), env, makeProps({
+ mcpClientName: 'claude-code',
+ mcpClientVersion: '2.0',
+ mcpProtocolVersion: '2025-03-26',
+ mcpConsumer: 'posthog-code',
+ transport: 'streamable-http',
+ }))
+
+ expect(ctx.buildClientProperties()).toEqual({
+ mcp_runtime: 'hono',
+ mcp_client_name: 'claude-code',
+ mcp_client_version: '2.0',
+ mcp_protocol_version: '2025-03-26',
+ mcp_consumer: 'posthog-code',
+ mcp_transport: 'streamable-http',
+ })
+ })
+
+ it('omits undefined properties', () => {
+ const ctx = new RequestContext(fakeRedis(), env, makeProps({
+ mcpClientName: undefined,
+ mcpClientVersion: undefined,
+ mcpProtocolVersion: undefined,
+ mcpConsumer: undefined,
+ transport: undefined,
+ }))
+
+ expect(ctx.buildClientProperties()).toEqual({ mcp_runtime: 'hono' })
+ })
+ })
+
+ describe('cache', () => {
+ it('throws when userHash is missing', () => {
+ const ctx = new RequestContext(fakeRedis(), env, makeProps({ userHash: '' }))
+ expect(() => ctx.cache).toThrow('User hash is required')
+ })
+
+ it('returns the same cache instance on repeated access', () => {
+ const ctx = new RequestContext(fakeRedis(), env, makeProps())
+ expect(ctx.cache).toBe(ctx.cache)
+ })
+ })
+})
diff --git a/services/mcp/tests/hono/resource-catalog.test.ts b/services/mcp/tests/hono/resource-catalog.test.ts
new file mode 100644
index 000000000000..217a9dcd9dec
--- /dev/null
+++ b/services/mcp/tests/hono/resource-catalog.test.ts
@@ -0,0 +1,170 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/resources/internals', () => ({
+ fetchContextMillResources: vi.fn(),
+ filterValidEntries: vi.fn(),
+ loadManifestFromArchive: vi.fn(),
+ clearResourceCache: vi.fn(),
+}))
+
+vi.mock('@/resources', () => ({
+ getPromptsFromManifest: vi.fn(),
+}))
+
+vi.mock('@/resources/ui-apps.generated', async (importOriginal) => importOriginal())
+vi.mock('@/resources/ui-apps', async (importOriginal) => importOriginal())
+
+import { fetchContextMillResources, filterValidEntries, loadManifestFromArchive } from '@/resources/internals'
+import { getPromptsFromManifest } from '@/resources'
+import { ResourceCatalog } from '@/hono/resource-catalog'
+
+const mockEnv = {
+ MCP_APPS_BASE_URL: 'https://apps.test',
+ POSTHOG_MCP_APPS_ANALYTICS_BASE_URL: undefined,
+} as any
+
+function makeContextMillEntry(name: string, uri: string): { name: string; uri: string; resource: { mimeType: string; description: string; text: string } } {
+ return {
+ name,
+ uri,
+ resource: {
+ mimeType: 'text/plain',
+ description: `${name} desc`,
+ text: `content of ${name}`,
+ },
+ }
+}
+
+describe('ResourceCatalog', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ describe('warmup and resource listing', () => {
+ it('serves resources and prompts after warmup', async () => {
+ const entries = [
+ makeContextMillEntry('guide', 'posthog://guide'),
+ makeContextMillEntry('faq', 'posthog://faq'),
+ ]
+ vi.mocked(fetchContextMillResources).mockResolvedValue('archive' as any)
+ vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)
+ vi.mocked(filterValidEntries).mockReturnValue(entries as any)
+ vi.mocked(getPromptsFromManifest).mockResolvedValue([
+ { name: 'greet', title: 'Greet', description: 'A greeting', messages: [{ role: 'user', content: { type: 'text', text: 'hi' } }] },
+ ] as any)
+
+ const catalog = new ResourceCatalog(mockEnv)
+ await catalog.warmup()
+
+ const { resources } = catalog.getResourcesList()
+ expect(resources.map((r) => r.name)).toContain('guide')
+ expect(resources.map((r) => r.name)).toContain('faq')
+
+ const { prompts } = catalog.getPromptsList()
+ expect(prompts).toHaveLength(1)
+ expect(prompts[0]!.name).toBe('greet')
+ })
+
+ it('pre-merges resource list so getResourcesList returns a stable array', async () => {
+ vi.mocked(fetchContextMillResources).mockResolvedValue('archive' as any)
+ vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)
+ vi.mocked(filterValidEntries).mockReturnValue([makeContextMillEntry('a', 'posthog://a')] as any)
+ vi.mocked(getPromptsFromManifest).mockResolvedValue([])
+
+ const catalog = new ResourceCatalog(mockEnv)
+ await catalog.warmup()
+
+ const list1 = catalog.getResourcesList().resources
+ const list2 = catalog.getResourcesList().resources
+ expect(list1).toBe(list2)
+ })
+ })
+
+ describe('readResource', () => {
+ it('returns contents for a known URI', async () => {
+ vi.mocked(fetchContextMillResources).mockResolvedValue('archive' as any)
+ vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)
+ vi.mocked(filterValidEntries).mockReturnValue([makeContextMillEntry('doc', 'posthog://doc')] as any)
+ vi.mocked(getPromptsFromManifest).mockResolvedValue([])
+
+ const catalog = new ResourceCatalog(mockEnv)
+ await catalog.warmup()
+
+ const result = catalog.readResource({ uri: 'posthog://doc' }) as any
+ expect(result.contents).toHaveLength(1)
+ expect(result.contents[0].text).toBe('content of doc')
+ })
+
+ it('returns empty contents for unknown URI', async () => {
+ vi.mocked(fetchContextMillResources).mockResolvedValue('archive' as any)
+ vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)
+ vi.mocked(filterValidEntries).mockReturnValue([])
+ vi.mocked(getPromptsFromManifest).mockResolvedValue([])
+
+ const catalog = new ResourceCatalog(mockEnv)
+ await catalog.warmup()
+
+ const result = catalog.readResource({ uri: 'posthog://nonexistent' }) as any
+ expect(result.contents).toEqual([])
+ })
+ })
+
+ describe('getPrompt', () => {
+ it('returns messages for a known prompt name', async () => {
+ vi.mocked(fetchContextMillResources).mockResolvedValue('archive' as any)
+ vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)
+ vi.mocked(filterValidEntries).mockReturnValue([])
+ vi.mocked(getPromptsFromManifest).mockResolvedValue([
+ { name: 'test-prompt', title: 'T', description: 'D', messages: [{ role: 'user', content: { type: 'text', text: 'hello' } }] },
+ ] as any)
+
+ const catalog = new ResourceCatalog(mockEnv)
+ await catalog.warmup()
+
+ const result = catalog.getPrompt({ name: 'test-prompt' }) as any
+ expect(result.messages).toHaveLength(1)
+ })
+
+ it('returns empty messages for unknown prompt', async () => {
+ vi.mocked(fetchContextMillResources).mockResolvedValue('archive' as any)
+ vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)
+ vi.mocked(filterValidEntries).mockReturnValue([])
+ vi.mocked(getPromptsFromManifest).mockResolvedValue([])
+
+ const catalog = new ResourceCatalog(mockEnv)
+ await catalog.warmup()
+
+ const result = catalog.getPrompt({ name: 'nope' }) as any
+ expect(result.messages).toEqual([])
+ })
+ })
+
+ describe('error resilience', () => {
+ it('continues serving prompts when resource fetch fails', async () => {
+ vi.mocked(fetchContextMillResources).mockRejectedValue(new Error('network'))
+ vi.mocked(getPromptsFromManifest).mockResolvedValue([
+ { name: 'p', title: 'P', description: 'D', messages: [] },
+ ] as any)
+
+ const catalog = new ResourceCatalog(mockEnv)
+ await catalog.warmup()
+
+ const names = catalog.getResourcesList().resources.map((r) => r.name)
+ expect(names).not.toContain('guide')
+ expect(catalog.getPromptsList().prompts).toHaveLength(1)
+ })
+
+ it('continues serving resources when prompt fetch fails', async () => {
+ vi.mocked(fetchContextMillResources).mockResolvedValue('archive' as any)
+ vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)
+ vi.mocked(filterValidEntries).mockReturnValue([makeContextMillEntry('r', 'posthog://r')] as any)
+ vi.mocked(getPromptsFromManifest).mockRejectedValue(new Error('fail'))
+
+ const catalog = new ResourceCatalog(mockEnv)
+ await catalog.warmup()
+
+ expect(catalog.getResourcesList().resources.map((r) => r.name)).toContain('r')
+ expect(catalog.getPromptsList().prompts).toEqual([])
+ })
+ })
+})
diff --git a/services/mcp/tests/hono/setup.ts b/services/mcp/tests/hono/setup.ts
index 2686f60fafd5..476771e9460c 100644
--- a/services/mcp/tests/hono/setup.ts
+++ b/services/mcp/tests/hono/setup.ts
@@ -17,14 +17,15 @@ vi.mock('@shared/guidelines.md', () => ({
default: '# Guidelines\nTest guidelines content.',
}))
-vi.mock('@/resources/ui-apps', () => ({
- registerUiAppResources: vi.fn().mockResolvedValue(undefined),
- withUiApp: <T extends { _meta?: unknown }>(_appKey: string, config: Omit<T, '_meta'>): T => config as T,
-}))
+vi.mock('@/resources/ui-apps', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/resources/ui-apps')>()
+ return {
+ ...actual,
+ registerUiAppResources: vi.fn().mockResolvedValue(undefined),
+ }
+})
-vi.mock('@/resources/ui-apps.generated', () => ({
- UI_APP_REGISTRY: {},
-}))
+vi.mock('@/resources/ui-apps.generated', async (importOriginal) => importOriginal())
vi.mock('@posthog/mcp-analytics', () => ({
track: vi.fn(),
diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.ts
new file mode 100644
index 000000000000..10af221069ab
--- /dev/null
+++ b/services/mcp/tests/hono/tool-executor.test.ts
@@ -0,0 +1,164 @@
+import { beforeAll, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/resources/internals', () => ({
+ fetchContextMillResources: vi.fn().mockRejectedValue(new Error('mocked')),
+ filterValidEntries: vi.fn().mockReturnValue([]),
+ loadManifestFromArchive: vi.fn().mockReturnValue({ resources: [] }),
+ clearResourceCache: vi.fn(),
+}))
+
+vi.mock('@/resources', () => ({
+ getPromptsFromManifest: vi.fn().mockResolvedValue([]),
+}))
+
+
+import type { RequestProperties } from '@/lib/request-properties'
+import type { ResolvedState } from '@/hono/request-state-resolver'
+import { ToolCatalog } from '@/hono/tool-catalog'
+import { ToolExecutor } from '@/hono/tool-executor'
+import { InstructionsBuilder } from '@/hono/instructions'
+import type { } from '@/tools/types'
+
+function makeProps(overrides: Partial<RequestProperties> = {}): RequestProperties {
+ return {
+ userHash: 'test-user',
+ apiToken: 'phx_test',
+ sessionId: 'sess-1',
+ mcpClientName: 'test',
+ mcpClientVersion: '1.0',
+ mcpProtocolVersion: '2025-03-26',
+ transport: 'streamable-http',
+ requestStartTime: Date.now(),
+ ...overrides,
+ }
+}
+
+function makeState(tools: { name: string }[], overrides: Partial<ResolvedState> = {}): ResolvedState {
+ return {
+ reqCtx: {
+ cache: { get: vi.fn(), set: vi.fn() },
+ getAnalyticsContextSafe: vi.fn().mockResolvedValue(undefined),
+ trackEvent: vi.fn(),
+ getSessionUuid: vi.fn().mockResolvedValue(undefined),
+ } as any,
+ context: {
+ api: {},
+ cache: {},
+ env: {},
+ stateManager: {},
+ sessionManager: {},
+ getDistinctId: vi.fn(),
+ trackEvent: vi.fn(),
+ } as any,
+ version: 1,
+ useSingleExec: false,
+ toolFeatureFlags: undefined,
+ apiKeyScopes: [],
+ clientProfile: { capabilities: { supportsInstructions: true } } as any,
+ allTools: tools as any,
+ distinctId: 'test-distinct-id',
+ ...overrides,
+ }
+}
+
+describe('ToolExecutor', () => {
+ let catalog: ToolCatalog
+ let executor: ToolExecutor
+
+ beforeAll(async () => {
+ catalog = new ToolCatalog()
+ await catalog.warmup()
+ executor = new ToolExecutor(catalog, new InstructionsBuilder(''))
+ })
+
+ describe('handleToolCall', () => {
+ it('returns error when tool name is missing', async () => {
+ const result = (await executor.handleToolCall({}, makeProps(), makeState([]))) as any
+ expect(result.isError).toBe(true)
+ expect(result.content[0].text).toContain('Missing tool name')
+ })
+
+ it('returns error when tool does not exist', async () => {
+ const result = (await executor.handleToolCall(
+ { name: 'nonexistent-tool', arguments: {} },
+ makeProps(),
+ makeState([])
+ )) as any
+ expect(result.isError).toBe(true)
+ expect(result.content[0].text).toContain('nonexistent-tool')
+ expect(result.content[0].text).toContain('not found')
+ })
+
+ it('rejects tools not in the per-request filtered set', async () => {
+ const entries = catalog.getPreBuiltEntries()
+ const tool = entries[0]!
+
+ const result = (await executor.handleToolCall(
+ { name: tool.name, arguments: {} },
+ makeProps(),
+ makeState([])
+ )) as any
+ expect(result.isError).toBe(true)
+ expect(result.content[0].text).toContain('not found')
+ })
+
+ it('returns validation error for invalid arguments', async () => {
+ const knownTool = catalog.getPreBuiltEntries()[0]
+ if (!knownTool) {throw new Error('need at least one tool to test validation')}
+
+ const result = (await executor.handleToolCall(
+ { name: knownTool.name, arguments: { __invalid_field_xyz: 'bad' } },
+ makeProps(),
+ makeState([{ name: knownTool.name }])
+ )) as any
+
+ expect(result).not.toBeNull()
+ })
+
+ it('successfully calls a real tool from the catalog', async () => {
+ const entries = catalog.getPreBuiltEntries()
+ const userGet = entries.find((e) => e.name === 'user-get')
+ if (!userGet) {throw new Error('user-get tool not found in catalog')}
+
+ const result = (await executor.handleToolCall(
+ { name: 'user-get', arguments: {} },
+ makeProps(),
+ makeState([{ name: 'user-get' }])
+ )) as any
+
+ expect(result).not.toBeNull()
+ expect(result.content).not.toBeNull()
+ })
+ })
+
+ describe('handleToolsList', () => {
+ it('returns filtered tools matching the state allTools', async () => {
+ const allEntries = catalog.getPreBuiltEntries()
+ const subset = allEntries.slice(0, 3)
+
+ const result = await executor.handleToolsList(
+ makeState(subset.map((e) => ({ name: e.name }))),
+ makeProps()
+ )
+
+ expect(result.tools).toHaveLength(3)
+ expect(result.tools.map((t) => t.name)).toEqual(subset.map((e) => e.name))
+ })
+
+ it('returns empty list when allTools is empty', async () => {
+ const result = await executor.handleToolsList(makeState([]), makeProps())
+ expect(result.tools).toEqual([])
+ })
+
+ it('returns single exec tool entry when useSingleExec is true', async () => {
+ const state = makeState(
+ catalog.getPreBuiltEntries().slice(0, 5).map((e) => ({ name: e.name })),
+ { useSingleExec: true, version: 2 }
+ )
+
+ const result = await executor.handleToolsList(state, makeProps())
+ expect(result.tools).toHaveLength(1)
+ expect(result.tools[0]!.name).toBe('exec')
+ })
+ })
+})
diff --git a/services/mcp/tests/integration/harness/hono.ts b/services/mcp/tests/integration/harness/hono.ts
index 021c2b2679f8..9da72fbd4171 100644
--- a/services/mcp/tests/integration/harness/hono.ts
+++ b/services/mcp/tests/integration/harness/hono.ts
@@ -36,21 +36,24 @@ async function startTestRedis(): Promise<InstanceType<typeof Redis>> {
}
export async function startHonoHarness(env: IntegrationEnv): Promise<IntegrationHarness> {
- // Route the MCP server's outbound API traffic at the local PostHog stack.
- // `getBaseUrl()` checks `POSTHOG_API_BASE_URL` first and bypasses region detection.
process.env.POSTHOG_API_BASE_URL = env.apiBaseUrl
- const redis = await startTestRedis()
- const { app } = createApp(redis as unknown as Parameters<typeof createApp>[0])
- const server = serve({ fetch: app.fetch, port: 0 })
- const address = server.address() as AddressInfo
- const baseUrl = new URL(`http://127.0.0.1:${address.port}`)
-
- // `getEnv()` reads MCP_APPS_BASE_URL on every HonoMcpServer init, so we can
- // set it after the listener has its port. Pointing at the harness's own
- // origin so `/ui-apps/<app>/main.js` resolves to this server's static route.
+ // Start a temporary listener on port 0 to discover a free port, then
+ // set MCP_APPS_BASE_URL before creating the app so the ResourceCatalog
+ // (which snapshots env at construction time) sees the correct URL.
+ const probe = serve({ fetch: () => new Response(), port: 0 })
+ const probePort = (probe.address() as AddressInfo).port
+ await new Promise<void>((resolve) => probe.close(() => resolve()))
+
+ const baseUrl = new URL(`http://127.0.0.1:${probePort}`)
process.env.MCP_APPS_BASE_URL = baseUrl.toString().replace(/\/$/, '')
+ const redis = await startTestRedis()
+ const { app, warmup } = createApp(redis as unknown as Parameters<typeof createApp>[0])
+ await warmup()
+
+ const server = serve({ fetch: app.fetch, port: probePort })
+
return {
baseUrl,
stop: async () => {
diff --git a/services/mcp/tests/integration/mcp-protocol-suite.ts b/services/mcp/tests/integration/mcp-protocol-suite.ts
index 4475645b4b45..4c913f8f6561 100644
--- a/services/mcp/tests/integration/mcp-protocol-suite.ts
+++ b/services/mcp/tests/integration/mcp-protocol-suite.ts
@@ -22,6 +22,9 @@ export type ProtocolTestHarness = {
/** Whether the runtime is stateless (no session store). Stateless runtimes
* ignore unknown Mcp-Session-Id headers instead of rejecting them. */
stateless?: boolean | undefined
+ /** 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
}
function buildStreamableClient(
@@ -56,10 +59,11 @@ export function defineMcpProtocolTests(
): void {
describe(`MCP protocol (${label})`, () => {
let client: Client
+ let currentHarness: ProtocolTestHarness
beforeEach(async () => {
- const harness = await getHarness()
- const built = buildStreamableClient(harness)
+ currentHarness = await getHarness()
+ const built = buildStreamableClient(currentHarness)
client = built.client
await client.connect(built.transport as ConnectableTransport)
})
@@ -74,6 +78,13 @@ export function defineMcpProtocolTests(
expect(info?.version).toBeTruthy()
})
+ it('returns instructions in the initialize response', () => {
+ const instructions = client.getInstructions()
+ expect(instructions).toBeTruthy()
+ expect(typeof instructions).toBe('string')
+ expect(instructions!.length).toBeGreaterThan(0)
+ })
+
it('lists available tools with non-empty schemas', async () => {
const { tools } = await client.listTools()
expect(tools.length).toBeGreaterThan(0)
@@ -93,58 +104,62 @@ export function defineMcpProtocolTests(
expect(names).toContain('organization-get')
})
- // Prompts and resources are populated at runtime from context-mill's
- // GitHub release. When the fetch fails (offline, sandbox, blocked TLS)
- // the McpServer doesn't claim those capabilities and the SDK surfaces
- // -32601. We accept either outcome here so the suite is robust to a
- // missing context-mill build artifact.
- it('lists prompts (empty or unsupported)', async () => {
- try {
- const { prompts } = await client.listPrompts()
- expect(Array.isArray(prompts)).toBe(true)
- } catch (err) {
- expect(String(err)).toMatch(/Method not found|-32601/)
+ it('lists prompts', async () => {
+ if (!currentHarness.gracefulUnknown) {
+ return
}
+ const { prompts } = await client.listPrompts()
+ expect(Array.isArray(prompts)).toBe(true)
})
- it('lists resources (empty or unsupported)', async () => {
- try {
- const { resources } = await client.listResources()
- expect(Array.isArray(resources)).toBe(true)
- } catch (err) {
- expect(String(err)).toMatch(/Method not found|-32601/)
+ it('lists resources including UI apps', async () => {
+ const { resources } = await client.listResources()
+ expect(resources.length).toBeGreaterThan(0)
+ const uris = resources.map((r) => r.uri)
+ expect(uris.some((u) => u.startsWith('ui://'))).toBe(true)
+ })
+
+ it('reads a UI app resource end-to-end', async () => {
+ const { resources } = await client.listResources()
+ const uiApp = resources.find((r) => r.uri.startsWith('ui://'))
+ if (!uiApp) {
+ throw new Error('expected at least one ui:// resource')
}
+ expect(uiApp.mimeType).toBeTruthy()
+
+ const result = await client.readResource({ uri: uiApp.uri })
+ expect(result.contents.length).toBeGreaterThan(0)
+ expect(result.contents[0]?.uri).toBe(uiApp.uri)
})
- it('reads a registered resource end-to-end', async ({ skip }) => {
- // Resources come from two sources at runtime: context-mill (a GitHub
- // release fetched at init) and `registerUiAppResources`. If neither
- // produced any registrations the protocol method is "not found" and
- // there's nothing to read — skip rather than fail.
- let resources: Awaited<ReturnType<Client['listResources']>>['resources']
- try {
- resources = (await client.listResources()).resources
- } catch {
- skip('No resources registered (resources/list returned -32601).')
- return
+ it('reads a context-mill resource by URI', async () => {
+ const { resources } = await client.listResources()
+ const cmResource = resources.find((r) => r.uri.startsWith('posthog://'))
+ if (!cmResource) {
+ throw new Error('expected at least one posthog:// resource from context-mill')
}
- if (resources.length === 0) {
- skip('No resources registered.')
+
+ const result = await client.readResource({ uri: cmResource.uri })
+ expect(result.contents.length).toBeGreaterThan(0)
+ expect(result.contents[0]?.uri).toBe(cmResource.uri)
+ const text = 'text' in result.contents[0]! ? result.contents[0].text : ''
+ expect(text).toBeTruthy()
+ })
+
+ it('returns empty contents for an unknown resource URI', async () => {
+ if (!currentHarness.gracefulUnknown) {
return
}
- // Pick the first resource; assert listing shape, then exercise the
- // resources/read JSON-RPC call which hits a different code path.
- const first = resources[0]
- if (!first) {
- throw new Error('expected at least one resource')
- }
- expect(first.uri).toBeTruthy()
- expect(first.mimeType).toBeTruthy()
+ const result = await client.readResource({ uri: 'posthog://does-not-exist' })
+ expect(result.contents).toEqual([])
+ })
- const result = await client.readResource({ uri: first.uri })
- expect(Array.isArray(result.contents)).toBe(true)
- expect(result.contents.length).toBeGreaterThan(0)
- expect(result.contents[0]?.uri).toBe(first.uri)
+ it('returns empty messages for an unknown prompt name', async () => {
+ if (!currentHarness.gracefulUnknown) {
+ return
+ }
+ const result = await client.getPrompt({ name: 'nonexistent-prompt' })
+ expect(result.messages).toEqual([])
})
it('calls a tool and returns content blocks', async () => {
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 f075390482fc..c3e140dd52d2 100644
--- a/services/mcp/tests/integration/mcp-protocol.hono.integration.test.ts
+++ b/services/mcp/tests/integration/mcp-protocol.hono.integration.test.ts
@@ -31,12 +31,14 @@ const harnessFor = (): {
token: string
token2: string | undefined
stateless: boolean
+ gracefulUnknown: boolean
} => ({
baseUrl: harness.baseUrl,
fetch: globalThis.fetch,
token: env.apiToken,
token2: env.apiToken2,
stateless: true,
+ gracefulUnknown: true,
})
defineMcpProtocolTests('Hono (real stack)', harnessFor)
diff --git a/services/mcp/tests/unit/feature-flag-version.test.ts b/services/mcp/tests/unit/feature-flag-version.test.ts
index 667e6d82f72a..ddc360580490 100644
--- a/services/mcp/tests/unit/feature-flag-version.test.ts
+++ b/services/mcp/tests/unit/feature-flag-version.test.ts
@@ -1,9 +1,11 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const mockIsFeatureEnabled = vi.fn()
+const mockGetAllFlags = vi.fn()
vi.mock('posthog-node', () => ({
PostHog: vi.fn().mockImplementation(() => ({
isFeatureEnabled: mockIsFeatureEnabled,
+ getAllFlags: mockGetAllFlags,
})),
}))
@@ -68,24 +70,30 @@ describe('evaluateFeatureFlags', () => {
vi.clearAllMocks()
})
- it('should evaluate multiple flags and forward groups on each call', async () => {
- mockIsFeatureEnabled.mockImplementation((flagKey: string) => Promise.resolve(flagKey === 'flag-on'))
+ it('should evaluate multiple flags via getAllFlags and forward groups', async () => {
+ mockGetAllFlags.mockResolvedValue({ 'flag-on': true, 'flag-off': false, 'unrelated': true })
const result = await evaluateFeatureFlags(['flag-on', 'flag-off'], 'user-123', { organization: 'org-abc' })
expect(result).toEqual({ 'flag-on': true, 'flag-off': false })
- expect(mockIsFeatureEnabled).toHaveBeenCalledWith('flag-on', 'user-123', {
- groups: { organization: 'org-abc' },
- })
- expect(mockIsFeatureEnabled).toHaveBeenCalledWith('flag-off', 'user-123', {
+ expect(mockGetAllFlags).toHaveBeenCalledWith('user-123', {
+ flagKeys: ['flag-on', 'flag-off'],
groups: { organization: 'org-abc' },
})
})
+ it('should omit groups when not provided', async () => {
+ mockGetAllFlags.mockResolvedValue({ 'flag-a': true })
+
+ await evaluateFeatureFlags(['flag-a'], 'user-123')
+
+ expect(mockGetAllFlags).toHaveBeenCalledWith('user-123', { flagKeys: ['flag-a'] })
+ })
+
it('should short-circuit when no flag keys are requested', async () => {
const result = await evaluateFeatureFlags([], 'user-123', { organization: 'org-abc' })
expect(result).toEqual({})
- expect(mockIsFeatureEnabled).not.toHaveBeenCalled()
+ expect(mockGetAllFlags).not.toHaveBeenCalled()
})
})
diff --git a/services/mcp/tests/unit/protocol-types.test.ts b/services/mcp/tests/unit/protocol-types.test.ts
new file mode 100644
index 000000000000..4dd7609a5033
--- /dev/null
+++ b/services/mcp/tests/unit/protocol-types.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from 'vitest'
+
+import { MCPClientProfile } from '@/lib/client-detection'
+import { resolveModeAndVersion } from '@/hono/request-state-resolver'
+
+describe('resolveModeAndVersion', () => {
+ function profile(overrides: Partial<ConstructorParameters<typeof MCPClientProfile>[0]> = {}): MCPClientProfile {
+ return new MCPClientProfile({ clientName: 'generic-client', ...overrides })
+ }
+
+ const base = {
+ mode: undefined as undefined,
+ singleExecFlagOn: false,
+ clientProfile: profile(),
+ flagVersion: undefined as number | undefined,
+ clientVersion: undefined as number | undefined,
+ }
+
+ it('defaults to version 1, no single exec', () => {
+ expect(resolveModeAndVersion(base)).toEqual({ useSingleExec: false, version: 1 })
+ })
+
+ it('explicit mode=cli forces single exec and version 2', () => {
+ expect(resolveModeAndVersion({ ...base, mode: 'cli' })).toEqual({
+ useSingleExec: true,
+ version: 2,
+ })
+ })
+
+ it('explicit mode=tools disables single exec even when flag is on for a coding agent', () => {
+ const result = resolveModeAndVersion({
+ ...base,
+ mode: 'tools',
+ singleExecFlagOn: true,
+ clientProfile: profile({ clientName: 'claude-code' }),
+ })
+ expect(result.useSingleExec).toBe(false)
+ })
+
+ it('coding agent with flag on activates single exec', () => {
+ const result = resolveModeAndVersion({
+ ...base,
+ singleExecFlagOn: true,
+ clientProfile: profile({ clientName: 'claude-code' }),
+ })
+ expect(result).toEqual({ useSingleExec: true, version: 2 })
+ })
+
+ it('non-coding agent with flag on does NOT activate single exec', () => {
+ const result = resolveModeAndVersion({
+ ...base,
+ singleExecFlagOn: true,
+ clientProfile: profile({ clientName: 'some-dashboard-client' }),
+ })
+ expect(result.useSingleExec).toBe(false)
+ })
+
+ it('flag on + PostHog code consumer activates single exec', () => {
+ const result = resolveModeAndVersion({
+ ...base,
+ singleExecFlagOn: true,
+ clientProfile: profile({ consumer: 'posthog-code' }),
+ })
+ expect(result.useSingleExec).toBe(true)
+ })
+
+ it('uses flagVersion when not in single exec mode', () => {
+ const result = resolveModeAndVersion({ ...base, flagVersion: 2 })
+ expect(result).toEqual({ useSingleExec: false, version: 2 })
+ })
+
+ it('clientVersion overrides default when no flagVersion', () => {
+ const result = resolveModeAndVersion({ ...base, clientVersion: 2 })
+ expect(result).toEqual({ useSingleExec: false, version: 2 })
+ })
+
+ it('flagVersion takes precedence over clientVersion', () => {
+ const result = resolveModeAndVersion({ ...base, flagVersion: 2, clientVersion: 1 })
+ expect(result.version).toBe(2)
+ })
+
+ it('single exec always forces version 2 regardless of flagVersion', () => {
+ const result = resolveModeAndVersion({ ...base, mode: 'cli', flagVersion: 1 })
+ expect(result).toEqual({ useSingleExec: true, version: 2 })
+ })
+})
diff --git a/services/mcp/tests/workers/fixtures/handlers.ts b/services/mcp/tests/workers/fixtures/handlers.ts
index a2255bc637d7..3b1fa950a419 100644
--- a/services/mcp/tests/workers/fixtures/handlers.ts
+++ b/services/mcp/tests/workers/fixtures/handlers.ts
@@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
+import { strToU8, zipSync } from 'fflate'
import { http, HttpResponse, type JsonBodyType, type RequestHandler, type StrictRequest } from 'msw'
const FIXTURES_DIR = dirname(fileURLToPath(import.meta.url))
@@ -44,6 +45,31 @@ export const handlers: RequestHandler[] = [
http.get('*/api/projects/:projectId/', () => HttpResponse.json(project)),
]
+const contextMillManifest = {
+ version: '1.0.0',
+ resources: [
+ {
+ id: 'test-guide',
+ name: 'PostHog Getting Started',
+ uri: 'posthog://guide/getting-started',
+ resource: {
+ mimeType: 'text/plain',
+ description: 'A guide to getting started with PostHog',
+ text: 'Welcome to PostHog. This is a test resource.',
+ },
+ },
+ ],
+}
+
+const contextMillZip = zipSync({
+ 'manifest.json': strToU8(JSON.stringify(contextMillManifest)),
+})
+
+export const contextMillHandler = http.get(
+ 'https://github.com/PostHog/context-mill/releases/latest/download/skills-mcp-resources.zip',
+ () => new HttpResponse(contextMillZip, { headers: { 'Content-Type': 'application/zip' } })
+)
+
/**
* Dispatch a workerd outbound request to the matching MSW handler. Mirrors
* MSW's internal handler-resolution loop without relying on global fetch
diff --git a/services/mcp/vitest.perf.config.mts b/services/mcp/vitest.perf.config.mts
new file mode 100644
index 000000000000..3e6aeabbddd4
--- /dev/null
+++ b/services/mcp/vitest.perf.config.mts
@@ -0,0 +1,26 @@
+import tsconfigPaths from 'vite-tsconfig-paths'
+import { defineConfig } from 'vitest/config'
+
+export default defineConfig({
+ plugins: [
+ tsconfigPaths({ root: '.' }),
+ {
+ name: 'text-loader',
+ transform(code, id) {
+ if (id.endsWith('.md') || id.endsWith('.html')) {
+ return {
+ code: `export default ${JSON.stringify(code)}`,
+ map: null,
+ }
+ }
+ },
+ },
+ ],
+ test: {
+ globals: true,
+ environment: 'node',
+ testTimeout: 120000,
+ setupFiles: ['tests/hono/setup.ts'],
+ include: ['tests/hono/**/*.perf.ts'],
+ },
+})