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.

fix(mcp): route tokens without user:read to their home region (#115851)

posthog[bot]1adc583d1a29
diff --git a/services/mcp/src/proxy.ts b/services/mcp/src/proxy.ts
index 39fcd50ea576..2b88e9375e1a 100644
--- a/services/mcp/src/proxy.ts
+++ b/services/mcp/src/proxy.ts
@@ -6,6 +6,7 @@ import {
signedClientIpHeaders,
} from '@/lib/client-ip-signature'
import { env } from '@/lib/env'
+import { findPostHogPermissionError } from '@/lib/errors'
import type { CloudRegion } from '@/tools/types'
const MCP_HONO_US_URL = 'https://mcp.us.posthog.com'
@@ -13,20 +14,19 @@ 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(
+async function resolveRegion(
token: string,
userHash: string,
kv: KVNamespace | undefined
-): Promise<ResolvedUser | undefined> {
+): Promise<CloudRegion | 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 }
+ try {
+ const region = await kv.get(`${userHash}:region`)
+ if (region) {
+ return region as CloudRegion
+ }
+ } catch (err) {
+ console.error('[MCP proxy] error reading cached region:', err)
}
}
@@ -42,21 +42,29 @@ async function resolveUser(
new ApiClient({ apiToken: token, baseUrl: euBase }).users().me(),
])
- let resolved: ResolvedUser | undefined
+ // Only the home region answers 403 (token known, `user:read` missing). The other region answers
+ // 401, which would make the client refresh a valid token forever.
+ let region: CloudRegion | undefined
if (usResult.success) {
- resolved = { distinctId: usResult.data.distinct_id, region: 'us' }
+ region = 'us'
} else if (euResult.success) {
- resolved = { distinctId: euResult.data.distinct_id, region: 'eu' }
+ region = 'eu'
+ } else if (findPostHogPermissionError(usResult.error)) {
+ region = 'us'
+ } else if (findPostHogPermissionError(euResult.error)) {
+ 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 }),
- ])
+ if (region && kv) {
+ // A failed cache write must not discard the region the probes resolved.
+ try {
+ await kv.put(`${userHash}:region`, region, { expirationTtl: KV_TTL_SECONDS })
+ } catch (err) {
+ console.error('[MCP proxy] error caching region:', err)
+ }
}
- return resolved
+ return region
}
function getHonoTargetUrl(region: CloudRegion): string {
@@ -72,9 +80,9 @@ export async function resolveProxyRegion(
kv: KVNamespace | undefined
): Promise<CloudRegion> {
try {
- const user = await resolveUser(token, userHash, kv)
- if (user) {
- return user.region
+ const region = await resolveRegion(token, userHash, kv)
+ if (region) {
+ return region
}
console.info('[MCP proxy] could not resolve user region, defaulting to us')
} catch (err) {
diff --git a/services/mcp/tests/unit/proxy.test.ts b/services/mcp/tests/unit/proxy.test.ts
new file mode 100644
index 000000000000..893f1f4ac72d
--- /dev/null
+++ b/services/mcp/tests/unit/proxy.test.ts
@@ -0,0 +1,63 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { resolveProxyRegion } from '@/proxy'
+
+const OK = { status: 200, body: { distinct_id: 'user-1' } }
+const UNAUTHORIZED = { status: 401, body: { detail: 'Invalid access token.' } }
+const MISSING_SCOPE = {
+ status: 403,
+ body: {
+ type: 'authentication_error',
+ code: 'permission_denied',
+ detail: "API key missing required scope 'user:read'",
+ },
+}
+
+type ProbeResponse = { status: number; body: unknown }
+
+function stubRegions(us: ProbeResponse, eu: ProbeResponse): void {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: string | URL | Request) => {
+ const url = input instanceof Request ? input.url : String(input)
+ const { status, body } = url.includes('eu.posthog.com') ? eu : us
+ return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
+ })
+ )
+}
+
+describe('resolveProxyRegion', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ it.each([
+ ['a US token', OK, UNAUTHORIZED, 'us'],
+ ['an EU token', UNAUTHORIZED, OK, 'eu'],
+ ['a US token without user:read', MISSING_SCOPE, UNAUTHORIZED, 'us'],
+ ['an EU token without user:read', UNAUTHORIZED, MISSING_SCOPE, 'eu'],
+ ])('routes %s to its home region', async (_, us, eu, expected) => {
+ stubRegions(us, eu)
+ const kv = { get: vi.fn(async () => null), put: vi.fn(async () => undefined) }
+
+ expect(await resolveProxyRegion('pha_test', 'hash', kv as unknown as KVNamespace)).toBe(expected)
+ expect(kv.put).toHaveBeenCalledWith('hash:region', expected, expect.anything())
+ })
+
+ it.each([
+ [
+ 'the cache read fails',
+ { get: vi.fn(async () => Promise.reject(new Error('kv down'))), put: vi.fn(async () => undefined) },
+ ],
+ [
+ 'the cache write fails',
+ { get: vi.fn(async () => null), put: vi.fn(async () => Promise.reject(new Error('kv down'))) },
+ ],
+ ])('still routes an EU token without user:read to EU when %s', async (_, kv) => {
+ stubRegions(UNAUTHORIZED, MISSING_SCOPE)
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+
+ expect(await resolveProxyRegion('pha_test', 'hash', kv as unknown as KVNamespace)).toBe('eu')
+ })
+})