: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
feat(mcp): route missing-scope reporting through one helper (#127702)
Rafael Audibert5a32925ff9cd
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.tsindex 8d81a87ed464..3783f214b469 100644--- a/services/mcp/src/api/client.ts+++ b/services/mcp/src/api/client.ts@@ -15,6 +15,7 @@ import {PostHogValidationError,ToolInputValidationError,} from '@/lib/errors'+import { parseInsufficientScopeChallenge } from '@/lib/missing-scope'import { getSearchParamsFromRecord, sanitizeHeaders, sanitizeHeaderValue } from '@/lib/utils.js'import type {ApiEventDefinition,@@ -627,6 +628,7 @@ export class ApiClient {return new PostHogPermissionError({detail: errorData.detail || 'permission denied',missingScope,+ challengeScopes: parseInsufficientScopeChallenge(response.headers.get('WWW-Authenticate')),url,method,})diff --git a/services/mcp/src/hono/dispatcher.ts b/services/mcp/src/hono/dispatcher.tsindex 9f40763b6ba0..ccbf2744787d 100644--- a/services/mcp/src/hono/dispatcher.ts+++ b/services/mcp/src/hono/dispatcher.ts@@ -20,11 +20,12 @@ import type {import GUIDELINES from '@shared/guidelines.md'import { randomUUID } from 'node:crypto'-import { mapErrorToAuthResponse } from '@/lib/auth-errors'+import { mapErrorToAuthResponse, withoutStepUpChallenge } from '@/lib/auth-errors'import { StateLookupCache } from '@/lib/cache/StateLookupCache'import { isLegacyDialectOnlyClient } from '@/lib/client-detection'import { MCP_SERVER_NAME, MCP_SERVER_VERSION } from '@/lib/constants'import { McpSessionResetRequiredError, SESSION_RESET_REQUIRED_REASON } from '@/lib/errors'+import { InsufficientScopeError } from '@/lib/missing-scope'import { resolveFeatureFlagOverrides } from '@/lib/posthog/flags'import type { RequestProperties } from '@/lib/request-properties'import { getPublicUrl } from '@/lib/routing'@@ -359,10 +360,20 @@ class McpDispatcher {return new Response(JSON.stringify(result), { status, headers })}+ // A step-up 403 answers the whole HTTP request and would drop the other items' results, so+ // batch items report a missing scope as a tool error.+ const withoutStepUp = (itemState: ResolvedState | undefined): ResolvedState | undefined =>+ itemState && { ...itemState, supportsStepUp: false }const results = await Promise.all(requests.map(async (request) => {if (!sessionlessBatch) {- return this.dispatch(request, props, state, getPublicUrl(req).origin, carriedContextHandle)+ return this.dispatch(+ request,+ props,+ withoutStepUp(state),+ getPublicUrl(req).origin,+ carriedContextHandle+ )}const itemProps = { ...props }if (request.method === Method.ToolsCall) {@@ -375,7 +386,7 @@ class McpDispatcher {: undefined} catch (error) {if (mapErrorToAuthResponse(error)) {- throw error+ throw withoutStepUpChallenge(error)}console.error('[McpDispatcher] Internal error:', error)return jsonRpcMethodError(request.id, ErrorCode.InternalError, 'Internal error')@@ -383,7 +394,7 @@ class McpDispatcher {return this.dispatch(request,itemProps,- itemState,+ withoutStepUp(itemState),getPublicUrl(req).origin,Boolean(itemProps.mcpSessionId || itemProps.mcpConversationId))@@ -427,6 +438,10 @@ class McpDispatcher {if (error instanceof InterviewRequestError) {return jsonRpcMethodError(id, ErrorCode.InvalidParams, error.message)}+ // A step-up client needs the HTTP 403 and its challenge, not a JSON-RPC error.+ if (error instanceof InsufficientScopeError) {+ throw error+ }console.error('[McpDispatcher] Internal error:', error)return jsonRpcMethodError(id, ErrorCode.InternalError, 'Internal error')}@@ -462,9 +477,13 @@ class McpDispatcher {params? {carriedContextHandle,- resolveConversation: (conversationId) => {+ resolveConversation: async (conversationId) => {props.mcpConversationId = conversationId- return this.stateResolver.resolve(props, state!.reqCtx.lookups)+ const resolved = await this.stateResolver.resolve(props, state!.reqCtx.lookups)+ return {+ ...resolved,+ supportsStepUp: resolved.supportsStepUp && state!.supportsStepUp,+ }},beforeExecute: (callState) =>this.interviewRecruitment.beforeToolCall(diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex 64a042be34df..d8ceb04709d8 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -89,6 +89,7 @@ export interface ResolvedState {heldTools?: ReadonlySet<string> | undefined/** The task a sandbox token is bound to, from token introspection. */sandboxTaskId?: string | undefined+ supportsStepUp: boolean/*** Whether the caller's team may reach third-party MCP tools through `exec`.* Gated on the same flag as the gateway UI — the tools are the gateway's payoff,@@ -372,6 +373,7 @@ export class RequestStateResolver {gatewayToolFilter: { tools, features, excludeTools },heldTools,sandboxTaskId: _apiKey?.sandbox_task_id,+ supportsStepUp: _apiKey?.supports_step_up === true,gatewayToolsEnabled:useSingleExec &&!readOnly &&diff --git a/services/mcp/src/hono/request-utils.ts b/services/mcp/src/hono/request-utils.tsindex 87fa4dd1e3f6..bdd8a2da3076 100644--- a/services/mcp/src/hono/request-utils.ts+++ b/services/mcp/src/hono/request-utils.ts@@ -1,7 +1,12 @@import { getUiCapability, RESOURCE_MIME_TYPE } from '@modelcontextprotocol/ext-apps/server'import { z } from 'zod'-import { classifyAuthFailure, mapErrorToAuthResponse, validateBearerToken } from '@/lib/auth-errors'+import {+ classifyAuthFailure,+ isStepUpChallengeError,+ mapErrorToAuthResponse,+ validateBearerToken,+} from '@/lib/auth-errors'import { getPostHogClient } from '@/lib/posthog'import {type ClientInfo,@@ -141,7 +146,9 @@ export async function authenticateAndParse(}export function handleCatchError(error: unknown, props: RequestProperties): Response {- console.error('[handleCatchError]', error)+ if (!isStepUpChallengeError(error)) {+ console.error('[handleCatchError]', error)+ }const authResponse = mapErrorToAuthResponse(error)if (authResponse) {const reason = authResponse.status === 403 ? 'insufficient_scope' : 'invalid_token'diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.tsindex 7e34624f11f0..59693696cd13 100644--- a/services/mcp/src/index.ts+++ b/services/mcp/src/index.ts@@ -1,4 +1,4 @@-import { isRejectedTokenChallenge, withResourceMetadata } from '@/lib/auth-errors'+import { isInsufficientScopeChallenge, isRejectedTokenChallenge, withResourceMetadata } from '@/lib/auth-errors'import { resolveEffectiveClientName } from '@/lib/client-detection'import { MCP_DOCS_URL, getAuthorizationServerUrl } from '@/lib/constants'import { isIdJagAccessToken } from '@/lib/id-jag'@@ -275,8 +275,13 @@ const handleRequest = async (const region = await resolveProxyRegion(token, ctx.props.userHash, env.MCP_KV)log.extend({ proxy: 'hono', region })const response = await proxyToHono(request, region)- if (isRejectedTokenChallenge(response)) {- log.extend({ authError: 'rejected_token' })+ const authError = isRejectedTokenChallenge(response)+ ? 'rejected_token'+ : isInsufficientScopeChallenge(response)+ ? 'insufficient_scope'+ : undefined+ if (authError) {+ log.extend({ authError })return withResourceMetadata(response, request, effectiveRegion)}return responsediff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.tsindex f12c01df92d2..dd2dd8bda9fe 100644--- a/services/mcp/src/lib/StateManager.ts+++ b/services/mcp/src/lib/StateManager.ts@@ -172,6 +172,7 @@ export class StateManager {...(introspectionResult.data.mcp_allowed_tools? { mcp_allowed_tools: introspectionResult.data.mcp_allowed_tools }: {}),+ ...(introspectionResult.data.supports_step_up === true ? { supports_step_up: true } : {}),}}diff --git a/services/mcp/src/lib/auth-errors.ts b/services/mcp/src/lib/auth-errors.tsindex e8e3856d47e0..f646688ebdce 100644--- a/services/mcp/src/lib/auth-errors.ts+++ b/services/mcp/src/lib/auth-errors.ts@@ -7,28 +7,28 @@import type { CloudRegion } from '@/tools/types'-import {- buildInsufficientScopeChallenge,- ErrorCode,- findPostHogPermissionError,- formatPermissionErrorMessage,-} from './errors'+import { ErrorCode, findPostHogPermissionError, formatPermissionErrorMessage, PostHogPermissionError } from './errors'import { isIdJagAccessToken } from './id-jag'+import { buildInsufficientScopeChallenge, InsufficientScopeError, insufficientScopeResponse } from './missing-scope'import { MCP_DOCS_URL } from './oauth-constants'import { getPublicUrl } from './routing'// Map a thrown error to the appropriate auth response, or null if not auth-related.// Callers handle the null case (typically by emitting observability + returning 500).export function mapErrorToAuthResponse(error: unknown): Response | null {+ if (error instanceof InsufficientScopeError) {+ return insufficientScopeResponse(error.message, error.challenge)+ }+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),- },- })+ // A request can fail here before token introspection has run, so the API's own challenge+ // is the step-up signal. The API sends one only for a token whose app supports step-up,+ // which is the same token flag introspection reports.+ return insufficientScopeResponse(+ formatPermissionErrorMessage(permissionError),+ permissionError.challengeScopes && buildInsufficientScopeChallenge(permissionError.requiredScopes ?? [])+ )}if (error instanceof Error) {@@ -38,6 +38,25 @@ export function mapErrorToAuthResponse(error: unknown): Response | null {return null}+// Other items of a batch may already have run tools, and a step-up client replays the whole+// request after re-consent, so a batch's 403 must not carry the challenge.+export function withoutStepUpChallenge(error: unknown): unknown {+ const permissionError = findPostHogPermissionError(error)+ if (!permissionError?.challengeScopes) {+ return error+ }+ return new PostHogPermissionError({+ detail: permissionError.detail,+ missingScope: permissionError.missingScope,+ url: permissionError.url,+ method: permissionError.method,+ })+}++export function isStepUpChallengeError(error: unknown): boolean {+ return error instanceof InsufficientScopeError || findPostHogPermissionError(error)?.challengeScopes !== undefined+}+export type McpAuthFailureReason =| 'insufficient_scope'| 'inactive_oauth_token'@@ -55,9 +74,15 @@ export interface McpAuthFailure {export function classifyAuthFailure(error: unknown): McpAuthFailure {const status = mapErrorToAuthResponse(error)?.status+ if (error instanceof InsufficientScopeError) {+ return { reason: 'insufficient_scope', status, missingScope: error.requiredScopes.join(' ') }+ }const permissionError = findPostHogPermissionError(error)if (permissionError) {- return { reason: 'insufficient_scope', status, missingScope: permissionError.missingScope }+ const missingScope = permissionError.challengeScopes+ ? permissionError.requiredScopes?.join(' ')+ : permissionError.missingScope+ return { reason: 'insufficient_scope', status, missingScope }}const message = error instanceof Error ? error.message : ''@@ -99,6 +124,13 @@ export function isRejectedTokenChallenge(response: Response): boolean {return response.status === 401 && (response.headers.get('WWW-Authenticate') ?? '').includes('error="invalid_token"')}+export function isInsufficientScopeChallenge(response: Response): boolean {+ return (+ response.status === 403 &&+ (response.headers.get('WWW-Authenticate') ?? '').includes('error="insufficient_scope"')+ )+}+// The worker answers the protected-resource metadata request, so the metadata URL must name the// origin the client connected to, not the regional Hono origin that the proxy rewrites it to.export function withResourceMetadata(diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.tsindex 7d48e6825763..faf432cbf854 100644--- a/services/mcp/src/lib/errors.ts+++ b/services/mcp/src/lib/errors.ts@@ -3,7 +3,6 @@ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'import type { Schemas } from '@/api/generated'import { getPostHogClient } from '@/lib/posthog'import { getToolRecoveryHint } from '@/lib/tool-error-hints'-import { sanitizeHeaderValue } from '@/lib/utils'export enum ErrorCode {INVALID_API_KEY = 'INVALID_API_KEY',@@ -382,6 +381,7 @@ export function parseRetryAfterSeconds(header: string | null): number | null {export interface PostHogPermissionErrorOptions {detail: stringmissingScope?: string | undefined+ challengeScopes?: string[] | undefinedurl: stringmethod: string}@@ -394,6 +394,8 @@ export interface PostHogPermissionErrorOptions {export class PostHogPermissionError extends Error {public readonly detail: stringpublic readonly missingScope: string | undefined+ /** From the API's `insufficient_scope` challenge, which it sends only for a step-up token. */+ public readonly challengeScopes: string[] | undefinedpublic readonly url: stringpublic readonly method: string@@ -405,9 +407,17 @@ export class PostHogPermissionError extends Error {this.name = 'PostHogPermissionError'this.detail = options.detailthis.missingScope = options.missingScope+ this.challengeScopes = options.challengeScopesthis.url = options.urlthis.method = options.method}++ get requiredScopes(): string[] | undefined {+ if (this.challengeScopes?.length) {+ return this.challengeScopes+ }+ return this.missingScope ? [this.missingScope] : undefined+ }}/**@@ -459,25 +469,6 @@ export function formatPermissionErrorMessage(error: PostHogPermissionError): str].join('\n')}-/**- * RFC 6750 §3.1: OAuth 2.0 Bearer challenge for 403 insufficient_scope. When- * a missing scope is known, advertise it so OAuth-aware clients can prompt- * for re-consent with the correct scope instead of reporting a generic error.- */-export function buildInsufficientScopeChallenge(error: PostHogPermissionError): string {- const parts = ['Bearer error="insufficient_scope"']- const scope = sanitizeHeaderValue(error.missingScope)- if (scope) {- parts.push(`scope="${scope}"`)- }- // Replace double quotes to keep the challenge syntactically valid.- const description = sanitizeHeaderValue(error.detail)?.replace(/"/g, "'")- if (description) {- parts.push(`error_description="${description}"`)- }- 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 indiff --git a/services/mcp/src/lib/missing-scope.ts b/services/mcp/src/lib/missing-scope.tsnew file mode 100644index 000000000000..20e18c4af425--- /dev/null+++ b/services/mcp/src/lib/missing-scope.ts@@ -0,0 +1,54 @@+// Decides how a missing OAuth scope reaches the client. A step-up token gets HTTP 403 with an+// RFC 6750 §3.1 challenge, but only from a check that runs before a tool does anything, because+// the client replays the request after re-consent. Everything else gets the tool error over+// HTTP 200 it always got, since other clients treat a 403 as a dead connection.++const OAUTH_SCOPE_TOKEN = /^[\x21\x23-\x5B\x5D-\x7E]+$/++/** Thrown in place of a tool result so the transport answers the request with HTTP 403. */+export class InsufficientScopeError extends Error {+ public readonly challenge: string+ public readonly requiredScopes: readonly string[]++ constructor(requiredScopes: readonly string[]) {+ super(`This request needs the PostHog scopes: ${requiredScopes.join(', ')}`)+ this.name = 'InsufficientScopeError'+ this.challenge = buildInsufficientScopeChallenge(requiredScopes)+ this.requiredScopes = requiredScopes+ }+}++// No `resource_metadata`: Hono sits behind the worker proxy and does not know the origin the+// client connected to, so the worker adds it to the 403 (see `withResourceMetadata`).+export function buildInsufficientScopeChallenge(requiredScopes: readonly string[]): string {+ // RFC 6749 §3.3 limits a scope token to these characters, so nothing that passes can+ // break out of the quoted header value.+ const scopes = [...new Set(requiredScopes)].filter((scope) => OAUTH_SCOPE_TOKEN.test(scope))+ const parts = ['Bearer error="insufficient_scope"']+ if (scopes.length > 0) {+ parts.push(`scope="${scopes.join(' ')}"`)+ }+ return parts.join(', ')+}++export function parseInsufficientScopeChallenge(header: string | null | undefined): string[] | undefined {+ if (!header || !/error="insufficient_scope"/.test(header)) {+ return undefined+ }+ const scope = /(?:^|[\s,])scope="([^"]*)"/.exec(header)?.[1]+ return scope ? scope.split(' ').filter(Boolean) : []+}++export function challengeStepUpBeforeRun(requiredScopes: readonly string[], supportsStepUp: boolean): void {+ if (supportsStepUp) {+ throw new InsufficientScopeError(requiredScopes)+ }+}++export function insufficientScopeResponse(body: string, challenge: string | undefined): Response {+ const headers: Record<string, string> = { 'Content-Type': 'text/plain; charset=utf-8' }+ if (challenge) {+ headers['WWW-Authenticate'] = challenge+ }+ return new Response(body, { status: 403, headers })+}diff --git a/services/mcp/src/schema/api.ts b/services/mcp/src/schema/api.tsindex b292c9bc520e..b00cb4e9be6a 100644--- a/services/mcp/src/schema/api.ts+++ b/services/mcp/src/schema/api.ts@@ -51,6 +51,7 @@ export interface ApiRedactedPersonalApiKey {sandbox_task_id?: string// The tools a run with a picked tool list holds. Absent means no per-tool policy.mcp_allowed_tools?: string[]+ supports_step_up?: boolean}export type ApiOAuthIntrospection =@@ -64,6 +65,7 @@ export type ApiOAuthIntrospection =client_id?: stringsandbox_task_id?: stringmcp_allowed_tools?: string[]+ supports_step_up?: boolean}| {active: falsediff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsindex 3c0a3b0df10b..921f8b88e1b5 100644--- a/services/mcp/tests/hono/analytics.test.ts+++ b/services/mcp/tests/hono/analytics.test.ts@@ -78,6 +78,7 @@ function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {},allTools: [],scopeGatedTools: [],+ supportsStepUp: false,flagGatedTools: [],gatewayToolsEnabled: false,distinctId: 'distinct-id',diff --git a/services/mcp/tests/hono/permission-error-boundary.test.ts b/services/mcp/tests/hono/permission-error-boundary.test.tsindex 17d24b3c3331..1ea650a56f10 100644--- a/services/mcp/tests/hono/permission-error-boundary.test.ts+++ b/services/mcp/tests/hono/permission-error-boundary.test.ts@@ -1,22 +1,24 @@-import { describe, expect, it } from 'vitest'+import { describe, expect, it, vi } from 'vitest'import { handleCatchError } from '@/hono/request-utils'import { PostHogPermissionError, wrapError } from '@/lib/errors'+import { InsufficientScopeError } from '@/lib/missing-scope'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.+// must answer with a 403, not an opaque 500. The 403 carries the RFC 6750+// `insufficient_scope` challenge only when the API challenged a step-up token.-function buildWrappedPermissionError(): Error {+function buildWrappedPermissionError(challengeScopes?: string[]): 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',+ challengeScopes,url: 'https://us.posthog.com/api/users/@me/',method: 'GET',})@@ -26,17 +28,45 @@ function buildWrappedPermissionError(): Error {const props = { userHash: 'abc123', transport: 'streamable-http' } as RequestPropertiesdescribe('handleCatchError permission boundary', () => {- it('maps a wrapped permission error to a 403 insufficient_scope challenge', async () => {- const response = handleCatchError(buildWrappedPermissionError(), props)+ it.each([+ {+ label: 'the API challenged a step-up token',+ challengeScopes: ['user:read', 'organization:read'],+ expectedChallenge: 'Bearer error="insufficient_scope", scope="user:read organization:read"',+ },+ {+ label: 'the API challenged a step-up token without naming scopes',+ challengeScopes: [],+ expectedChallenge: 'Bearer error="insufficient_scope", scope="user:read"',+ },+ { label: 'the token does not support step-up', challengeScopes: undefined, expectedChallenge: null },+ ])('maps a wrapped permission error to a 403 when $label', async ({ challengeScopes, expectedChallenge }) => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})- expect(response.status).toBe(403)+ const response = handleCatchError(buildWrappedPermissionError(challengeScopes), props)++ expect(consoleError).toHaveBeenCalledTimes(expectedChallenge ? 0 : 1)+ consoleError.mockRestore()- const challenge = response.headers.get('www-authenticate')- expect(challenge).toContain('error="insufficient_scope"')- expect(challenge).toContain('scope="user:read"')+ expect(response.status).toBe(403)+ expect(response.headers.get('www-authenticate')).toBe(expectedChallenge)const body = await response.text()expect(body).toContain("'user:read'")expect(body).toContain('MCP Server')})++ it('maps a step-up challenge thrown by a tool call to a 403 carrying it, without logging it as an error', () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})++ const response = handleCatchError(new InsufficientScopeError(['insight:read', 'query:read']), props)++ expect(consoleError).not.toHaveBeenCalled()+ consoleError.mockRestore()++ expect(response.status).toBe(403)+ expect(response.headers.get('www-authenticate')).toBe(+ 'Bearer error="insufficient_scope", scope="insight:read query:read"'+ )+ })})diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsindex 98c8a46f0db3..ff05d3c9a907 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -23,6 +23,7 @@ const {is_impersonated: undefined as boolean | undefined,suppress_analytics: undefined as boolean | undefined,mcp_allowed_tools: undefined as string[] | undefined,+ supports_step_up: undefined as boolean | undefined,},mockSessionScopedStores: new Map<string, Map<string, unknown>>(),// Records the keys passed to every session-scoped refreshTtl call (only the@@ -220,6 +221,7 @@ describe('RequestStateResolver MCP client contexts', () => {mockApiKey.is_impersonated = undefinedmockApiKey.suppress_analytics = undefinedmockApiKey.mcp_allowed_tools = undefined+ mockApiKey.supports_step_up = undefined})it.each([diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex 3ea06ff6a65e..2afd3270aaad 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -17,7 +17,7 @@ import type { ResolvedState } from '@/hono/request-state-resolver'import { ToolCatalog } from '@/hono/tool-catalog'import { ToolExecutor } from '@/hono/tool-executor'import { MCPClientProfile } from '@/lib/client-detection'-import { PostHogApiError } from '@/lib/errors'+import { PostHogApiError, PostHogPermissionError } from '@/lib/errors'import { buildToolDomainsCompact } from '@/lib/instructions'import { CHATGPT_APP_OAUTH_CLIENT_ID } from '@/lib/oauth-constants'import { RENDER_UI_RESOURCE_URI, URI_MAP } from '@/resources/ui-apps.generated'@@ -967,6 +967,52 @@ describe('ToolExecutor', () => {})})+ describe('a missing scope reported by the API', () => {+ let getToolByNameSpy: MockInstance | undefined++ afterEach(() => {+ getToolByNameSpy?.mockRestore()+ getToolByNameSpy = undefined+ })++ function stubToolDeniedWith(error: PostHogPermissionError): void {+ getToolByNameSpy = vi.spyOn(catalog, 'getToolByName').mockReturnValue({+ build() {+ return this.base+ },+ base: {+ schema: z.object({}),+ handler: async () => {+ throw error+ },+ },+ } as any)+ }++ // The client replays the request after re-consent, so a scope the API reports missing+ // after the tool started must not become a step-up 403.+ it('returns the plain tool error to a step-up token when the API reports a missing scope mid-run', async () => {+ stubToolDeniedWith(+ new PostHogPermissionError({+ detail: "API key missing required scope 'person:read'",+ missingScope: 'person:read',+ challengeScopes: ['person:read', 'cohort:read'],+ url: 'https://us.posthog.com/api/projects/1/persons/cohorts/',+ method: 'GET',+ })+ )++ const result = (await executor.handleToolCall(+ { name: 'mock-tool', arguments: {} },+ makeToolExecutorState([{ name: 'mock-tool' }], { supportsStepUp: true })+ )) as any++ expect(result.isError).toBe(true)+ expect(result.content[0].text).toContain("Missing PostHog API scope: 'person:read'")+ expect(result._meta).toBeUndefined()+ })+ })+describe('ignored input keys in tools mode', () => {let getToolByNameSpy: MockInstance | undefineddiff --git a/services/mcp/tests/integration/skill-analytics.integration.test.ts b/services/mcp/tests/integration/skill-analytics.integration.test.tsindex 0a923d55562f..570cbf7c4eb2 100644--- a/services/mcp/tests/integration/skill-analytics.integration.test.ts+++ b/services/mcp/tests/integration/skill-analytics.integration.test.ts@@ -126,6 +126,7 @@ describe.skipIf(!API_TOKEN)('skill read reaches PostHog with $mcp_skill_name', (sessionContext: null,allTools: tools,scopeGatedTools: [],+ supportsStepUp: false,flagGatedTools: [],gatewayToolsEnabled: false,distinctId: 'e2e-distinct-id',diff --git a/services/mcp/tests/shared/test-utils.ts b/services/mcp/tests/shared/test-utils.tsindex c7526a301a00..ed65bd379a14 100644--- a/services/mcp/tests/shared/test-utils.ts+++ b/services/mcp/tests/shared/test-utils.ts@@ -701,6 +701,7 @@ export function makeToolExecutorState(sessionContext: null,allTools: tools as any,scopeGatedTools: [],+ supportsStepUp: false,flagGatedTools: [],gatewayToolsEnabled: false,distinctId: 'test-distinct-id',diff --git a/services/mcp/tests/unit/StateManager.test.ts b/services/mcp/tests/unit/StateManager.test.tsindex a8d0ac936c83..00339db7e095 100644--- a/services/mcp/tests/unit/StateManager.test.ts+++ b/services/mcp/tests/unit/StateManager.test.ts@@ -255,7 +255,12 @@ describe('StateManager', () => {const cacheOnlyApi = { config: { apiToken: 'phx_test' } } as unknown as ApiClientconst cacheOnlyOauthApi = { config: { apiToken: 'pha_test' } } as unknown as ApiClient- function oauthApi(clientName: string | null, impersonated?: boolean, scope = 'insight:read'): ApiClient {+ function oauthApi(+ clientName: string | null,+ impersonated?: boolean,+ scope = 'insight:read',+ supportsStepUp?: boolean+ ): ApiClient {return {config: { apiToken: 'pha_test' },apiKeys: () => ({@@ -269,6 +274,7 @@ describe('StateManager', () => {scope,client_name: clientName,is_impersonated: impersonated,+ supports_step_up: supportsStepUp,},}),}),@@ -301,6 +307,14 @@ describe('StateManager', () => {})+ it.each([true, false, undefined])('reads supports_step_up=%s from introspection', async (supportsStepUp) => {+ stateManager = new StateManager(cache, oauthApi(null, false, 'insight:read', supportsStepUp))++ const result = await stateManager.getApiKey()++ expect(result.supports_step_up === true).toBe(supportsStepUp === true)+ })+it.each([{ scopes: [] }, { scopes: ['scout_experiment_internal:read'] }])('does not suppress personal-key telemetry for scopes $scopes',async ({ scopes }) => {diff --git a/services/mcp/tests/unit/auth-errors.test.ts b/services/mcp/tests/unit/auth-errors.test.tsindex bc937a623567..b4fec99a06d9 100644--- a/services/mcp/tests/unit/auth-errors.test.ts+++ b/services/mcp/tests/unit/auth-errors.test.ts@@ -1,7 +1,16 @@import { describe, expect, it } from 'vitest'-import { isRejectedTokenChallenge, mapKnownErrorMessage, withResourceMetadata } from '@/lib/auth-errors'-import { ErrorCode } from '@/lib/errors'+import {+ classifyAuthFailure,+ isInsufficientScopeChallenge,+ isRejectedTokenChallenge,+ mapErrorToAuthResponse,+ mapKnownErrorMessage,+ withoutStepUpChallenge,+ withResourceMetadata,+} from '@/lib/auth-errors'+import { ErrorCode, PostHogPermissionError } from '@/lib/errors'+import { InsufficientScopeError } from '@/lib/missing-scope'describe('rejected token challenge', () => {it.each([ErrorCode.INVALID_API_KEY, ErrorCode.INACTIVE_OAUTH_TOKEN])(@@ -23,3 +32,37 @@ describe('rejected token challenge', () => {})})++describe('step-up challenge', () => {+ it('points the 403 challenge at the metadata of the origin the client connected to', () => {+ const error = new InsufficientScopeError(['insight:read', 'query:read'])+ const honoResponse = mapErrorToAuthResponse(error)!+ expect(isInsufficientScopeChallenge(honoResponse)).toBe(true)+ expect(classifyAuthFailure(error)).toMatchObject({ missingScope: 'insight:read query:read' })++ const response = withResourceMetadata(honoResponse, new Request('https://mcp.posthog.com/mcp'), null)++ expect(response.status).toBe(403)+ expect(response.headers.get('WWW-Authenticate')).toBe(+ 'Bearer error="insufficient_scope", scope="insight:read query:read", resource_metadata="https://mcp.posthog.com/.well-known/oauth-protected-resource/mcp"'+ )+ })+})++describe('withoutStepUpChallenge', () => {+ it('drops the challenge from a step-up 403 so a batch is not replayed', () => {+ const error = new PostHogPermissionError({+ detail: "API key missing required scope 'user:read'",+ missingScope: 'user:read',+ challengeScopes: ['user:read'],+ url: 'https://us.posthog.com/api/users/@me/',+ method: 'GET',+ })+ expect(mapErrorToAuthResponse(error)!.headers.get('WWW-Authenticate')).not.toBeNull()++ const response = mapErrorToAuthResponse(withoutStepUpChallenge(error))!++ expect(response.status).toBe(403)+ expect(response.headers.get('WWW-Authenticate')).toBeNull()+ })+})diff --git a/services/mcp/tests/unit/permission-errors.test.ts b/services/mcp/tests/unit/permission-errors.test.tsindex 9d12d31d845b..b58be5656e21 100644--- a/services/mcp/tests/unit/permission-errors.test.ts+++ b/services/mcp/tests/unit/permission-errors.test.ts@@ -2,7 +2,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import { ApiClient } from '@/api/client'import {- buildInsufficientScopeChallenge,findPostHogPermissionError,formatPermissionErrorMessage,handleToolError,@@ -11,6 +10,7 @@ import {PostHogValidationError,wrapError,} from '@/lib/errors'+import { buildInsufficientScopeChallenge } from '@/lib/missing-scope'const captureException = vi.fn()vi.mock('@/lib/posthog', () => ({@@ -101,45 +101,17 @@ describe('formatPermissionErrorMessage', () => {})describe('buildInsufficientScopeChallenge', () => {- it('follows RFC 6750 §3.1 when a scope is known', () => {- const error = new PostHogPermissionError({- detail: "API key missing required scope 'user:read'",- missingScope: 'user:read',- url: 'https://us.posthog.com/api/users/@me/',- method: 'GET',- })-- expect(buildInsufficientScopeChallenge(error)).toBe(- 'Bearer error="insufficient_scope", scope="user:read", error_description="API key missing required scope \'user:read\'"'+ it('names every required scope in one RFC 6750 §3.1 challenge', () => {+ expect(buildInsufficientScopeChallenge(['person:read', 'cohort:read', 'person:read'])).toBe(+ 'Bearer error="insufficient_scope", scope="person:read cohort:read"')})- it('omits scope when unknown', () => {- const error = new PostHogPermissionError({- detail: 'team access denied',- url: 'https://us.posthog.com/api/projects/1/',- method: 'GET',- })-- expect(buildInsufficientScopeChallenge(error)).toBe(- 'Bearer error="insufficient_scope", error_description="team access denied"'+ it('drops a value that is not an OAuth scope token, so it cannot break the header', () => {+ expect(buildInsufficientScopeChallenge(['user:read', 'bad" scope', 'x\ny'])).toBe(+ 'Bearer error="insufficient_scope", scope="user:read"')})-- it('strips control chars and balances quotes in detail', () => {- const error = new PostHogPermissionError({- detail: 'hi "there"\nthis is bad',- missingScope: 'user:read',- url: 'https://us.posthog.com/api/users/@me/',- method: 'GET',- })-- const header = buildInsufficientScopeChallenge(error)- // Double quotes inside error_description must be swapped out and newlines dropped.- expect(header).not.toMatch(/"there"/)- expect(header).not.toMatch(/\n/)- expect(header).toContain(`error_description="hi 'there'this is bad"`)- })})describe('findPostHogPermissionError', () => {@@ -268,12 +240,22 @@ describe('ApiClient fetchJson on 403 permission_denied', () => {vi.restoreAllMocks()})- it('throws PostHogPermissionError with the parsed missingScope', async () => {+ it.each([+ { label: 'no challenge', challenge: undefined, challengeScopes: undefined },+ {+ label: 'a step-up challenge',+ challenge: 'Bearer error="insufficient_scope", scope="user:read organization:read"',+ challengeScopes: ['user:read', 'organization:read'],+ },+ ])('throws PostHogPermissionError with the parsed scopes for $label', async ({ challenge, challengeScopes }) => {const mockFetch = vi.fn().mockResolvedValue(new Response(permissionDeniedBody, {status: 403,statusText: 'Forbidden',- headers: { 'Content-Type': 'application/json' },+ headers: {+ 'Content-Type': 'application/json',+ ...(challenge ? { 'WWW-Authenticate': challenge } : {}),+ },}))vi.stubGlobal('fetch', mockFetch)@@ -292,6 +274,7 @@ describe('ApiClient fetchJson on 403 permission_denied', () => {expect(result.error).toBeInstanceOf(PostHogPermissionError)const permissionError = result.error as PostHogPermissionErrorexpect(permissionError.missingScope).toBe('user:read')+ expect(permissionError.challengeScopes).toEqual(challengeScopes)expect(permissionError.method).toBe('GET')expect(permissionError.url).toBe('https://us.posthog.com/api/users/@me/')