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): surface scope-gated tools in exec search (#60676)

Tom Owerse8c7e7fa8039
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
index cc4ce7cd4ccc..3b5d7e830e7c 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -3,7 +3,7 @@ import { buildMCPAnalyticsGroups } from '@/lib/posthog/analytics'
import { type EvaluatedFlags, evaluateFeatureFlags, type FlagGroups } from '@/lib/posthog/flags'
import type { RequestProperties } from '@/lib/request-properties'
import type { McpMode } from '@/lib/utils'
-import { getRequiredFeatureFlags } from '@/tools/toolDefinitions'
+import { getRequiredFeatureFlags, getScopeGatedTools, type ScopeGatedTool } from '@/tools/toolDefinitions'
import type { Context, Tool, Env, State, ZodObjectAny } from '@/tools/types'
import type { RedisLike } from './cache/RedisCache'
@@ -28,6 +28,7 @@ export interface ResolvedState {
requestContext: MCPRequestContext
sessionContext: MCPSessionContext | null
allTools: Tool<ZodObjectAny>[]
+ scopeGatedTools: ScopeGatedTool[]
distinctId: string
}
@@ -137,16 +138,19 @@ export class RequestStateResolver {
excludeTools.push('switch-organization')
}
- const allTools = this.catalog.getFilteredTools({
+ const filterOptions = {
features,
tools,
excludeTools,
readOnly,
featureFlags: toolFeatureFlags,
- scopes: apiKeyScopes,
scopedTeams: apiKeyScopedTeams,
aiConsentGiven: aiConsentGiven ?? undefined,
- })
+ }
+ const allTools = this.catalog.getFilteredTools({ ...filterOptions, scopes: apiKeyScopes })
+ // 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) : []
return {
reqCtx,
@@ -158,6 +162,7 @@ export class RequestStateResolver {
requestContext,
sessionContext,
allTools,
+ scopeGatedTools,
distinctId,
}
}
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index aa9f3efb2383..db9871a3882e 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -224,7 +224,8 @@ export class ToolExecutor {
this.instructionsBuilder.buildExecToolDescription(),
commandReference,
clientContext.mcpConsumer,
- trackInnerCall
+ trackInnerCall,
+ state.scopeGatedTools
)
return {
diff --git a/services/mcp/src/mcp.ts b/services/mcp/src/mcp.ts
index 1a70e5b40fad..ddff3dee296c 100644
--- a/services/mcp/src/mcp.ts
+++ b/services/mcp/src/mcp.ts
@@ -41,7 +41,7 @@ import { registerResources } from '@/resources'
import { registerUiAppResources } from '@/resources/ui-apps'
import EXECUTE_SQL_PROMPT from '@/templates/execute-sql-prompt.md'
import { createExecInnerToolCallResolver, createExecTool, type ExecInnerCallTracker } from '@/tools/exec'
-import { getToolDefinition } from '@/tools/toolDefinitions'
+import { getScopeGatedTools, getToolDefinition } from '@/tools/toolDefinitions'
import { type CloudRegion, type Context, type State, type Tool } from '@/tools/types'
const instructionsFormatter = new InstructionsFormatter()
@@ -744,13 +744,25 @@ export class MCP extends McpAgent<Env> {
)
}
+ const aiConsentGiven = await context.stateManager.getAiConsentGiven()
+ const scopeGatedTools = getScopeGatedTools(_apiKey?.scopes ?? [], {
+ features,
+ tools,
+ excludeTools,
+ readOnly,
+ featureFlags: toolFeatureFlags,
+ scopedTeams: _apiKey?.scoped_teams ?? [],
+ ...(aiConsentGiven !== undefined ? { aiConsentGiven } : {}),
+ })
+
const execTool = createExecTool(
allTools,
context,
instructionsFormatter.buildExecToolDescription(),
commandReference,
this.requestProperties.mcpConsumer,
- trackInnerCall
+ trackInnerCall,
+ scopeGatedTools
)
const typedExecTool = execTool as Tool<z.ZodObject>
this.registerTool(typedExecTool, async (params) => typedExecTool.handler(context, params))
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 41ef1bebc99e..39cfb343dcd5 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -6,6 +6,7 @@ import { isPostHogCodeConsumer } from '@/lib/client-detection'
import { formatResponse } from '@/lib/response'
import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'
+import type { ScopeGatedTool } from './toolDefinitions'
import {
POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY,
POSTHOG_META_KEY,
@@ -14,6 +15,10 @@ import {
type ZodObjectAny,
} from './types'
+/** Upper bound on a `search` regex pattern — keeps a pathological pattern from
+ * forcing catastrophic backtracking against tool metadata. */
+const MAX_SEARCH_PATTERN_LENGTH = 200
+
type ExecSchema = ReturnType<typeof makeExecSchema>
export interface ExecInnerCallProperties {
@@ -122,7 +127,8 @@ export function createExecTool(
toolDescription: string,
commandReference: string,
mcpConsumer: string | undefined,
- trackInnerCall?: ExecInnerCallTracker
+ trackInnerCall?: ExecInnerCallTracker,
+ scopeGatedTools: ScopeGatedTool[] = []
): Tool<ExecSchema> {
const ExecSchema = makeExecSchema(commandReference)
@@ -150,6 +156,13 @@ export function createExecTool(
if (!rest) {
throw new Error('Usage: search <regex_pattern>')
}
+ // Bound the user-supplied pattern length to limit the blast
+ // radius of a pathological (catastrophic-backtracking) regex.
+ if (rest.length > MAX_SEARCH_PATTERN_LENGTH) {
+ throw new Error(
+ `Search pattern too long (${rest.length} chars, max ${MAX_SEARCH_PATTERN_LENGTH}). Use a shorter, more targeted pattern.`
+ )
+ }
let regex: RegExp
try {
regex = new RegExp(rest, 'i')
@@ -159,6 +172,22 @@ export function createExecTool(
const matches = allTools
.filter((t) => regex.test(t.name) || regex.test(t.title) || regex.test(t.description))
.map((t) => t.name)
+ const gatedMatches = scopeGatedTools.filter(
+ (t) => regex.test(t.name) || regex.test(t.title) || regex.test(t.description)
+ )
+ if (gatedMatches.length > 0) {
+ const requiredScopes = [...new Set(gatedMatches.flatMap((t) => t.missingScopes))].sort()
+ return JSON.stringify({
+ matches,
+ scope_gated_matches: gatedMatches.map((t) => ({
+ name: t.name,
+ missing_scopes: t.missingScopes,
+ })),
+ hint:
+ `These tools also match but are hidden because the API key is missing the ` +
+ `required scope(s): ${requiredScopes.join(', ')}. The user needs to re-authenticate the MCP or connector, if the harness supports OAuth, or add the scopes to the personal API key to use these tools.`,
+ })
+ }
if (matches.length === 0) {
return JSON.stringify({
matches: [],
diff --git a/services/mcp/src/tools/toolDefinitions.ts b/services/mcp/src/tools/toolDefinitions.ts
index 97aac5d92ff0..7b829166e7e1 100644
--- a/services/mcp/src/tools/toolDefinitions.ts
+++ b/services/mcp/src/tools/toolDefinitions.ts
@@ -1,5 +1,6 @@
import z from 'zod'
+import { hasScope, hasScopes } from '@/lib/api'
import type { EvaluatedFlags } from '@/lib/posthog/flags'
import generatedToolDefinitionsJson from '../../schema/generated-tool-definitions.json'
@@ -190,3 +191,43 @@ export function getToolsForFeatures(options?: ToolFilterOptions): string[] {
return entries.map(([toolName, _]) => toolName)
}
+
+export interface ScopeGatedTool {
+ name: string
+ title: string
+ description: string
+ /** Scopes the tool requires that the current API key is missing. */
+ missingScopes: string[]
+}
+
+/**
+ * Tools that pass every filter except the API key's scopes — i.e. they exist
+ * and are enabled for this session's features, but the token lacks the scopes
+ * to call them. Surfaced by the exec `search` command so an agent gets an
+ * actionable "add this scope" hint instead of silently concluding the tool is
+ * missing.
+ */
+export function getScopeGatedTools(scopes: string[], options?: ToolFilterOptions): ScopeGatedTool[] {
+ const toolDefinitions = getToolDefinitions()
+ const excluded = new Set(options?.excludeTools ?? [])
+ const gated: ScopeGatedTool[] = []
+
+ for (const name of getToolsForFeatures(options)) {
+ if (excluded.has(name)) {
+ continue
+ }
+ const definition = toolDefinitions[name]
+ const required = definition?.required_scopes ?? []
+ if (!definition || required.length === 0 || hasScopes(scopes, required)) {
+ continue
+ }
+ gated.push({
+ name,
+ title: definition.title,
+ description: definition.description,
+ missingScopes: required.filter((scope) => !hasScope(scopes, scope)),
+ })
+ }
+
+ return gated
+}
diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.ts
index 7923525e6f1b..d46fe0854cd7 100644
--- a/services/mcp/tests/hono/analytics.test.ts
+++ b/services/mcp/tests/hono/analytics.test.ts
@@ -53,6 +53,7 @@ function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {
mcpVendorClient: 'ClaudeCode',
},
allTools: [],
+ scopeGatedTools: [],
distinctId: 'distinct-id',
...overrides,
}
diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.ts
index c600fb648efc..066aebda8afa 100644
--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts
+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts
@@ -75,6 +75,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
},
sessionContext: null,
allTools: tools as any,
+ scopeGatedTools: [],
distinctId: 'test-distinct-id',
...overrides,
}
diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.ts
index 59b4433362df..f77086bdf499 100644
--- a/services/mcp/tests/hono/tool-executor.test.ts
+++ b/services/mcp/tests/hono/tool-executor.test.ts
@@ -49,6 +49,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
},
sessionContext: null,
allTools: tools as any,
+ scopeGatedTools: [],
distinctId: 'test-distinct-id',
...overrides,
}
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index cc8458c65511..a1cc3768789d 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -514,6 +514,66 @@ describe('exec tool', () => {
})
})
+ describe('search command', () => {
+ it('returns a plain array of matching tool names', async () => {
+ const flagTool = makeMockTool({ name: 'feature-flag-get-all', title: 'List feature flags' })
+ const exec = createExec([flagTool])
+ const result = await exec.handler(mockContext, { command: 'search feature-flag' })
+ expect(JSON.parse(result as string)).toEqual(['feature-flag-get-all'])
+ })
+
+ it('rejects an overly long search pattern before compiling the regex', async () => {
+ const exec = createExec([makeMockTool()])
+ const longPattern = 'a'.repeat(201)
+ await expect(exec.handler(mockContext, { command: `search ${longPattern}` })).rejects.toThrow(
+ /pattern too long/i
+ )
+ })
+
+ it('hints scope-gated tools that match but are hidden by missing scopes', async () => {
+ const exec = createExecTool([makeMockTool()], mockContext, 'desc', 'cmd', undefined, undefined, [
+ {
+ name: 'external-data-sources-refresh-schemas',
+ title: 'Refresh available schemas',
+ description: 'Fetch the latest table list from the remote database',
+ missingScopes: ['external_data_source:write'],
+ },
+ {
+ name: 'external-data-schemas-list',
+ title: 'List data import schemas',
+ description: 'List all table schemas',
+ missingScopes: ['external_data_source:read'],
+ },
+ ])
+ const result = JSON.parse(
+ (await exec.handler(mockContext, {
+ command: 'search external-data-sources|external-data-schemas',
+ })) as string
+ )
+ expect(result.matches).toEqual([])
+ expect(result.scope_gated_matches).toEqual([
+ { name: 'external-data-sources-refresh-schemas', missing_scopes: ['external_data_source:write'] },
+ { name: 'external-data-schemas-list', missing_scopes: ['external_data_source:read'] },
+ ])
+ expect(result.hint).toContain('external_data_source:read')
+ expect(result.hint).toContain('external_data_source:write')
+ })
+
+ it('does not hint scope-gated tools that do not match the query', async () => {
+ const flagTool = makeMockTool({ name: 'feature-flag-get-all', title: 'List feature flags' })
+ const exec = createExecTool([flagTool], mockContext, 'desc', 'cmd', undefined, undefined, [
+ {
+ name: 'external-data-schemas-list',
+ title: 'List data import schemas',
+ description: 'List all table schemas',
+ missingScopes: ['external_data_source:read'],
+ },
+ ])
+ const result = await exec.handler(mockContext, { command: 'search feature-flag' })
+ expect(JSON.parse(result as string)).toEqual(['feature-flag-get-all'])
+ })
+ })
+
describe('deprecated tool redirects', () => {
it.each([
['entity-search', 'execute-sql'],