: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): harden forwarded header handling (#102051)
Tom Piccirello007e4e99d824
diff --git a/services/mcp/.env.example b/services/mcp/.env.exampleindex a2de58286976..e4b9ad09c706 100644--- a/services/mcp/.env.example+++ b/services/mcp/.env.example@@ -21,6 +21,12 @@ POSTHOG_API_BASE_URL=http://localhost:8010# Base URL for serving MCP UI app static assets (the MCP server's own URL)MCP_APPS_BASE_URL=http://localhost:8787+# Trust X-Forwarded-Host when building the public URL in OAuth metadata and redirects.+# Set this only behind a local tunnel (ngrok, cloudflared) that sets the header, so the+# advertised URL names the tunnel host instead of localhost. Never set it in production:+# nothing in front of the worker or the k8s deployment sets this header.+# MCP_TRUST_FORWARDED_HOST=true+# PostHog base URL for MCP Apps analytics (CSP and event ingestion)POSTHOG_MCP_APPS_ANALYTICS_BASE_URL=http://localhost:8010POSTHOG_UI_APPS_TOKEN=phc_<your_ui_apps_project_api_key>diff --git a/services/mcp/CONTRIBUTING.md b/services/mcp/CONTRIBUTING.mdindex 406111e66eae..cfe15238789e 100644--- a/services/mcp/CONTRIBUTING.md+++ b/services/mcp/CONTRIBUTING.md@@ -382,6 +382,7 @@ The HTML import only works with wrangler's Text rule. If you see this error duri### UI not rendering in Claude Desktop1. Verify the tunnel is running (`cloudflared tunnel --url ...`)+ - If OAuth metadata or the `WWW-Authenticate` challenge names `localhost` instead of the tunnel host, set `MCP_TRUST_FORWARDED_HOST=true` in `.env` (see `.env.example`)2. Check Claude Desktop config has correct URL3. Restart Claude Desktop after config changes4. Verify tool has `_meta.ui.resourceUri` setdiff --git a/services/mcp/src/hono/app.ts b/services/mcp/src/hono/app.tsindex 5974bf234c11..ef3169263f4f 100644--- a/services/mcp/src/hono/app.ts+++ b/services/mcp/src/hono/app.ts@@ -1,6 +1,7 @@import { Hono } from 'hono'import { env } from '@/lib/env'+import { getPublicUrl } from '@/lib/routing'import {loadSigningKeyFromEnv,NonceLedger,@@ -25,7 +26,7 @@ export type App = {}const sseRedirect = (c: HonoCtx): Response => {- const target = new URL(c.req.url)+ const target = getPublicUrl(c.req.raw)target.pathname = '/mcp' + target.pathname.slice('/sse'.length)target.searchParams.set('_deprecated', 'sse')return c.redirect(target.toString(), 308) as unknown as Responsediff --git a/services/mcp/src/index.ts b/services/mcp/src/index.tsindex b263e1467158..5f4f85c8ba67 100644--- a/services/mcp/src/index.ts+++ b/services/mcp/src/index.ts@@ -5,67 +5,12 @@ import { RequestLogger, withLogging } from '@/lib/logging'import { extractClientInfoFromBody } from '@/lib/mcp-client-info'import { corsHeadersForOAuthMetadata, oauthMetadataPreflightResponse } from '@/lib/oauth-metadata-cors'import { RequestProperties } from '@/lib/request-properties'-import { buildRedirectUrl, matchAuthServerRedirect } from '@/lib/routing'+import { buildRedirectUrl, getPublicUrl, getRegionFromRequest, matchAuthServerRedirect } from '@/lib/routing'import { extractBearerToken, hash, parseMcpMode, sanitizeHeaderValue } from '@/lib/utils'import { getAdvertisedOAuthScopes } from '@/tools/toolDefinitions'-import type { CloudRegion } from '@/tools/types'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-// shows http://localhost but the actual URL is https://...ngrok-free.dev-function getPublicUrl(request: Request): URL {- const url = new URL(request.url)-- // Check for X-Forwarded-Host (ngrok, cloudflared, and most reverse proxies)- const forwardedHost = request.headers.get('X-Forwarded-Host')- if (forwardedHost) {- url.host = forwardedHost- }-- // Check for X-Forwarded-Proto (https vs http)- const forwardedProto = request.headers.get('X-Forwarded-Proto')- if (forwardedProto) {- url.protocol = forwardedProto + ':'- }-- return url-}--// Detect region from hostname for EU subdomain routing.-// This is a workaround for Claude Code's OAuth bug where it ignores the-// authorization_servers field from OAuth protected resource metadata and-// instead fetches /.well-known/oauth-authorization-server directly from the MCP server.-// See: https://github.com/anthropics/claude-code/issues/2267-//-// By using a separate subdomain (mcp-eu.posthog.com), Claude Code's request to-// /.well-known/oauth-authorization-server will hit our server with the EU hostname,-// allowing us to redirect to the correct EU OAuth server.-function getRegionFromHostname(request: Request): CloudRegion | undefined {- const publicUrl = getPublicUrl(request)-- // DNS hostnames are case-insensitive, so normalize to lowercase- if (publicUrl.hostname.toLowerCase() === 'mcp-eu.posthog.com') {- return 'eu'- }-- return undefined-}--// Detect region from hostname (mcp-eu.posthog.com) or query param (?region=eu)-// Hostname takes precedence as it's the workaround for Claude Code's OAuth bug-function getRegionFromRequest(request: Request): CloudRegion | null {- const hostnameRegion = getRegionFromHostname(request)- if (hostnameRegion) {- return hostnameRegion- }-- const url = new URL(request.url)- const queryRegion = url.searchParams.get('region') as CloudRegion | null- return queryRegion-}-const handleRequest = async (request: Request,env: Env,diff --git a/services/mcp/src/lib/routing.ts b/services/mcp/src/lib/routing.tsindex 2e50271195b9..5783a759034d 100644--- a/services/mcp/src/lib/routing.ts+++ b/services/mcp/src/lib/routing.ts@@ -1,15 +1,23 @@+import { env } from '@/lib/env'import type { CloudRegion } from '@/tools/types'-// Resolve the public-facing URL for a request, honoring reverse-proxy headers.-// Needed for local dev with ngrok/cloudflared, and for k8s deployments behind an ingress-// where `request.url` is the in-cluster URL but the well-known/RFC-9728 metadata must-// advertise the externally reachable origin.+// In production `request.url` already names the host the client connected to, and nothing in front+// of the worker or the Node server sets X-Forwarded-Host, so any value comes from the client. Only a+// local tunnel (ngrok, cloudflared) needs the header, so it is read only when MCP_TRUST_FORWARDED_HOST+// is set. X-Forwarded-Proto always applies, because the Node server sees http behind a TLS-terminating+// load balancer, and Cloudflare and the load balancer replace any value the client sends.export function getPublicUrl(request: Request): URL {const url = new URL(request.url)- const forwardedHost = request.headers.get('X-Forwarded-Host')+ const forwardedHost = trustForwardedHost() ? request.headers.get('X-Forwarded-Host') : nullif (forwardedHost) {- url.host = forwardedHost+ // Parse the value, so a header that is not a host leaves the URL alone. Assigning `host`+ // on its own would keep the local port, which the public host does not serve.+ const parsed = parseHost(url.protocol, forwardedHost)+ if (parsed) {+ url.host = parsed.host+ url.port = parsed.port+ }}const forwardedProto = request.headers.get('X-Forwarded-Proto')@@ -20,6 +28,19 @@ export function getPublicUrl(request: Request): URL {return url}+function trustForwardedHost(): boolean {+ const value = env.MCP_TRUST_FORWARDED_HOST+ return value === 'true' || value === '1'+}++function parseHost(protocol: string, host: string): URL | null {+ try {+ return new URL(`${protocol}//${host}`)+ } catch {+ return null+ }+}+// Detect region from the request hostname.// This is a workaround for Claude Code's OAuth bug where it ignores the// authorization_servers field from RFC 9728 metadata and instead fetchesdiff --git a/services/mcp/tests/hono/app-routes.test.ts b/services/mcp/tests/hono/app-routes.test.tsindex 754df178d00e..37ab7601a0fc 100644--- a/services/mcp/tests/hono/app-routes.test.ts+++ b/services/mcp/tests/hono/app-routes.test.ts@@ -181,12 +181,9 @@ describe('Hono App Routes', () => {})describe('hostname-based region detection', () => {- it('should detect EU from mcp.eu.posthog.com via X-Forwarded-Host', async () => {+ it('should detect EU from mcp.eu.posthog.com', async () => {const { app } = createApp(mockRedis)- const res = await app.request('/mcp', {- method: 'POST',- headers: { 'X-Forwarded-Host': 'mcp.eu.posthog.com' },- })+ const res = await app.request(new Request('http://mcp.eu.posthog.com/mcp', { method: 'POST' }))expect(res.status).toBe(401)const wwwAuth = res.headers.get('WWW-Authenticate') || ''expect(wwwAuth).toContain('mcp.eu.posthog.com')@@ -202,16 +199,43 @@ describe('Hono App Routes', () => {it('should detect EU from legacy mcp-eu.posthog.com', async () => {const { app } = createApp(mockRedis)- const res = await app.request('/mcp', {- method: 'POST',- headers: { 'X-Forwarded-Host': 'mcp-eu.posthog.com' },- })+ const res = await app.request(new Request('http://mcp-eu.posthog.com/mcp', { method: 'POST' }))expect(res.status).toBe(401)const wwwAuth = res.headers.get('WWW-Authenticate') || ''expect(wwwAuth).toContain('region=eu')})})+ describe('client-sent X-Forwarded-Host', () => {+ const headers = { 'X-Forwarded-Host': 'mcp-eu.posthog.com', 'X-Forwarded-Proto': 'https' }++ it('does not change the resource in protected resource metadata', async () => {+ const { app } = createApp(mockRedis)+ const res = await app.request(+ new Request('http://mcp.us.posthog.com/.well-known/oauth-protected-resource/mcp', { headers })+ )+ expect(res.status).toBe(200)+ const body = (await res.json()) as Record<string, any>+ expect(body.resource).toBe('https://mcp.us.posthog.com/mcp')+ })++ it('does not change the host or region in the 401 challenge', async () => {+ const { app } = createApp(mockRedis)+ const res = await app.request(new Request('http://mcp.us.posthog.com/mcp', { method: 'POST', headers }))+ expect(res.status).toBe(401)+ expect(res.headers.get('WWW-Authenticate')).toBe(+ 'Bearer resource_metadata="https://mcp.us.posthog.com/.well-known/oauth-protected-resource/mcp?region=us"'+ )+ })++ it('does not change the host in the SSE redirect, and keeps the forwarded protocol', async () => {+ const { app } = createApp(mockRedis)+ const res = await app.request(new Request('http://mcp.us.posthog.com/sse', { headers }))+ expect(res.status).toBe(308)+ expect(res.headers.get('location')).toBe('https://mcp.us.posthog.com/mcp?_deprecated=sse')+ })+ })+describe('MCP auth on /mcp', () => {it('should return 401 with WWW-Authenticate when no token', async () => {const { app } = createApp(mockRedis)diff --git a/services/mcp/tests/integration/harness/cf-proxy.ts b/services/mcp/tests/integration/harness/cf-proxy.tsindex 67bf965f5db0..304cad79020d 100644--- a/services/mcp/tests/integration/harness/cf-proxy.ts+++ b/services/mcp/tests/integration/harness/cf-proxy.ts@@ -47,7 +47,8 @@ export async function startCfProxyHarness(env: IntegrationEnv): Promise<Integrat// `cloudflare:workers`'s `env` export. `MCP_HONO_URL` collapses// both per-region targets onto the local Hono. `POSTHOG_API_BASE_URL`// points the worker's token-probe path at the same backend Hono- // talks to.+ // talks to. MCP_TRUST_FORWARDED_HOST stays unset, so the suite runs+ // the production rule: the worker ignores X-Forwarded-Host.vars: {MCP_HONO_URL: hono.baseUrl.toString().replace(/\/$/, ''),POSTHOG_API_BASE_URL: env.apiBaseUrl,diff --git a/services/mcp/tests/integration/proxy.cf.integration.test.ts b/services/mcp/tests/integration/proxy.cf.integration.test.tsindex ae3b1866e1be..1746e0b20b2d 100644--- a/services/mcp/tests/integration/proxy.cf.integration.test.ts+++ b/services/mcp/tests/integration/proxy.cf.integration.test.ts@@ -81,12 +81,13 @@ describe('CF proxy plumbing (real stack)', () => {expect(wwwAuth).toContain('oauth-protected-resource')})- it('detects the EU region from X-Forwarded-Host when building OAuth metadata', async () => {+ it('ignores a client-sent X-Forwarded-Host when building OAuth metadata', async () => {const res = await fetch(new URL('/.well-known/oauth-protected-resource/mcp', harness.baseUrl), {headers: { 'X-Forwarded-Host': 'mcp-eu.posthog.com' },})expect(res.status).toBe(200)- const json = (await res.json()) as { authorization_servers?: string[] }+ const json = (await res.json()) as { resource?: string; authorization_servers?: string[] }+ expect(new URL(json.resource!).host).toBe(new URL(harness.baseUrl).host)expect(Array.isArray(json.authorization_servers)).toBe(true)})diff --git a/services/mcp/tests/unit/routing.test.ts b/services/mcp/tests/unit/routing.test.tsindex ca5480dced17..8932a4158431 100644--- a/services/mcp/tests/unit/routing.test.ts+++ b/services/mcp/tests/unit/routing.test.ts@@ -1,6 +1,72 @@-import { describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it } from 'vitest'-import { matchAuthServerRedirect } from '@/lib/routing'+import { getPublicUrl, getRegionFromRequest, matchAuthServerRedirect } from '@/lib/routing'++describe('getPublicUrl', () => {+ afterEach(() => {+ delete process.env.MCP_TRUST_FORWARDED_HOST+ })++ it.each([undefined, 'false', 'yes'])('keeps the request host when MCP_TRUST_FORWARDED_HOST is %s', (flag) => {+ if (flag !== undefined) {+ process.env.MCP_TRUST_FORWARDED_HOST = flag+ }+ const request = new Request('https://mcp.posthog.com/mcp', {+ headers: { 'X-Forwarded-Host': 'untrusted.example.com' },+ })+ expect(getPublicUrl(request).toString()).toBe('https://mcp.posthog.com/mcp')+ })++ it.each(['true', '1'])('uses X-Forwarded-Host when MCP_TRUST_FORWARDED_HOST is %s', (flag) => {+ process.env.MCP_TRUST_FORWARDED_HOST = flag+ const request = new Request('http://localhost:8787/mcp', {+ headers: { 'X-Forwarded-Host': 'dev-tunnel.example.com', 'X-Forwarded-Proto': 'https' },+ })+ expect(getPublicUrl(request).toString()).toBe('https://dev-tunnel.example.com/mcp')+ })++ it('keeps a port that X-Forwarded-Host carries', () => {+ process.env.MCP_TRUST_FORWARDED_HOST = 'true'+ const request = new Request('http://localhost:8787/mcp', {+ headers: { 'X-Forwarded-Host': 'dev-tunnel.example.com:8443' },+ })+ expect(getPublicUrl(request).toString()).toBe('http://dev-tunnel.example.com:8443/mcp')+ })++ it('ignores an X-Forwarded-Host that is not a host', () => {+ process.env.MCP_TRUST_FORWARDED_HOST = 'true'+ const request = new Request('http://localhost:8787/mcp', {+ headers: { 'X-Forwarded-Host': 'first.example.com, second.example.com' },+ })+ expect(getPublicUrl(request).toString()).toBe('http://localhost:8787/mcp')+ })++ it('applies X-Forwarded-Proto behind a TLS-terminating load balancer', () => {+ const request = new Request('http://mcp.us.posthog.com/mcp', {+ headers: { 'X-Forwarded-Proto': 'https' },+ })+ expect(getPublicUrl(request).toString()).toBe('https://mcp.us.posthog.com/mcp')+ })+})++describe('getRegionFromRequest', () => {+ it.each([+ { url: 'https://mcp-eu.posthog.com/mcp', expected: 'eu' },+ { url: 'https://mcp.eu.posthog.com/mcp', expected: 'eu' },+ { url: 'https://mcp.us.posthog.com/mcp', expected: 'us' },+ { url: 'https://mcp.posthog.com/mcp?region=eu', expected: 'eu' },+ { url: 'https://mcp.posthog.com/mcp', expected: null },+ ])('resolves $url to $expected', ({ url, expected }) => {+ expect(getRegionFromRequest(new Request(url))).toBe(expected)+ })++ it('ignores a region hostname in a client-sent X-Forwarded-Host', () => {+ const request = new Request('https://mcp.posthog.com/mcp', {+ headers: { 'X-Forwarded-Host': 'mcp-eu.posthog.com' },+ })+ expect(getRegionFromRequest(request)).toBeNull()+ })+})describe('Authorization server redirects', () => {const redirectCases = [diff --git a/services/mcp/tests/workers/public-url.test.ts b/services/mcp/tests/workers/public-url.test.tsnew file mode 100644index 000000000000..29f0b66e3149--- /dev/null+++ b/services/mcp/tests/workers/public-url.test.ts@@ -0,0 +1,34 @@+import { SELF } from 'cloudflare:test'+import { describe, expect, it } from 'vitest'++// Cloudflare hands the worker the URL the client connected to. A client-sent+// X-Forwarded-Host must not replace that host in anything the worker advertises.+describe('public URL on the edge worker', () => {+ const headers = { 'X-Forwarded-Host': 'mcp-eu.posthog.com' }++ it('keeps the request host in protected resource metadata', async () => {+ const response = await SELF.fetch('https://mcp.posthog.com/.well-known/oauth-protected-resource/mcp', {+ headers,+ })++ expect(response.status).toBe(200)+ const body = (await response.json()) as { resource: string }+ expect(body.resource).toBe('https://mcp.posthog.com/mcp')+ })++ it('keeps the request host and region in the 401 challenge', async () => {+ const response = await SELF.fetch('https://mcp.posthog.com/mcp', { method: 'POST', headers })++ expect(response.status).toBe(401)+ expect(response.headers.get('WWW-Authenticate')).toBe(+ 'Bearer resource_metadata="https://mcp.posthog.com/.well-known/oauth-protected-resource/mcp"'+ )+ })++ it('keeps the request host in the SSE redirect', async () => {+ const response = await SELF.fetch('https://mcp.posthog.com/sse', { headers, redirect: 'manual' })++ expect(response.status).toBe(308)+ expect(new URL(response.headers.get('location')!).host).toBe('mcp.posthog.com')+ })+})diff --git a/services/mcp/vitest.workers.config.mts b/services/mcp/vitest.workers.config.mtsindex 3a394cb77c5e..4b7f6f392bbd 100644--- a/services/mcp/vitest.workers.config.mts+++ b/services/mcp/vitest.workers.config.mts@@ -28,6 +28,9 @@ export default defineConfig({POSTHOG_ANALYTICS_HOST: '',POSTHOG_MCP_APPS_ANALYTICS_BASE_URL: '',POSTHOG_UI_APPS_TOKEN: '',+ // The worker ignores X-Forwarded-Host in production. A developer who sets+ // this in .env for a tunnel must not change what these tests run.+ MCP_TRUST_FORWARDED_HOST: '',// Generic test marker. Code can short-circuit features// that need real network (e.g. context-mill GitHub// fetch in src/resources/index.ts).