:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): proxy to hono (#58950)
Joshua Snyderb12f80fab036
diff --git a/services/mcp/src/hono/mcp-server.ts b/services/mcp/src/hono/mcp-server.tsindex 68b0c7f26a8b..f6875fb4308b 100644--- a/services/mcp/src/hono/mcp-server.ts+++ b/services/mcp/src/hono/mcp-server.ts@@ -28,17 +28,10 @@ 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 CloudRegion, type Context, type Env, type State, type Tool } from '@/tools/types'+import { type Context, type Env, type State, type Tool } from '@/tools/types'import { RedisCache, type RedisLike } from './cache/RedisCache'-import {- getCustomApiBaseUrl,- POSTHOG_EU_BASE_URL,- POSTHOG_US_BASE_URL,- getBaseUrlForRegion,- getEnv,- toCloudRegion,-} from './constants'+import { getCustomApiBaseUrl, getEnv } from './constants'import { initDurationSeconds, toolCallDurationSeconds, toolCallsTotal } from './metrics'export type { RequestProperties }@@ -133,49 +126,15 @@ export class HonoMcpServer {}}- async detectRegion(): Promise<CloudRegion | undefined> {- const usClient = new ApiClient({- apiToken: this.props.apiToken,- baseUrl: POSTHOG_US_BASE_URL,- })-- const euClient = new ApiClient({- apiToken: this.props.apiToken,- baseUrl: POSTHOG_EU_BASE_URL,- })-- const [usResult, euResult] = await Promise.all([usClient.users().me(), euClient.users().me()])-- if (usResult.success) {- await this.cache.set('region', 'us')- return 'us'- }-- if (euResult.success) {- await this.cache.set('region', 'eu')- return 'eu'- }-- return undefined- }-async getBaseUrl(): Promise<string> {const customApiBaseUrl = getCustomApiBaseUrl()if (customApiBaseUrl) {return customApiBaseUrl}-- const propsRegion = this.props.region- if (propsRegion) {- const region = toCloudRegion(propsRegion)- await this.cache.set('region', region)- return getBaseUrlForRegion(region)+ 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.')}-- const cachedRegion = await this.cache.get('region')- const region = cachedRegion ? toCloudRegion(cachedRegion) : await this.detectRegion()-- return getBaseUrlForRegion(region || 'us')+ return 'http://localhost:8010'}async api(): Promise<ApiClient> {@@ -424,13 +383,6 @@ export class HonoMcpServer {}const context = await this.getContext()- // Sticky session: skip default resolution if a previous init for this- // userHash already picked a project (cache survives across requests).- // Without this guard, switching the active org in the user's browser- // would silently reshuffle an established session — `users/@me`- // returns whatever team the browser currently has selected, and- // setDefaultOrganizationAndProject would overwrite the cache with it.- // Headers always win because they were applied to the cache above.if (!cachedProjectId) {cachedProjectId = await this.cache.get('projectId')}diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.tsindex 24837a1b38a3..dd3000f35480 100644--- a/services/mcp/src/index.ts+++ b/services/mcp/src/index.ts@@ -13,6 +13,7 @@ import { hash, parseMcpMode, sanitizeHeaderValue } from '@/lib/utils'import type { CloudRegion } from '@/tools/types'import { MCP, RequestProperties } from './mcp'+import { proxyToHono, shouldProxyToHono } from './proxy'function extendMcpServerLog(log: RequestLogger, props: RequestProperties): void {const mcpServerLog: Record<string, unknown> = {@@ -404,6 +405,11 @@ const handleRequest = async (let server: Promise<Response> | null = nullif (url.pathname.startsWith('/mcp')) {+ const proxyResult = await shouldProxyToHono(token, ctx.props.userHash, env.MCP_KV)+ if (proxyResult.proxy) {+ log.extend({ proxy: 'hono', region: proxyResult.region })+ return proxyToHono(request, proxyResult.region)+ }Object.assign(ctx.props, { transport: 'streamable-http' })server = MCP.serve('/mcp').fetch(request, env, ctx)}diff --git a/services/mcp/src/proxy.ts b/services/mcp/src/proxy.tsnew file mode 100644index 000000000000..f6ed99925103--- /dev/null+++ b/services/mcp/src/proxy.ts@@ -0,0 +1,108 @@+import { ApiClient } from "@/api/client";+import { env } from "@/lib/env";+import { isFeatureFlagEnabled } from "@/lib/posthog/flags";+import type { CloudRegion } from "@/tools/types";++const MCP_HONO_US_URL = "https://mcp.us.posthog.com";+const MCP_HONO_EU_URL = "https://mcp.eu.posthog.com";++const KV_TTL_SECONDS = 7 * 24 * 60 * 60; // 7 days++type ResolvedUser = { distinctId: string; region: CloudRegion };++async function resolveUser(+ token: string,+ userHash: string,+ kv: KVNamespace | undefined,+): Promise<ResolvedUser | undefined> {+ if (kv) {+ const [distinctId, region] = await Promise.all([+ kv.get(`${userHash}:distinct_id`),+ kv.get(`${userHash}:region`),+ ]);+ if (distinctId && region) {+ return { distinctId, region: region as CloudRegion };+ }+ }++ // When POSTHOG_API_BASE_URL is set (local dev), both hit the same server —+ // region always resolves to "us", which is correct since local Hono is a+ // single instance. In production, POSTHOG_API_BASE_URL is not set on the+ // CF worker, so this probes both regions in parallel.+ const usBase = env.POSTHOG_API_BASE_URL || "https://us.posthog.com";+ const euBase = env.POSTHOG_API_BASE_URL || "https://eu.posthog.com";++ const [usResult, euResult] = await Promise.all([+ new ApiClient({ apiToken: token, baseUrl: usBase }).users().me(),+ new ApiClient({ apiToken: token, baseUrl: euBase }).users().me(),+ ]);++ let resolved: ResolvedUser | undefined;+ if (usResult.success) {+ resolved = { distinctId: usResult.data.distinct_id, region: "us" };+ } else if (euResult.success) {+ resolved = { distinctId: euResult.data.distinct_id, region: "eu" };+ }++ if (resolved && kv) {+ await Promise.all([+ kv.put(`${userHash}:distinct_id`, resolved.distinctId, { expirationTtl: KV_TTL_SECONDS }),+ kv.put(`${userHash}:region`, resolved.region, { expirationTtl: KV_TTL_SECONDS }),+ ]);+ }++ return resolved;+}++function getHonoTargetUrl(region: CloudRegion): string {+ if (env.MCP_HONO_URL) {+ return env.MCP_HONO_URL;+ }+ return region === "eu" ? MCP_HONO_EU_URL : MCP_HONO_US_URL;+}++export async function shouldProxyToHono(+ token: string,+ userHash: string,+ kv: KVNamespace | undefined,+): Promise<{ proxy: true; region: CloudRegion } | { proxy: false }> {+ try {+ const user = await resolveUser(token, userHash, kv);+ if (!user) {+ console.info("[MCP proxy] could not resolve user, staying on CF");+ return { proxy: false };+ }+ const enabled = await isFeatureFlagEnabled("mcp-hono", user.distinctId);+ console.info(+ `[MCP proxy] flag mcp-hono=${enabled} for ${userHash.slice(0, 8)}... (${user.region})`,+ );+ if (enabled) {+ return { proxy: true, region: user.region };+ }+ } catch (err) {+ console.error("[MCP proxy] error evaluating proxy:", err);+ }+ return { proxy: false };+}++export function proxyToHono(+ request: Request,+ region: CloudRegion,+): Promise<Response> {+ const targetBase = getHonoTargetUrl(region);+ const targetUrl = new URL(request.url);+ const target = new URL(targetBase);+ targetUrl.hostname = target.hostname;+ targetUrl.protocol = target.protocol;+ targetUrl.port = target.port;++ console.info(+ `[MCP proxy] forwarding ${request.method} to ${targetUrl.toString()}`,+ );++ return fetch(targetUrl.toString(), {+ method: request.method,+ headers: request.headers,+ body: request.body,+ });+}diff --git a/services/mcp/tests/hono/mcp-server.test.ts b/services/mcp/tests/hono/mcp-server.test.tsindex 43fc2e06e880..10fe228fd874 100644--- a/services/mcp/tests/hono/mcp-server.test.ts+++ b/services/mcp/tests/hono/mcp-server.test.ts@@ -53,37 +53,25 @@ describe('HonoMcpServer', () => {})describe('getBaseUrl', () => {- it('should return US base URL by default', async () => {+ 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)- vi.spyOn(server, 'detectRegion').mockResolvedValue(undefined)- const url = await server.getBaseUrl()- expect(url).toBe('https://us.posthog.com')- })-- it('should return EU base URL when region is eu', async () => {- const server = new HonoMcpServer(mockRedis, { ...baseProps, region: 'eu' })const url = await server.getBaseUrl()- expect(url).toBe('https://eu.posthog.com')+ expect(url).toBe('https://custom.posthog.com')})- it('should use cached region when available', async () => {- mockRedis._store.set('mcp:user:test-hash:region', '"eu"')+ it('should default to localhost:8010 in dev when not set', async () => {+ delete process.env.POSTHOG_API_BASE_URLconst server = new HonoMcpServer(mockRedis, baseProps)const url = await server.getBaseUrl()- expect(url).toBe('https://eu.posthog.com')- })-- it('should cache region from props', async () => {- const server = new HonoMcpServer(mockRedis, { ...baseProps, region: 'eu' })- await server.getBaseUrl()- expect(mockRedis.set).toHaveBeenCalledWith('mcp:user:test-hash:region', '"eu"', 'EX', expect.any(Number))+ expect(url).toBe('http://localhost:8010')})- it('should use custom API base URL from env', async () => {- process.env.POSTHOG_API_BASE_URL = 'https://custom.posthog.com'+ 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)- const url = await server.getBaseUrl()- expect(url).toBe('https://custom.posthog.com')+ await expect(server.getBaseUrl()).rejects.toThrow('POSTHOG_API_BASE_URL must be set')})})@@ -127,7 +115,8 @@ describe('HonoMcpServer', () => {describe('api', () => {it('should cache the ApiClient instance', async () => {- const server = new HonoMcpServer(mockRedis, { ...baseProps, region: 'us' })+ 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/types.d.ts b/services/mcp/types.d.tsindex 59148819c25f..2b06e4467367 100644--- a/services/mcp/types.d.ts+++ b/services/mcp/types.d.ts@@ -5,3 +5,12 @@ declare module 'ioredis' {const Redis: anyexport default Redis}++// Custom optional environment variables not generated by Wrangler+declare namespace Cloudflare {+ interface Env {+ MCP_CAT_PROJECT_ID: string | undefined+ MCP_KV: KVNamespace | undefined+ MCP_HONO_URL: string | undefined+ }+}diff --git a/services/mcp/wrangler.jsonc b/services/mcp/wrangler.jsoncindex bacb0c54178e..57baf97b8ec5 100644--- a/services/mcp/wrangler.jsonc+++ b/services/mcp/wrangler.jsonc@@ -27,6 +27,12 @@"tag": "v2",},],+ "kv_namespaces": [+ {+ "binding": "MCP_KV",+ "id": "30a887fff4d04c4fbf979208293ce012",+ },+ ],"durable_objects": {"bindings": [{