: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): check tool scopes before a tool call runs (#127703)
Rafael Audibertf693f9bd0e16
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex d8ceb04709d8..da0f582fa0cb 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -80,6 +80,7 @@ export interface ResolvedState {sessionContext: MCPSessionContext | nullallTools: Tool<ZodObjectAny>[]scopeGatedTools: ScopeGatedTool[]+ findScopeGatedTool: (name: string) => ScopeGatedTool | undefinedflagGatedTools: FlagGatedTool[]/*** The tools a scout run with a picked tool list holds, from token introspection.@@ -345,6 +346,14 @@ export class RequestStateResolver {// Scope-gated hints are only consumed by the exec `search` command, which// only exists in single-exec mode — skip the extra scan otherwise.const scopeGatedTools = useSingleExec ? getScopeGatedTools(apiKeyScopes, filterOptions).filter(isHeld) : []+ // A call to a gated tool reports the missing scope before the tool runs. Tools mode builds+ // the list only on the first miss instead of scanning the catalog on every request.+ let toolsModeScopeGatedTools: ScopeGatedTool[] | undefined+ const findScopeGatedTool = (name: string): ScopeGatedTool | undefined =>+ (useSingleExec+ ? scopeGatedTools+ : (toolsModeScopeGatedTools ??= getScopeGatedTools(apiKeyScopes, filterOptions).filter(isHeld))+ ).find((tool) => tool.name === name)// Only exec redirects a call to a gated tool; tools mode just omits it.const flagGatedTools = useSingleExec ? getFlagGatedTools(filterOptions).filter(isHeld) : []@@ -369,6 +378,7 @@ export class RequestStateResolver {sessionContext,allTools,scopeGatedTools,+ findScopeGatedTool,flagGatedTools,gatewayToolFilter: { tools, features, excludeTools },heldTools,diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex c5c749b95e20..8e868ecf7202 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -27,6 +27,7 @@ import {import { estimateTokens } from '@/lib/estimate-tokens'import { resolveGatewayTools } from '@/lib/gateway-tools'import { findIgnoredInputKeys, withIgnoredInputKeys } from '@/lib/ignored-input-keys'+import { challengeStepUpBeforeRun } from '@/lib/missing-scope'import { getPostHogClient } from '@/lib/posthog'import { sanitizeErrorToken } from '@/lib/posthog/analytics'import { isPrivateScoutTrialTool } from '@/lib/tool-privacy'@@ -40,6 +41,7 @@ import {formatInputValidationError,getDeprecatedToolRedirect,markNoncanonicalMetricRun,+ missingToolScopeError,parseExecCallInnerArgs,parseExecCallInnerToolName,repairArgumentNesting,@@ -244,6 +246,7 @@ export class ToolExecutor {}const rawArgs = (params?.arguments ?? {}) as Record<string, unknown>+ challengeStepUpForGatedTool(toolName, rawArgs, state)const originalTool = this.findOriginalTool(toolName, state)const rawRequestMeta = params?._metaconst requestMeta =@@ -344,6 +347,11 @@ export class ToolExecutor {if (!state.allTools.some((t) => t.name === toolName)) {toolCallsTotal.inc({ tool: toolName, status: 'error' })+ const scopeGatedTool = state.findScopeGatedTool(toolName)+ if (scopeGatedTool) {+ const error = missingToolScopeError(scopeGatedTool, state.context, state.oauthClientId)+ return handleToolError(error, toolName, state.distinctId, undefined, state.suppressAnalytics)+ }const text = getDeprecatedToolRedirect(toolName, state.allTools) ?? `Tool ${toolName} not found`return { content: [{ type: 'text', text }], isError: true }}@@ -1102,6 +1110,23 @@ function classifyToolError(error: unknown, toolName: string): ToolErrorClassificreturn classification}+// Runs first in a tool call, before analytics, guidance, interview recruitment or the tool itself,+// so a step-up client that replays the call after re-consent repeats nothing.+function challengeStepUpForGatedTool(toolName: string, args: Record<string, unknown>, state: ResolvedState): void {+ if (!state.supportsStepUp || state.viaMcpStore) {+ return+ }+ const targetToolName =+ toolName === 'exec' && typeof args.command === 'string' ? parseExecCallInnerToolName(args.command) : toolName+ if (!targetToolName || state.allTools.some((tool) => tool.name === targetToolName)) {+ return+ }+ const scopeGatedTool = state.findScopeGatedTool(targetToolName)+ if (scopeGatedTool) {+ challengeStepUpBeforeRun(scopeGatedTool.requiredScopes, state.supportsStepUp)+ }+}+function resolveToolErrorClassification(error: unknown): ToolErrorClassification {if (error instanceof MCPToolResultError) {const errorCode = error.errorCode ? sanitizeErrorToken(error.errorCode) : undefineddiff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 7e74d929f13e..b6451e3a3d41 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -1718,6 +1718,17 @@ function missingScopeRecovery(context: Context | undefined, oauthClientId: strin}}+export function missingToolScopeError(+ tool: ScopeGatedTool,+ context: Context | undefined,+ oauthClientId: string | undefined+): ExecCommandError {+ return new ExecCommandError(+ `Tool "${tool.name}" exists, but this MCP connection is missing the required scope(s): ${tool.missingScopes.join(', ')}. ${missingScopeRecovery(context, oauthClientId)} Logging in to PostHog in a browser does not update MCP permissions.`,+ 'missing_scope'+ )+}+function findTool(tools: Tool<ZodObjectAny>[],scopeGatedTools: ScopeGatedTool[],@@ -1739,10 +1750,7 @@ function findTool(}const scopeGatedTool = scopeGatedTools.find((candidate) => candidate.name === name)if (scopeGatedTool) {- throw new ExecCommandError(- `Tool "${name}" exists, but this MCP connection is missing the required scope(s): ${scopeGatedTool.missingScopes.join(', ')}. ${missingScopeRecovery(context, oauthClientId)} Logging in to PostHog in a browser does not update MCP permissions.`,- 'missing_scope'- )+ throw missingToolScopeError(scopeGatedTool, context, oauthClientId)}if (isNotGranted(name)) {throw new ExecCommandError(diff --git a/services/mcp/src/tools/toolDefinitions.ts b/services/mcp/src/tools/toolDefinitions.tsindex 611398cc7408..19aab98fa6b3 100644--- a/services/mcp/src/tools/toolDefinitions.ts+++ b/services/mcp/src/tools/toolDefinitions.ts@@ -393,6 +393,7 @@ export interface ScopeGatedTool {description: string/** Scopes the tool requires that the current API key is missing. */missingScopes: string[]+ requiredScopes: readonly string[]}/**@@ -426,6 +427,7 @@ export function getScopeGatedTools(scopes: string[], options?: ToolFilterOptionstitle: definition.title,description: definition.description,missingScopes: required.filter((scope) => !hasScope(scopes, scope)),+ requiredScopes: required,})}diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsindex 921f8b88e1b5..2aa8a30b423b 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: [],+ findScopeGatedTool: () => undefined,supportsStepUp: false,flagGatedTools: [],gatewayToolsEnabled: false,diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex 2afd3270aaad..7efb5dd70216 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -1013,6 +1013,64 @@ describe('ToolExecutor', () => {})})+ describe('a tool that needs a scope the token lacks', () => {+ const scopeGatedTools = [+ {+ name: 'endpoint-create',+ title: 'Create endpoint',+ description: 'Create a new endpoint',+ missingScopes: ['endpoint:write'],+ requiredScopes: ['endpoint:write', 'query:read'],+ },+ ]+ const gated = {+ scopeGatedTools,+ findScopeGatedTool: (name: string) => scopeGatedTools.find((tool) => tool.name === name),+ }+ const calls = [+ { mode: 'tools', useSingleExec: false, params: { name: 'endpoint-create', arguments: {} } },+ {+ mode: 'exec',+ useSingleExec: true,+ params: { name: 'exec', arguments: { command: 'call endpoint-create {}' } },+ },+ ]++ it.each(calls)('throws the step-up challenge before the tool runs in $mode mode', async (call) => {+ const result = executor.handleToolCall(+ call.params,+ makeToolExecutorState([], { useSingleExec: call.useSingleExec, ...gated, supportsStepUp: true })+ )++ await expect(result).rejects.toMatchObject({+ challenge: 'Bearer error="insufficient_scope", scope="endpoint:write query:read"',+ })+ })++ it.each([+ ...calls.map((call) => ({ ...call, supportsStepUp: false })),+ {+ mode: 'exec info',+ useSingleExec: true,+ params: { name: 'exec', arguments: { command: 'info endpoint-create' } },+ supportsStepUp: true,+ },+ ])('returns the plain tool error in $mode mode', async (call) => {+ const result = (await executor.handleToolCall(+ call.params,+ makeToolExecutorState([], {+ useSingleExec: call.useSingleExec,+ ...gated,+ supportsStepUp: call.supportsStepUp,+ })+ )) as any++ expect(result.isError).toBe(true)+ expect(result.content[0].text).toContain('missing the required scope(s): endpoint:write')+ 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 570cbf7c4eb2..6336526503dc 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: [],+ findScopeGatedTool: () => undefined,supportsStepUp: false,flagGatedTools: [],gatewayToolsEnabled: false,diff --git a/services/mcp/tests/shared/test-utils.ts b/services/mcp/tests/shared/test-utils.tsindex ed65bd379a14..b5090a64e673 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: [],+ findScopeGatedTool: () => undefined,supportsStepUp: false,flagGatedTools: [],gatewayToolsEnabled: false,diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 2304fc963f65..730a6543bdf2 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -1839,12 +1839,14 @@ describe('exec tool', () => {title: 'Refresh available schemas',description: 'Fetch the latest table list from the remote database',missingScopes: ['external_data_source:write'],+ requiredScopes: ['external_data_source:write'],},{name: 'external-data-schemas-list',title: 'List data import schemas',description: 'List all table schemas',missingScopes: ['external_data_source:read'],+ requiredScopes: ['external_data_source:read'],},])const result = JSON.parse(@@ -1869,6 +1871,7 @@ describe('exec tool', () => {title: 'List data import schemas',description: 'List all table schemas',missingScopes: ['external_data_source:read'],+ requiredScopes: ['external_data_source:read'],},])const result = await exec.handler(mockContext, { command: 'search feature-flag' })@@ -1914,6 +1917,7 @@ describe('exec tool', () => {title: 'Create experiment',description: 'Create a new experiment',missingScopes: ['experiment:write'],+ requiredScopes: ['experiment:write'],},])const result = JSON.parse(@@ -2142,6 +2146,7 @@ describe('exec tool', () => {title: 'Create endpoint',description: 'Create a new endpoint',missingScopes: ['endpoint:write'],+ requiredScopes: ['endpoint:write'],},])@@ -2178,6 +2183,7 @@ describe('exec tool', () => {title: 'Create endpoint',description: 'Create a new endpoint',missingScopes: ['endpoint:write'],+ requiredScopes: ['endpoint:write'],},]const exec = createExecTool(