: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
fix(mcp): redirect to the right place for oauth (#59035)
Joshua Snyder0b08ff81d610
diff --git a/services/mcp/src/hono/mcp-server.ts b/services/mcp/src/hono/mcp-server.tsindex f6875fb4308b..1e82e985ea50 100644--- a/services/mcp/src/hono/mcp-server.ts+++ b/services/mcp/src/hono/mcp-server.ts@@ -132,7 +132,9 @@ export class HonoMcpServer {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.')+ 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'}diff --git a/services/mcp/src/lib/constants.ts b/services/mcp/src/lib/constants.tsindex 302b510a82a9..9278810dfbff 100644--- a/services/mcp/src/lib/constants.ts+++ b/services/mcp/src/lib/constants.ts@@ -1,5 +1,3 @@-import { env } from '@/lib/env'-export {USER_AGENT,type GetUserAgentOptions,@@ -8,6 +6,9 @@ export {POSTHOG_EU_BASE_URL,toCloudRegion,getBaseUrlForRegion,+ getCustomApiBaseUrl,+ isCloudApi,+ isLocalApi,MCP_DOCS_URL,OAUTH_PROXY_URL,OAUTH_SCOPES_SUPPORTED,@@ -15,13 +16,4 @@ export {import { resolveAuthorizationServerUrl } from './oauth-constants'-/**- * Custom API base URL for self-hosted PostHog instances.- *- * WARNING: In PostHog Production, this should NOT be set.- * The code automatically handles US/EU region routing via getAuthorizationServerUrl().- * Only set this for self-hosted PostHog deployments.- */-export const getCustomApiBaseUrl = (): string | undefined => env.POSTHOG_API_BASE_URL--export const getAuthorizationServerUrl = (): string => resolveAuthorizationServerUrl(getCustomApiBaseUrl())+export const getAuthorizationServerUrl = (): string => resolveAuthorizationServerUrl()diff --git a/services/mcp/src/lib/oauth-constants.ts b/services/mcp/src/lib/oauth-constants.tsindex c20705be3f06..2a861e725206 100644--- a/services/mcp/src/lib/oauth-constants.ts+++ b/services/mcp/src/lib/oauth-constants.ts@@ -2,6 +2,7 @@// and Hono entry points. No imports from `cloudflare:workers` or Node-only modules// so this file is safe to import from either runtime.+import { env } from '@/lib/env'import type { CloudRegion } from '@/tools/types'import packageJson from '../../package.json'@@ -59,11 +60,30 @@ export const MCP_DOCS_URL = 'https://posthog.com/docs/model-context-protocol'export const OAUTH_PROXY_URL = 'https://oauth.posthog.com'-// Resolve the OAuth authorization server URL given an optional self-hosted override.-// Each runtime fetches the override from its own env source (CF binding vs process.env)-// and passes it in.-export const resolveAuthorizationServerUrl = (customApiBaseUrl: string | undefined): string => {- return customApiBaseUrl || OAUTH_PROXY_URL+export const getCustomApiBaseUrl = (): string | undefined => env.POSTHOG_API_BASE_URL++const CLOUD_HOSTS = new Set(['us.posthog.com', 'eu.posthog.com'])++export const isCloudApi = (): boolean => {+ const url = getCustomApiBaseUrl()+ if (!url) {+ return true+ }+ try {+ const hostname = new URL(url).hostname+ return CLOUD_HOSTS.has(hostname) || hostname.endsWith('.svc.cluster.local')+ } catch {+ return false+ }+}++export const isLocalApi = (): boolean => !!getCustomApiBaseUrl()?.includes('localhost')++export const resolveAuthorizationServerUrl = (): string => {+ if (isCloudApi()) {+ return OAUTH_PROXY_URL+ }+ return getCustomApiBaseUrl()!}// Generated from `posthog/scopes.py` — keep in sync with `hogli build:openapi`.diff --git a/services/mcp/src/proxy.ts b/services/mcp/src/proxy.tsindex f6ed99925103..ddbcfc988a0f 100644--- a/services/mcp/src/proxy.ts+++ b/services/mcp/src/proxy.ts@@ -1,27 +1,27 @@-import { ApiClient } from "@/api/client";-import { env } from "@/lib/env";-import { isFeatureFlagEnabled } from "@/lib/posthog/flags";-import type { CloudRegion } from "@/tools/types";+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 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+const KV_TTL_SECONDS = 7 * 24 * 60 * 60 // 7 days-type ResolvedUser = { distinctId: string; region: CloudRegion };+type ResolvedUser = { distinctId: string; region: CloudRegion }async function resolveUser(token: string,userHash: string,- kv: KVNamespace | undefined,+ 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 };+ return { distinctId, region: region as CloudRegion }}}@@ -29,80 +29,73 @@ async function resolveUser(// 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 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;+ let resolved: ResolvedUser | undefinedif (usResult.success) {- resolved = { distinctId: usResult.data.distinct_id, region: "us" };+ resolved = { distinctId: usResult.data.distinct_id, region: 'us' }} else if (euResult.success) {- resolved = { distinctId: euResult.data.distinct_id, region: "eu" };+ 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;+ return resolved}function getHonoTargetUrl(region: CloudRegion): string {if (env.MCP_HONO_URL) {- return env.MCP_HONO_URL;+ return env.MCP_HONO_URL}- return region === "eu" ? MCP_HONO_EU_URL : MCP_HONO_US_URL;+ return region === 'eu' ? MCP_HONO_EU_URL : MCP_HONO_US_URL}export async function shouldProxyToHono(token: string,userHash: string,- kv: KVNamespace | undefined,+ kv: KVNamespace | undefined): Promise<{ proxy: true; region: CloudRegion } | { proxy: false }> {try {- const user = await resolveUser(token, userHash, kv);+ const user = await resolveUser(token, userHash, kv)if (!user) {- console.info("[MCP proxy] could not resolve user, staying on CF");- return { proxy: false };+ 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})`,- );+ 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 };+ return { proxy: true, region: user.region }}} catch (err) {- console.error("[MCP proxy] error evaluating proxy:", err);+ console.error('[MCP proxy] error evaluating proxy:', err)}- return { proxy: false };+ 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;+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()}`,- );+ 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/constants.test.ts b/services/mcp/tests/hono/constants.test.tsindex 3f02fac75a38..14d3030fb1bf 100644--- a/services/mcp/tests/hono/constants.test.ts+++ b/services/mcp/tests/hono/constants.test.ts@@ -58,9 +58,24 @@ describe('Hono Constants', () => {})describe('getAuthorizationServerUrl', () => {- it('should return custom URL when POSTHOG_API_BASE_URL is set', () => {- process.env.POSTHOG_API_BASE_URL = 'https://custom.posthog.com'- expect(getAuthorizationServerUrl()).toBe('https://custom.posthog.com')+ it('should return localhost URL when POSTHOG_API_BASE_URL is localhost', () => {+ process.env.POSTHOG_API_BASE_URL = 'http://localhost:8010'+ expect(getAuthorizationServerUrl()).toBe('http://localhost:8010')+ })++ it('should return oauth proxy URL when POSTHOG_API_BASE_URL is a cloud URL', () => {+ process.env.POSTHOG_API_BASE_URL = 'https://us.posthog.com'+ expect(getAuthorizationServerUrl()).toBe('https://oauth.posthog.com')+ })++ it('should return oauth proxy URL when POSTHOG_API_BASE_URL is an internal cluster URL', () => {+ process.env.POSTHOG_API_BASE_URL = 'http://posthog-web-django.posthog.svc.cluster.local:8000'+ expect(getAuthorizationServerUrl()).toBe('https://oauth.posthog.com')+ })++ it('should return self-hosted URL when POSTHOG_API_BASE_URL is a custom domain', () => {+ process.env.POSTHOG_API_BASE_URL = 'https://posthog.example.com'+ expect(getAuthorizationServerUrl()).toBe('https://posthog.example.com')})it('should return oauth proxy URL when no custom URL', () => {diff --git a/services/mcp/tests/integration/global-setup.ts b/services/mcp/tests/integration/global-setup.tsindex a85be6aca9f0..b25c58004b69 100644--- a/services/mcp/tests/integration/global-setup.ts+++ b/services/mcp/tests/integration/global-setup.ts@@ -17,9 +17,7 @@ function uiAppsAlreadyBuilt(): boolean {if (!existsSync(UI_APPS_DIR)) {return false}- return readdirSync(UI_APPS_DIR).some((name) =>- existsSync(resolve(UI_APPS_DIR, name, 'main.js'))- )+ return readdirSync(UI_APPS_DIR).some((name) => existsSync(resolve(UI_APPS_DIR, name, 'main.js')))}export async function setup(): Promise<void> {diff --git a/services/mcp/tests/unit/oauth-region.test.ts b/services/mcp/tests/unit/oauth-region.test.tsindex 921655a86f35..a8565908853a 100644--- a/services/mcp/tests/unit/oauth-region.test.ts+++ b/services/mcp/tests/unit/oauth-region.test.ts@@ -1,8 +1,63 @@-import { describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it } from 'vitest'-import { getAuthorizationServerUrl, getBaseUrlForRegion, toCloudRegion } from '@/lib/constants'+import { getAuthorizationServerUrl, getBaseUrlForRegion, isCloudApi, isLocalApi, toCloudRegion } from '@/lib/constants'describe('OAuth Region Routing', () => {+ const originalEnv = { ...process.env }++ afterEach(() => {+ process.env = { ...originalEnv }+ })++ describe('isLocalApi', () => {+ it('returns true when POSTHOG_API_BASE_URL is localhost', () => {+ process.env.POSTHOG_API_BASE_URL = 'http://localhost:8010'+ expect(isLocalApi()).toBe(true)+ })++ it('returns false when POSTHOG_API_BASE_URL is a cloud URL', () => {+ process.env.POSTHOG_API_BASE_URL = 'https://us.posthog.com'+ expect(isLocalApi()).toBe(false)+ })++ it('returns false when POSTHOG_API_BASE_URL is not set', () => {+ delete process.env.POSTHOG_API_BASE_URL+ expect(isLocalApi()).toBe(false)+ })+ })++ describe('isCloudApi', () => {+ it('returns true when POSTHOG_API_BASE_URL is not set', () => {+ delete process.env.POSTHOG_API_BASE_URL+ expect(isCloudApi()).toBe(true)+ })++ it('returns true for us.posthog.com', () => {+ process.env.POSTHOG_API_BASE_URL = 'https://us.posthog.com'+ expect(isCloudApi()).toBe(true)+ })++ it('returns true for eu.posthog.com', () => {+ process.env.POSTHOG_API_BASE_URL = 'https://eu.posthog.com'+ expect(isCloudApi()).toBe(true)+ })++ it('returns true for internal cluster URL', () => {+ process.env.POSTHOG_API_BASE_URL = 'http://posthog-web-django.posthog.svc.cluster.local:8000'+ expect(isCloudApi()).toBe(true)+ })++ it('returns false for self-hosted domain', () => {+ process.env.POSTHOG_API_BASE_URL = 'https://posthog.example.com'+ expect(isCloudApi()).toBe(false)+ })++ it('returns false for localhost', () => {+ process.env.POSTHOG_API_BASE_URL = 'http://localhost:8010'+ expect(isCloudApi()).toBe(false)+ })+ })+describe('toCloudRegion', () => {it.each([{ input: 'eu', expected: 'eu' },@@ -30,7 +85,28 @@ describe('OAuth Region Routing', () => {})describe('getAuthorizationServerUrl', () => {- it('returns oauth proxy URL', () => {+ it('returns localhost when POSTHOG_API_BASE_URL is localhost', () => {+ process.env.POSTHOG_API_BASE_URL = 'http://localhost:8010'+ expect(getAuthorizationServerUrl()).toBe('http://localhost:8010')+ })++ it('returns oauth proxy URL when POSTHOG_API_BASE_URL is a cloud URL', () => {+ process.env.POSTHOG_API_BASE_URL = 'https://us.posthog.com'+ expect(getAuthorizationServerUrl()).toBe('https://oauth.posthog.com')+ })++ it('returns oauth proxy URL when POSTHOG_API_BASE_URL is an internal cluster URL', () => {+ process.env.POSTHOG_API_BASE_URL = 'http://posthog-web-django.posthog.svc.cluster.local:8000'+ expect(getAuthorizationServerUrl()).toBe('https://oauth.posthog.com')+ })++ it('returns self-hosted URL when POSTHOG_API_BASE_URL is a custom domain', () => {+ process.env.POSTHOG_API_BASE_URL = 'https://posthog.example.com'+ expect(getAuthorizationServerUrl()).toBe('https://posthog.example.com')+ })++ it('returns oauth proxy URL when not set', () => {+ delete process.env.POSTHOG_API_BASE_URLexpect(getAuthorizationServerUrl()).toBe('https://oauth.posthog.com')})})diff --git a/services/mcp/tests/workers/mcp-protocol.test.ts b/services/mcp/tests/workers/mcp-protocol.test.tsindex 04da57e37fa2..cd1ebd2c0722 100644--- a/services/mcp/tests/workers/mcp-protocol.test.ts+++ b/services/mcp/tests/workers/mcp-protocol.test.ts@@ -15,9 +15,7 @@ import { describe, expect, it } from 'vitest'describe('MCP HTTP entry point (Cloudflare Workers)', () => {describe('OAuth Protected Resource Metadata (RFC 9728)', () => {it('returns metadata advertising scopes_supported for /mcp', async () => {- const response = await SELF.fetch(- 'https://mcp.posthog.com/.well-known/oauth-protected-resource/mcp'- )+ const response = await SELF.fetch('https://mcp.posthog.com/.well-known/oauth-protected-resource/mcp')expect(response.status).toBe(200)expect(response.headers.get('content-type')).toContain('application/json')@@ -30,9 +28,7 @@ describe('MCP HTTP entry point (Cloudflare Workers)', () => {})it('returns metadata for /sse with the same shape', async () => {- const response = await SELF.fetch(- 'https://mcp.posthog.com/.well-known/oauth-protected-resource/sse'- )+ const response = await SELF.fetch('https://mcp.posthog.com/.well-known/oauth-protected-resource/sse')expect(response.status).toBe(200)const body = (await response.json()) as Record<string, unknown>@@ -64,10 +60,9 @@ describe('MCP HTTP entry point (Cloudflare Workers)', () => {describe('Authorization server redirects', () => {it('redirects /.well-known/oauth-authorization-server to the auth server', async () => {- const response = await SELF.fetch(- 'https://mcp.posthog.com/.well-known/oauth-authorization-server',- { redirect: 'manual' }- )+ const response = await SELF.fetch('https://mcp.posthog.com/.well-known/oauth-authorization-server', {+ redirect: 'manual',+ })expect(response.status).toBe(302)const location = response.headers.get('location') || ''