: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
chore(mcp): always route /mcp to hono, drop mcp-hono flag gating (#61703)
Georgiy Tarasov2297883539eb
diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.tsindex 8d4907295673..202d889f61a2 100644--- a/services/mcp/src/index.ts+++ b/services/mcp/src/index.ts@@ -1,36 +1,13 @@import { MCP_DOCS_URL, OAUTH_SCOPES_SUPPORTED, getAuthorizationServerUrl } from '@/lib/constants'-import {- buildInsufficientScopeChallenge,- ErrorCode,- findPostHogPermissionError,- formatPermissionErrorMessage,-} from '@/lib/errors'import { isIdJagAccessToken } from '@/lib/id-jag'import { RequestLogger, withLogging } from '@/lib/logging'import { extractClientInfoFromBody } from '@/lib/mcp-client-info'-import { getPostHogClient } from '@/lib/posthog'-import { MCP_ANALYTICS_VERSION } from '@/lib/posthog/analytics'import { buildRedirectUrl, matchAuthServerRedirect } from '@/lib/routing'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> = {- ...(props.mcpAnalyticsInitAction ? { mcpAnalyticsInitAction: props.mcpAnalyticsInitAction } : {}),- ...(props.mcpAnalyticsInitReason ? { mcpAnalyticsInitReason: props.mcpAnalyticsInitReason } : {}),- ...(props.mcpAnalyticsInitErrorName ? { mcpAnalyticsInitErrorName: props.mcpAnalyticsInitErrorName } : {}),- ...(props.mcpAnalyticsInitErrorMessage- ? { mcpAnalyticsInitErrorMessage: props.mcpAnalyticsInitErrorMessage }- : {}),- }-- if (Object.keys(mcpServerLog).length > 0) {- log.extend(mcpServerLog)- }-}+import { RequestProperties } from './mcp'+import { proxyToHono, resolveProxyRegion } from './proxy'// Helper to get the public-facing URL, respecting reverse proxy headers// This is needed for local development with ngrok/cloudflared where request.url@@ -86,78 +63,6 @@ function getRegionFromRequest(request: Request): CloudRegion | null {return queryRegion}-// Detect error codes and return appropriate responses-const onThenErrorHandler = async (response: Response): Promise<Response> => {- if (!response.ok) {- const body = await response.clone().text()- const errorResponse = generateErrorResponseFromMessage(body)- if (errorResponse) {- return errorResponse- }- }-- return response-}--const onCatchErrorHandler = async (- error: Error,- log: RequestLogger,- ctx: ExecutionContext<RequestProperties>-): Promise<Response> => {- const permissionError = findPostHogPermissionError(error)- if (permissionError) {- return new Response(formatPermissionErrorMessage(permissionError), {- status: 403,- headers: {- 'Content-Type': 'text/plain; charset=utf-8',- 'WWW-Authenticate': buildInsufficientScopeChallenge(permissionError),- },- })- }-- const knownErrorResponse = generateErrorResponseFromMessage(error.message)- if (knownErrorResponse) {- return knownErrorResponse- }-- // Unrecognized error → opaque 500 to the client. Surface the underlying- // error in the wide log and PostHog so we can debug without scraping CF- // request traces.- log.extend({- errorName: error?.name,- errorMessage: error?.message,- errorStack: error?.stack,- })-- try {- const client = getPostHogClient()- const distinctId = ctx.props?.userHash- client.captureException(error, distinctId, {- team: 'posthog_ai',- source: 'mcp_request_handler',- mcp_transport: ctx.props?.transport,- mcp_version: MCP_ANALYTICS_VERSION,- has_organization_id: !!ctx.props?.organizationId,- has_project_id: !!ctx.props?.projectId,- })- ctx.waitUntil(client.flush())- } catch {- // Never let observability break the request.- }-- return new Response('Internal server error', { status: 500 })-}--const generateErrorResponseFromMessage = (message: string): Response | null => {- if (message.includes(ErrorCode.INACTIVE_OAUTH_TOKEN)) {- return new Response('OAuth token is inactive', { status: 401 })- } else if (message.includes(ErrorCode.INVALID_API_KEY)) {- return new Response('Invalid API key', { status: 401 })- }-- return null-}-const handleRequest = async (request: Request,env: Env,@@ -413,28 +318,10 @@ const handleRequest = async (Object.assign(ctx.props, { viaSseRedirect: true })}- 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)- }-- if (server !== null) {- return server- .then(async (response) => {- const handledResponse = await onThenErrorHandler(response)- extendMcpServerLog(log, ctx.props)- return handledResponse- })- .catch((error: Error) => {- extendMcpServerLog(log, ctx.props)- return onCatchErrorHandler(error, log, ctx)- })+ const region = await resolveProxyRegion(token, ctx.props.userHash, env.MCP_KV)+ log.extend({ proxy: 'hono', region })+ return proxyToHono(request, region)}log.extend({ error: 'route_not_found' })diff --git a/services/mcp/src/proxy.ts b/services/mcp/src/proxy.tsindex ddbcfc988a0f..c3d7c6d7e936 100644--- a/services/mcp/src/proxy.ts+++ b/services/mcp/src/proxy.ts@@ -1,6 +1,5 @@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'@@ -61,26 +60,21 @@ function getHonoTargetUrl(region: CloudRegion): string {return region === 'eu' ? MCP_HONO_EU_URL : MCP_HONO_US_URL}-export async function shouldProxyToHono(+export async function resolveProxyRegion(token: string,userHash: string,kv: KVNamespace | undefined-): Promise<{ proxy: true; region: CloudRegion } | { proxy: false }> {+): Promise<CloudRegion> {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 }+ if (user) {+ return user.region}+ console.info('[MCP proxy] could not resolve user region, defaulting to us')} catch (err) {- console.error('[MCP proxy] error evaluating proxy:', err)+ console.error('[MCP proxy] error resolving region:', err)}- return { proxy: false }+ return 'us'}export function proxyToHono(request: Request, region: CloudRegion): Promise<Response> {@@ -91,8 +85,6 @@ export function proxyToHono(request: Request, region: CloudRegion): Promise<ResptargetUrl.protocol = target.protocoltargetUrl.port = target.port- console.info(`[MCP proxy] forwarding ${request.method} to ${targetUrl.toString()}`)-return fetch(targetUrl.toString(), {method: request.method,headers: request.headers,diff --git a/services/mcp/tests/hono/permission-error-boundary.test.ts b/services/mcp/tests/hono/permission-error-boundary.test.tsnew file mode 100644index 000000000000..17d24b3c3331--- /dev/null+++ b/services/mcp/tests/hono/permission-error-boundary.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest'++import { handleCatchError } from '@/hono/request-utils'+import { PostHogPermissionError, wrapError } from '@/lib/errors'+import type { RequestProperties } from '@/lib/request-properties'++// All `/mcp` traffic now flows through the Hono request path, so the OAuth+// permission-error boundary lives here (`handleCatchError`) rather than at the+// old CF worker → durable-object edge. When init or tool work throws a+// permission error — e.g. a CIMD/DCR token missing `user:read` — the boundary+// must answer with a 403 + RFC 6750 `insufficient_scope` challenge so+// OAuth-aware MCP clients can re-consent, not an opaque 500.++function buildWrappedPermissionError(): Error {+ // Same shape as the StateManager `_fetchUser` path: a generic Error wrapping+ // the typed PostHogPermissionError as its cause.+ const original = new PostHogPermissionError({+ detail: "API key missing required scope 'user:read'",+ missingScope: 'user:read',+ url: 'https://us.posthog.com/api/users/@me/',+ method: 'GET',+ })+ return wrapError(`Failed to get user: ${original.message}`, original)+}++const props = { userHash: 'abc123', transport: 'streamable-http' } as RequestProperties++describe('handleCatchError permission boundary', () => {+ it('maps a wrapped permission error to a 403 insufficient_scope challenge', async () => {+ const response = handleCatchError(buildWrappedPermissionError(), props)++ expect(response.status).toBe(403)++ const challenge = response.headers.get('www-authenticate')+ expect(challenge).toContain('error="insufficient_scope"')+ expect(challenge).toContain('scope="user:read"')++ const body = await response.text()+ expect(body).toContain("'user:read'")+ expect(body).toContain('MCP Server')+ })+})diff --git a/services/mcp/tests/integration/mcp-protocol.cf.integration.test.ts b/services/mcp/tests/integration/mcp-protocol.cf.integration.test.tsindex fd8b1cc1325c..9f294ace0058 100644--- a/services/mcp/tests/integration/mcp-protocol.cf.integration.test.ts+++ b/services/mcp/tests/integration/mcp-protocol.cf.integration.test.ts@@ -1,4 +1,4 @@-import { afterAll, beforeAll } from 'vitest'+import { afterAll, beforeAll, describe } from 'vitest'import { startCfHarness } from './harness/cf'import { loadIntegrationEnv, type IntegrationEnv, type IntegrationHarness } from './harness/types'@@ -55,10 +55,20 @@ const harnessFor = (): ProtocolTestHarness => ({publicRoutes: false,})-defineMcpProtocolTests('Cloudflare Workers (real stack)', harnessFor)-defineResilienceTests('Cloudflare Workers (real stack)', harnessFor)-defineUiAppProtocolTests('Cloudflare Workers (real stack)', harnessFor)+// The worker now proxies all `/mcp` traffic to the Hono runtime instead of+// serving it locally via the durable object, so these serving suites no longer+// exercise the worker. The same protocol behavior is covered against the+// runtime that actually serves it in `mcp-protocol.hono.integration.test.ts`.+// Skipped (not removed) until the durable object itself is retired.+describe.skip('Cloudflare Workers serving (now proxied to Hono)', () => {+ defineMcpProtocolTests('Cloudflare Workers (real stack)', harnessFor)+ defineResilienceTests('Cloudflare Workers (real stack)', harnessFor)+ defineUiAppProtocolTests('Cloudflare Workers (real stack)', harnessFor)+ defineResourceCatalogTests('Cloudflare Workers (real stack)', harnessFor)+ defineToolBehaviorTests('Cloudflare Workers (real stack)', harnessFor)+ defineCatalogFilterTests('Cloudflare Workers (real stack)', harnessFor)+})++// The worker still enforces the bearer-token boundary before any proxying, so+// these 401 assertions remain valid against the real worker.defineAuthTests('Cloudflare Workers (real stack)', harnessFor)-defineResourceCatalogTests('Cloudflare Workers (real stack)', harnessFor)-defineToolBehaviorTests('Cloudflare Workers (real stack)', harnessFor)-defineCatalogFilterTests('Cloudflare Workers (real stack)', harnessFor)diff --git a/services/mcp/tests/workers/oauth-permission-error-boundary.test.ts b/services/mcp/tests/workers/oauth-permission-error-boundary.test.tsdeleted file mode 100644index 6d324ce5effc..000000000000--- a/services/mcp/tests/workers/oauth-permission-error-boundary.test.ts+++ /dev/null@@ -1,99 +0,0 @@-import { SELF } from 'cloudflare:test'-import { afterEach, describe, expect, it, vi } from 'vitest'--import { PostHogPermissionError, wrapError } from '@/lib/errors'-import { StateManager } from '@/lib/StateManager'--// End-to-end worker → durable-object → boundary test for the bug reported-// against `https://mcp.posthog.com/mcp`: an OAuth-issued bearer token-// (DCR or CIMD, prefix `pha_`) on the JSON-RPC `initialize` request returns-// HTTP 500 / `Internal server error` instead of a structured 403-// `insufficient_scope` challenge when the token lacks a scope that MCP-// `init()` needs (e.g. `user:read` for `_fetchUser`).-//-// Personal API keys (`phx_`) work because they're issued with the full-// "MCP Server" scope preset; CIMD/DCR tokens carry only the scopes the-// client app declared in its registration, so they regularly miss-// `user:read` and trip the `_fetchUser → wrapError(..., PostHogPermissionError)`-// path inside the durable object.-//-// Hypothesis under test: `findPostHogPermissionError` (errors.ts:212) walks-// the `Error.cause` chain looking for an `instanceof PostHogPermissionError`,-// but the Cloudflare DO RPC boundary serializes thrown errors and drops both-// `cause` and the custom-subclass prototype. The detector returns undefined,-// `onCatchErrorHandler` falls through to the "unrecognized error → opaque-// 500" branch (index.ts), and the OAuth-aware client never receives the-// 403 + `WWW-Authenticate: Bearer error="insufficient_scope"` it needs to-// trigger re-consent.--const initializeBody = JSON.stringify({- jsonrpc: '2.0',- id: 1,- method: 'initialize',- params: {- protocolVersion: '2025-03-26',- capabilities: {},- clientInfo: { name: 'Neptune', version: '1.0.0' },- },-})--function buildWrappedPermissionError(): Error {- // Same shape as `_fetchUser` (StateManager.ts:25): a generic Error wrapping- // the typed PostHogPermissionError as its cause. Inside the DO this object- // walks just fine; across the RPC boundary the cause and prototype are gone.- const original = new PostHogPermissionError({- detail: "API key missing required scope 'user:read'",- missingScope: 'user:read',- url: 'https://us.posthog.com/api/users/@me/',- method: 'GET',- })- return wrapError(`Failed to get user: ${original.message}`, original)-}--describe('OAuth permission errors thrown inside the MCP durable object', () => {- afterEach(() => {- vi.restoreAllMocks()- })-- it('initialize with a CIMD/DCR token missing user:read returns 403 with insufficient_scope challenge', async () => {- // Force the DO's init() path to fail the way a CIMD/DCR token without- // `user:read` does in production: getApiKey resolves cleanly (OAuth- // introspection says the token is active), then getUser throws the- // wrapped PostHogPermissionError that `_fetchUser` constructs.- vi.spyOn(StateManager.prototype, 'getApiKey').mockResolvedValue({- scopes: [],- scoped_teams: [],- scoped_organizations: [],- })- vi.spyOn(StateManager.prototype, 'getUser').mockImplementation(async () => {- throw buildWrappedPermissionError()- })-- const response = await SELF.fetch('https://mcp.posthog.com/mcp', {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- Accept: 'application/json, text/event-stream',- Authorization: 'Bearer pha_test_oauth_token_for_dcr_client',- },- body: initializeBody,- })- // Drain the body so the response stream is closed before the test- // teardown pops the DO storage frame.- const body = await response.text()-- // The fix: insufficient-scope responses must be 403 (RFC 6750 §3.1)- // so MCP-SDK clients can recover. 500 here is the bug — a generic- // server error short-circuits the SDK's `auth()` recovery branch- // and the user sees "Internal server error" forever.- expect(response.status).toBe(403)-- const challenge = response.headers.get('www-authenticate')- expect(challenge).toBeTruthy()- expect(challenge).toContain('error="insufficient_scope"')- expect(challenge).toContain('scope="user:read"')-- expect(body).toContain("'user:read'")- expect(body).toContain('MCP Server')- })-})