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.

feat(mcp): support feature_flag_variant for tool gating (#60681)

Paul D'Ambraf556afdbc889
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index 83228c3735a9..a4597ff834d7 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -1482,6 +1482,7 @@ function generateDefinitionsJson(
...(toolConfig.feature_flag_behavior
? { feature_flag_behavior: toolConfig.feature_flag_behavior }
: {}),
+ ...(toolConfig.feature_flag_variant ? { feature_flag_variant: toolConfig.feature_flag_variant } : {}),
...(toolConfig.system_prompt_hint ? { system_prompt_hint: toolConfig.system_prompt_hint } : {}),
}
}
@@ -1505,6 +1506,9 @@ function generateDefinitionsJson(
...(wrapperConfig.feature_flag_behavior
? { feature_flag_behavior: wrapperConfig.feature_flag_behavior }
: {}),
+ ...(wrapperConfig.feature_flag_variant
+ ? { feature_flag_variant: wrapperConfig.feature_flag_variant }
+ : {}),
...(wrapperConfig.system_prompt_hint ? { system_prompt_hint: wrapperConfig.system_prompt_hint } : {}),
}
}
@@ -1682,6 +1686,7 @@ function generateQueryWrapperDefinitionsJson(
},
...(toolConfig.feature_flag ? { feature_flag: toolConfig.feature_flag } : {}),
...(toolConfig.feature_flag_behavior ? { feature_flag_behavior: toolConfig.feature_flag_behavior } : {}),
+ ...(toolConfig.feature_flag_variant ? { feature_flag_variant: toolConfig.feature_flag_variant } : {}),
...(toolConfig.system_prompt_hint ? { system_prompt_hint: toolConfig.system_prompt_hint } : {}),
}
}
diff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.ts
index de05c88a36ae..1866fb095ca4 100644
--- a/services/mcp/scripts/yaml-config-schema.ts
+++ b/services/mcp/scripts/yaml-config-schema.ts
@@ -144,6 +144,8 @@ export const ToolConfigSchema = z
* - `'disable'`: tool is hidden when the flag is on.
*/
feature_flag_behavior: z.enum(['enable', 'disable']).optional(),
+ /** Variant of `feature_flag` to match exactly. Requires `feature_flag` to be set. */
+ feature_flag_variant: z.string().optional(),
/**
* Response field filtering. Supports dot-path patterns with wildcards (e.g. 'filters.groups.*.key').
* For list endpoints, applied to each item in `results`. `include` and `exclude` are mutually exclusive.
@@ -179,6 +181,10 @@ export const ToolConfigSchema = z
.refine((data) => !(data.description && data.description_file), {
message: 'description and description_file are mutually exclusive',
})
+ .refine((data) => !(data.feature_flag_variant && !data.feature_flag), {
+ message: '`feature_flag_variant` requires `feature_flag` to be set',
+ path: ['feature_flag_variant'],
+ })
export type ToolConfig = z.infer<typeof ToolConfigSchema>
@@ -398,11 +404,17 @@ export const QueryWrapperToolConfigSchema = z
* - `'disable'`: tool is hidden when the flag is on.
*/
feature_flag_behavior: z.enum(['enable', 'disable']).optional(),
+ /** Variant of `feature_flag` to match exactly. Requires `feature_flag` to be set. */
+ feature_flag_variant: z.string().optional(),
})
.strict()
.refine((data) => !(data.description && data.description_file), {
message: 'description and description_file are mutually exclusive',
})
+ .refine((data) => !(data.feature_flag_variant && !data.feature_flag), {
+ message: '`feature_flag_variant` requires `feature_flag` to be set',
+ path: ['feature_flag_variant'],
+ })
export type QueryWrapperToolConfig = z.infer<typeof QueryWrapperToolConfigSchema>
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
index 7639a68a37e2..6ce295c6eea6 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -1,6 +1,6 @@
import { MCPClientProfile } from '@/lib/client-detection'
import { buildMCPAnalyticsGroups } from '@/lib/posthog/analytics'
-import { evaluateFeatureFlags, type FlagGroups } from '@/lib/posthog/flags'
+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'
@@ -23,7 +23,7 @@ export interface ResolvedState {
context: Context
version: number
useSingleExec: boolean
- toolFeatureFlags: Record<string, boolean> | undefined
+ toolFeatureFlags: EvaluatedFlags | undefined
apiKeyScopes: string[]
clientProfile: MCPClientProfile
requestContext: MCPRequestContext
@@ -108,9 +108,11 @@ export class RequestStateResolver {
reqCtx.getDistinctId(),
])
- const flagVersion = allFlags['mcp-version-2'] ? 2 : undefined
+ const flagVersion = allFlags['mcp-version-2'] === true ? 2 : undefined
+ // Preserve variant strings (and `undefined` for unevaluated flags) — the
+ // tool filter needs raw values to support `feature_flag_variant` matching.
const toolFeatureFlags =
- toolFlagKeys.length > 0 ? Object.fromEntries(toolFlagKeys.map((k) => [k, !!allFlags[k]])) : undefined
+ toolFlagKeys.length > 0 ? Object.fromEntries(toolFlagKeys.map((k) => [k, allFlags[k]])) : undefined
const oauthClientName = (await reqCtx.tokenCache.get('clientName')) || undefined
@@ -207,7 +209,7 @@ export class RequestStateResolver {
reqCtx: RequestContext,
flagKeys: string[],
groups?: FlagGroups
- ): Promise<Record<string, boolean>> {
+ ): Promise<EvaluatedFlags> {
if (flagKeys.length === 0) {
return {}
}
diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.ts
index 57afac8b830a..58d7e04b950e 100644
--- a/services/mcp/src/lib/instructions-formatter.ts
+++ b/services/mcp/src/lib/instructions-formatter.ts
@@ -8,6 +8,7 @@ import {
type QueryToolInfo,
type ToolInfo,
} from '@/lib/instructions'
+import type { EvaluatedFlags } from '@/lib/posthog/flags'
import { formatPrompt } from '@/lib/utils'
import AGENT_FEEDBACK from '@/templates/sections/agent-feedback.md'
import BASIC_FUNCTIONALITY from '@/templates/sections/basic-functionality.md'
@@ -34,7 +35,7 @@ export interface InstructionsContext {
queryTools?: QueryToolInfo[] | undefined
/** Resolved tool feature flags from `resolveToolFeatureFlags`. Used to gate
* prompt sections whose corresponding tool is flag-gated. */
- featureFlags?: Record<string, boolean> | undefined
+ featureFlags?: EvaluatedFlags | undefined
}
/**
@@ -111,7 +112,7 @@ export class InstructionsFormatter {
/** The agent-feedback section is only useful when the `agent-feedback` tool
* is reachable, which is governed by the `mcp-feedback-tool` flag evaluated
* in `resolveToolFeatureFlags`. */
- private agentFeedbackEnabled(featureFlags: Record<string, boolean> | undefined): boolean {
+ private agentFeedbackEnabled(featureFlags: EvaluatedFlags | undefined): boolean {
return featureFlags?.['mcp-feedback-tool'] === true
}
diff --git a/services/mcp/src/lib/posthog/flags.ts b/services/mcp/src/lib/posthog/flags.ts
index 6fec1a6cc42d..58f9715284c0 100644
--- a/services/mcp/src/lib/posthog/flags.ts
+++ b/services/mcp/src/lib/posthog/flags.ts
@@ -14,11 +14,17 @@ export async function isFeatureFlagEnabled(flagKey: string, distinctId: string,
}
}
+/** Raw value from posthog-node for a single flag — `true`/`false` for boolean flags, a variant string for multivariate. */
+export type FlagValue = boolean | string | undefined
+
+/** Shape returned by {@link evaluateFeatureFlags} and threaded through the tool-filtering and instructions layers. */
+export type EvaluatedFlags = Record<string, FlagValue>
+
export async function evaluateFeatureFlags(
flagKeys: string[],
distinctId: string,
groups?: FlagGroups
-): Promise<Record<string, boolean>> {
+): Promise<EvaluatedFlags> {
if (flagKeys.length === 0) {
return {}
}
@@ -26,9 +32,9 @@ export async function evaluateFeatureFlags(
const client = getPostHogClient()
const hasGroups = groups && Object.keys(groups).length > 0
const allFlags = await client.getAllFlags(distinctId, { flagKeys, ...(hasGroups ? { groups } : {}) })
- const result: Record<string, boolean> = {}
+ const result: EvaluatedFlags = {}
for (const key of flagKeys) {
- result[key] = allFlags[key] === true
+ result[key] = allFlags[key] as FlagValue
}
return result
}
diff --git a/services/mcp/src/mcp.ts b/services/mcp/src/mcp.ts
index 1f6ff8700c96..46c6b8628149 100644
--- a/services/mcp/src/mcp.ts
+++ b/services/mcp/src/mcp.ts
@@ -30,7 +30,7 @@ import {
McpAnalyticsInitResult,
type MCPAnalyticsContext,
} from '@/lib/posthog/analytics'
-import { evaluateFeatureFlags, type FlagGroups, isFeatureFlagEnabled } from '@/lib/posthog/flags'
+import { type EvaluatedFlags, evaluateFeatureFlags, type FlagGroups, isFeatureFlagEnabled } from '@/lib/posthog/flags'
import { SessionManager } from '@/lib/SessionManager'
import { StateManager } from '@/lib/StateManager'
import { formatPrompt, type McpMode, sanitizeHeaderValue } from '@/lib/utils'
@@ -923,10 +923,7 @@ export class MCP extends McpAgent<Env> {
}
}
- private async resolveToolFeatureFlags(
- version?: number,
- groups?: FlagGroups
- ): Promise<Record<string, boolean> | undefined> {
+ private async resolveToolFeatureFlags(version?: number, groups?: FlagGroups): Promise<EvaluatedFlags | undefined> {
try {
const { getRequiredFeatureFlags } = await import('@/tools/toolDefinitions')
const flagKeys = getRequiredFeatureFlags(version)
diff --git a/services/mcp/src/tools/toolDefinitions.ts b/services/mcp/src/tools/toolDefinitions.ts
index 543d2c3075ad..bdf5e1d514d4 100644
--- a/services/mcp/src/tools/toolDefinitions.ts
+++ b/services/mcp/src/tools/toolDefinitions.ts
@@ -1,39 +1,48 @@
import z from 'zod'
+import type { EvaluatedFlags } from '@/lib/posthog/flags'
+
import generatedToolDefinitionsJson from '../../schema/generated-tool-definitions.json'
import toolDefinitionsV2Json from '../../schema/tool-definitions-v2.json'
import toolDefinitionsJson from '../../schema/tool-definitions.json'
-export const ToolDefinitionSchema = z.object({
- description: z.string(),
- category: z.string(),
- feature: z.string(),
- summary: z.string(),
- title: z.string(),
- required_scopes: z.array(z.string()),
- new_mcp: z.boolean().optional(),
- requires_ai_consent: z.boolean().optional(),
- /** PostHog feature flag key that gates this tool. */
- feature_flag: z.string().optional(),
- /** How the flag gates the tool: 'enable' (default) or 'disable'. */
- feature_flag_behavior: z.enum(['enable', 'disable']).optional(),
- /** One-line selection hint surfaced in the system prompt's query tool catalog. */
- system_prompt_hint: z.string().optional(),
- /**
- * When true, the tool is exposed even when the client passes a `features`
- * or `tools` allowlist that wouldn't otherwise match. Reserved for
- * cross-cutting utility tools (e.g. feedback) that should remain
- * discoverable to every client without forcing them to opt in.
- * Other filters (readOnly, AI consent, feature flags, scopes) still apply.
- */
- always_available: z.boolean().optional(),
- annotations: z.object({
- destructiveHint: z.boolean(),
- idempotentHint: z.boolean(),
- openWorldHint: z.boolean(),
- readOnlyHint: z.boolean(),
- }),
-})
+export const ToolDefinitionSchema = z
+ .object({
+ description: z.string(),
+ category: z.string(),
+ feature: z.string(),
+ summary: z.string(),
+ title: z.string(),
+ required_scopes: z.array(z.string()),
+ new_mcp: z.boolean().optional(),
+ requires_ai_consent: z.boolean().optional(),
+ /** PostHog feature flag key that gates this tool. */
+ feature_flag: z.string().optional(),
+ /** How the flag gates the tool: 'enable' (default) or 'disable'. */
+ feature_flag_behavior: z.enum(['enable', 'disable']).optional(),
+ /** Variant of `feature_flag` to match exactly. Requires `feature_flag` to be set. */
+ feature_flag_variant: z.string().optional(),
+ /** One-line selection hint surfaced in the system prompt's query tool catalog. */
+ system_prompt_hint: z.string().optional(),
+ /**
+ * When true, the tool is exposed even when the client passes a `features`
+ * or `tools` allowlist that wouldn't otherwise match. Reserved for
+ * cross-cutting utility tools (e.g. feedback) that should remain
+ * discoverable to every client without forcing them to opt in.
+ * Other filters (readOnly, AI consent, feature flags, scopes) still apply.
+ */
+ always_available: z.boolean().optional(),
+ annotations: z.object({
+ destructiveHint: z.boolean(),
+ idempotentHint: z.boolean(),
+ openWorldHint: z.boolean(),
+ readOnlyHint: z.boolean(),
+ }),
+ })
+ .refine((data) => !(data.feature_flag_variant && !data.feature_flag), {
+ message: '`feature_flag_variant` requires `feature_flag` to be set',
+ path: ['feature_flag_variant'],
+ })
export type ToolDefinition = z.infer<typeof ToolDefinitionSchema>
@@ -89,11 +98,8 @@ export interface ToolFilterOptions {
excludeTools?: string[] | undefined
readOnly?: boolean | undefined
aiConsentGiven?: boolean | undefined
- /**
- * Map of feature flag key → evaluated boolean result.
- * Used to gate tools that declare `feature_flag` in their YAML config.
- */
- featureFlags?: Record<string, boolean> | undefined
+ /** Used to gate tools that declare `feature_flag` in their YAML config. */
+ featureFlags?: EvaluatedFlags | undefined
/**
* Project IDs the token is restricted to (`scoped_teams` on the API key).
* When set, the backend 403s any org-level endpoint, so we drop tools that
@@ -121,6 +127,31 @@ function normalizeFeatureName(name: string): string {
return name.replace(/-/g, '_')
}
+/**
+ * Predicate: does a tool's `feature_flag` configuration permit it under the
+ * given evaluation map? An undefined map is treated as "no flags evaluated".
+ *
+ * no `feature_flag` → always passes
+ * `feature_flag_variant` set → flag value must equal the variant string
+ * `feature_flag_behavior: 'enable'` (default) → flag must be `=== true`
+ * `feature_flag_behavior: 'disable'` → flag must NOT be `=== true`
+ */
+export function toolPassesFlagGate(definition: ToolDefinition, featureFlags: EvaluatedFlags = {}): boolean {
+ if (!definition.feature_flag) {
+ // Belt-and-braces: the schema `.refine` rejects this at parse time, but
+ // `z.infer` strips refinements so TS lets callers hand-roll a bad
+ // ToolDefinition. Treat the misconfig as "always hidden" rather than
+ // silently ungated.
+ return definition.feature_flag_variant === undefined
+ }
+ const flagValue = featureFlags[definition.feature_flag]
+ if (definition.feature_flag_variant !== undefined) {
+ return flagValue === definition.feature_flag_variant
+ }
+ const isOn = flagValue === true
+ return (definition.feature_flag_behavior ?? 'enable') === 'enable' ? isOn : !isOn
+}
+
export function getToolsForFeatures(options?: ToolFilterOptions): string[] {
const { features, tools, version, readOnly, aiConsentGiven, featureFlags, scopedTeams } = options || {}
const toolDefinitions = getToolDefinitions(version)
@@ -165,32 +196,8 @@ export function getToolsForFeatures(options?: ToolFilterOptions): string[] {
entries = entries.filter(([_, definition]) => !definition.requires_ai_consent)
}
- // Filter by feature flags — tools with a feature_flag are gated by the flag's evaluation.
- // behavior 'enable' (default): tool is included only when the flag is on.
- // behavior 'disable': tool is excluded when the flag is on.
- if (featureFlags) {
- entries = entries.filter(([_, definition]) => {
- if (!definition.feature_flag) {
- return true
- }
- const flagValue = featureFlags[definition.feature_flag]
- // If the flag wasn't evaluated (missing from the map), exclude the tool
- // for 'enable' behavior and include it for 'disable' behavior.
- const isOn = flagValue === true
- const behavior = definition.feature_flag_behavior ?? 'enable'
- return behavior === 'enable' ? isOn : !isOn
- })
- } else {
- // When no feature flags have been evaluated, exclude tools that require
- // a flag to be enabled (behavior 'enable') — they shouldn't appear by default.
- // Tools with behavior 'disable' are included since their flag hasn't fired.
- entries = entries.filter(([_, definition]) => {
- if (!definition.feature_flag) {
- return true
- }
- return (definition.feature_flag_behavior ?? 'enable') === 'disable'
- })
- }
+ // Filter by feature flags — see {@link toolPassesFlagGate} for the predicate.
+ entries = entries.filter(([_, definition]) => toolPassesFlagGate(definition, featureFlags))
// Hide tools that need org-level access when the session's token is
// project-scoped - the backend would 403 them
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index f162d1785210..1d0c8f437200 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import { OAUTH_SCOPES_SUPPORTED } from '@/lib/constants'
+import type { EvaluatedFlags } from '@/lib/posthog/flags'
import { SessionManager } from '@/lib/SessionManager'
import { getToolsFromContext } from '@/tools'
import {
@@ -8,6 +9,8 @@ import {
getRequiredFeatureFlags,
getToolsForFeatures,
type ToolDefinition,
+ ToolDefinitionSchema,
+ toolPassesFlagGate,
} from '@/tools/toolDefinitions'
import type { Context } from '@/tools/types'
@@ -703,35 +706,12 @@ describe('Tool Filtering - Feature Flags', () => {
expect(flags).toHaveLength(9)
})
- // Test the filtering logic with a direct unit test approach using
- // a standalone implementation that mirrors getToolsForFeatures' logic
+ // Exercise the real predicate (toolPassesFlagGate) over hand-rolled entries
+ // so we can cover variant / behavior / missing-flag matrices without
+ // having to register fake tools into the global tool registry.
describe('feature flag filter predicate', () => {
- function filterByFeatureFlags(
- entries: [string, ToolDefinition][],
- featureFlags?: Record<string, boolean>
- ): string[] {
- let filtered = entries
-
- if (featureFlags) {
- filtered = filtered.filter(([_, definition]) => {
- if (!definition.feature_flag) {
- return true
- }
- const flagValue = featureFlags[definition.feature_flag]
- const isOn = flagValue === true
- const behavior = definition.feature_flag_behavior ?? 'enable'
- return behavior === 'enable' ? isOn : !isOn
- })
- } else {
- filtered = filtered.filter(([_, definition]) => {
- if (!definition.feature_flag) {
- return true
- }
- return (definition.feature_flag_behavior ?? 'enable') === 'disable'
- })
- }
-
- return filtered.map(([name]) => name)
+ function filterByFeatureFlags(entries: [string, ToolDefinition][], featureFlags?: EvaluatedFlags): string[] {
+ return entries.filter(([_, def]) => toolPassesFlagGate(def, featureFlags)).map(([name]) => name)
}
it('should include tools with feature_flag when flag is enabled', () => {
@@ -821,5 +801,99 @@ describe('Tool Filtering - Feature Flags', () => {
expect(toolsOff).toContain('old-tool-v1')
expect(toolsOff).toContain('unrelated-tool')
})
+
+ describe('feature_flag_variant matching', () => {
+ const variantToolEntries: [string, ToolDefinition][] = [
+ ['unrelated-tool', { ...baseDef }],
+ [
+ 'variant-gated-tool',
+ {
+ ...baseDef,
+ feature_flag: 'promoted-product',
+ feature_flag_variant: 'intent_plus',
+ },
+ ],
+ ]
+
+ it('shows variant-gated tool only when the variant matches', () => {
+ const tools = filterByFeatureFlags(variantToolEntries, { 'promoted-product': 'intent_plus' })
+ expect(tools).toContain('variant-gated-tool')
+ expect(tools).toContain('unrelated-tool')
+ })
+
+ it.each(['control_a', 'control_b', 'intent', false, true, undefined])(
+ 'hides variant-gated tool when flag value is %p',
+ (flagValue) => {
+ const tools = filterByFeatureFlags(variantToolEntries, { 'promoted-product': flagValue })
+ expect(tools).not.toContain('variant-gated-tool')
+ expect(tools).toContain('unrelated-tool')
+ }
+ )
+
+ it('hides variant-gated tool when featureFlags map is omitted entirely', () => {
+ const tools = filterByFeatureFlags(variantToolEntries)
+ expect(tools).not.toContain('variant-gated-tool')
+ expect(tools).toContain('unrelated-tool')
+ })
+
+ it('hides a hand-rolled misconfig tool with feature_flag_variant but no feature_flag', () => {
+ // The Zod `.refine` rejects this at parse time, but a developer
+ // can still construct one in code via cast — the runtime predicate
+ // must treat it as hidden, not ungated.
+ const misconfigEntries: [string, ToolDefinition][] = [
+ ['orphan-variant', { ...baseDef, feature_flag_variant: 'intent_plus' }],
+ ]
+ expect(filterByFeatureFlags(misconfigEntries, { 'promoted-product': 'intent_plus' })).not.toContain(
+ 'orphan-variant'
+ )
+ expect(filterByFeatureFlags(misconfigEntries)).not.toContain('orphan-variant')
+ })
+ })
+
+ describe('feature_flag_variant schema validation', () => {
+ const baseFields = {
+ description: '',
+ category: 'platform_features',
+ feature: 'platform_features',
+ summary: '',
+ title: '',
+ required_scopes: [],
+ annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: true, readOnlyHint: true },
+ }
+
+ it('rejects feature_flag_variant without feature_flag', () => {
+ const result = ToolDefinitionSchema.safeParse({
+ ...baseFields,
+ feature_flag_variant: 'intent_plus',
+ })
+ expect(result.success).toBe(false)
+ if (!result.success) {
+ expect(result.error.issues[0]?.message).toMatch(/feature_flag_variant.*requires.*feature_flag/i)
+ expect(result.error.issues[0]?.path).toEqual(['feature_flag_variant'])
+ }
+ })
+
+ it('accepts feature_flag_variant when feature_flag is also set', () => {
+ const result = ToolDefinitionSchema.safeParse({
+ ...baseFields,
+ feature_flag: 'promoted-product',
+ feature_flag_variant: 'intent_plus',
+ })
+ expect(result.success).toBe(true)
+ })
+
+ it('accepts feature_flag alone (no variant)', () => {
+ const result = ToolDefinitionSchema.safeParse({
+ ...baseFields,
+ feature_flag: 'promoted-product',
+ })
+ expect(result.success).toBe(true)
+ })
+
+ it('accepts a definition with neither flag field set', () => {
+ const result = ToolDefinitionSchema.safeParse(baseFields)
+ expect(result.success).toBe(true)
+ })
+ })
})
})