: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(phai): return 403 insufficient_scope on MCP init when OAuth token lacks user:read (#57906)
Georgiy Tarasov2a8c9d8d34b7
diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.tsindex a0dcd0668c00..1395b8865565 100644--- a/services/mcp/src/lib/errors.ts+++ b/services/mcp/src/lib/errors.ts@@ -166,11 +166,12 @@ export function wrapError(message: string, cause: unknown): Error {const PERSONAL_API_KEY_DOCS_URL = 'https://posthog.com/docs/api#how-to-authenticate-with-the-posthog-api'export function formatPermissionErrorMessage(error: PostHogPermissionError): string {+ const callTarget = error.method && error.url ? `${error.method} ${error.url}` : 'this MCP request'if (error.missingScope) {return [`Missing PostHog API scope: '${error.missingScope}'`,'',- `Your Personal API key is missing the '${error.missingScope}' scope, which is required to call ${error.method} ${error.url}.`,+ `Your Personal API key is missing the '${error.missingScope}' scope, which is required to call ${callTarget}.`,'',`To fix: edit the Personal API key in PostHog (User settings → Personal API keys) and add the '${error.missingScope}' scope. Alternatively, select the "MCP Server" scope preset which includes every scope the MCP needs.`,'',@@ -181,7 +182,7 @@ export function formatPermissionErrorMessage(error: PostHogPermissionError): strreturn [`PostHog API permission denied: ${error.detail}`,'',- `The request to ${error.method} ${error.url} was rejected with HTTP 403. Verify that your API key, OAuth token, and user account have access to this project.`,+ `The request to ${callTarget} was rejected with HTTP 403. Verify that your API key, OAuth token, and user account have access to this project.`,].join('\n')}@@ -204,10 +205,31 @@ export function buildInsufficientScopeChallenge(error: PostHogPermissionError):return parts.join(', ')}+// Literal message shape produced by `new PostHogPermissionError({...})`. We+// reconstruct from this when the error has crossed a boundary that strips+// `cause` and the custom subclass prototype — see the fallback in+// `findPostHogPermissionError` for the full reasoning.+const MISSING_SCOPE_MESSAGE_PATTERN = /Missing PostHog API scope: ['"]([^'"]+)['"]/+/*** Walk `Error.cause` chains to find a wrapped PostHogPermissionError.* Tool-level wrappers (e.g. `throw new Error("Failed to X: ...", { cause })`)* hide the underlying permission error, so callers must unwrap before acting.+ *+ * Fallback for the Cloudflare Durable Object RPC boundary: errors thrown+ * inside the DO arrive in the worker as plain Errors — `cause`, the+ * PostHogPermissionError prototype, and any custom own-properties have all+ * been stripped by the cross-isolate serializer, leaving just `name`,+ * `message`, and `stack`. Without this fallback, a permission error from+ * `_fetchUser` (or any other init-time API call) gets mapped to an opaque+ * 500 in `onCatchErrorHandler` and OAuth-aware MCP clients never see the+ * 403 + `WWW-Authenticate: insufficient_scope` they need to re-consent.+ *+ * The literal `Missing PostHog API scope: 'X'` shape produced by the+ * `PostHogPermissionError` constructor is the one piece of information that+ * does survive — we re-synthesize a typed error from it. `url`/`method`+ * are not recoverable from the message alone; `formatPermissionErrorMessage`+ * handles the empty case.*/export function findPostHogPermissionError(error: unknown): PostHogPermissionError | undefined {let current: unknown = error@@ -219,6 +241,20 @@ export function findPostHogPermissionError(error: unknown): PostHogPermissionErrseen.add(current)current = current instanceof Error ? (current as Error & { cause?: unknown }).cause : undefined}++ if (error instanceof Error && typeof error.message === 'string') {+ const match = MISSING_SCOPE_MESSAGE_PATTERN.exec(error.message)+ if (match) {+ const missingScope = match[1]!+ return new PostHogPermissionError({+ detail: `API key missing required scope '${missingScope}'`,+ missingScope,+ url: '',+ method: '',+ })+ }+ }+return undefined}diff --git a/services/mcp/tests/unit/permission-errors.test.ts b/services/mcp/tests/unit/permission-errors.test.tsindex 549b21e751b1..66700ee9aac3 100644--- a/services/mcp/tests/unit/permission-errors.test.ts+++ b/services/mcp/tests/unit/permission-errors.test.ts@@ -166,6 +166,35 @@ describe('findPostHogPermissionError', () => {err.cause = errexpect(findPostHogPermissionError(err)).toBeUndefined()})++ // Cloudflare Durable Object RPC strips Error.cause and the custom subclass+ // prototype on the way out of the DO. Only `name`, `message`, and `stack`+ // survive. Without a message-shape fallback, init-time permission failures+ // get mapped to opaque 500s and OAuth-aware MCP clients never see the+ // 403 + insufficient_scope challenge they need to re-consent.+ describe('boundary-stripped errors (DO RPC fallback)', () => {+ it('reconstructs a PostHogPermissionError from a plain Error whose message carries the missing-scope literal', () => {+ const stripped = new Error("Failed to get user: Missing PostHog API scope: 'user:read'")++ const recovered = findPostHogPermissionError(stripped)++ expect(recovered).toBeInstanceOf(PostHogPermissionError)+ expect(recovered?.missingScope).toBe('user:read')+ })++ it('handles double-quoted scope literal', () => {+ const stripped = new Error('Failed to do thing: Missing PostHog API scope: "insight:write"')++ const recovered = findPostHogPermissionError(stripped)++ expect(recovered?.missingScope).toBe('insight:write')+ })++ it('returns undefined for unrelated error messages even when shape-similar', () => {+ expect(findPostHogPermissionError(new Error('Something about scope but not the literal'))).toBeUndefined()+ expect(findPostHogPermissionError(new Error('Missing PostHog API scope without quotes'))).toBeUndefined()+ })+ })})describe('handleToolError with permission errors', () => {diff --git a/services/mcp/tests/workers/oauth-permission-error-boundary.test.ts b/services/mcp/tests/workers/oauth-permission-error-boundary.test.tsnew file mode 100644index 000000000000..6d324ce5effc--- /dev/null+++ b/services/mcp/tests/workers/oauth-permission-error-boundary.test.ts@@ -0,0 +1,99 @@+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')+ })+})