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): evaluate feature flags using groups (#59228)

Alex Lider3445f05ad51e
diff --git a/services/mcp/src/hono/mcp-server.ts b/services/mcp/src/hono/mcp-server.ts
index 41f5d5f277dd..7754800c41c5 100644
--- a/services/mcp/src/hono/mcp-server.ts
+++ b/services/mcp/src/hono/mcp-server.ts
@@ -17,7 +17,7 @@ import {
initMcpAnalytics,
type MCPAnalyticsContext,
} from '@/lib/posthog/analytics'
-import { evaluateFeatureFlags, isFeatureFlagEnabled } from '@/lib/posthog/flags'
+import { evaluateFeatureFlags, type FlagGroups, isFeatureFlagEnabled } from '@/lib/posthog/flags'
import { type RequestProperties } from '@/lib/request-properties'
import { SessionManager } from '@/lib/SessionManager'
import { StateManager } from '@/lib/StateManager'
@@ -386,9 +386,9 @@ export class HonoMcpServer {
await this.resolveClientInfo()
_lap('resolveClientInfo')
- // Start feature flag resolution in parallel with cache seeding
+ // User-level flags resolve in parallel with cache seeding. Tool flags are
+ // deferred until orgId/projectUuid are known so group-scoped rollouts evaluate correctly.
const flagPromise = this.resolveVersionFlag()
- const toolFlagsPromise = this.resolveToolFeatureFlags(clientVersion)
const singleExecPromise = this.resolveSingleExecFlag()
// Seed cache with header-provided IDs before any fetches
@@ -415,6 +415,12 @@ export class HonoMcpServer {
}
_lap('setDefaultOrgAndProject')
+ // Flag-eval groups mirror analytics `$groups` so per-organization and per-project
+ // rollouts evaluate against the same entities — see `buildMCPAnalyticsGroups`.
+ const flagAnalyticsContext = await this.getAnalyticsContextSafe(context)
+ const flagGroups = flagAnalyticsContext ? buildMCPAnalyticsGroups(flagAnalyticsContext) : undefined
+ const toolFlagsPromise = this.resolveToolFeatureFlags(clientVersion, flagGroups)
+
const [flagVersion, toolFeatureFlags, singleExecFlagOn, _apiKey] = await Promise.all([
flagPromise,
toolFlagsPromise,
@@ -715,7 +721,10 @@ export class HonoMcpServer {
}
}
- private async resolveToolFeatureFlags(version?: number): Promise<Record<string, boolean> | undefined> {
+ private async resolveToolFeatureFlags(
+ version?: number,
+ groups?: FlagGroups
+ ): Promise<Record<string, boolean> | undefined> {
try {
const { getRequiredFeatureFlags } = await import('@/tools/toolDefinitions')
const flagKeys = getRequiredFeatureFlags(version)
@@ -723,7 +732,7 @@ export class HonoMcpServer {
return undefined
}
const distinctId = await this.getDistinctId()
- return await evaluateFeatureFlags(flagKeys, distinctId)
+ return await evaluateFeatureFlags(flagKeys, distinctId, groups)
} catch {
return undefined
}
diff --git a/services/mcp/src/lib/posthog/flags.ts b/services/mcp/src/lib/posthog/flags.ts
index 9ac24609f27a..853ff9180fa3 100644
--- a/services/mcp/src/lib/posthog/flags.ts
+++ b/services/mcp/src/lib/posthog/flags.ts
@@ -1,9 +1,13 @@
import { getPostHogClient } from './client'
-export async function isFeatureFlagEnabled(flagKey: string, distinctId: string): Promise<boolean> {
+// Group type → group key, matching the `$groups` shape from `buildMCPAnalyticsGroups`.
+export type FlagGroups = Record<string, string>
+
+export async function isFeatureFlagEnabled(flagKey: string, distinctId: string, groups?: FlagGroups): Promise<boolean> {
try {
const client = getPostHogClient()
- const result = await client.isFeatureEnabled(flagKey, distinctId)
+ const hasGroups = groups && Object.keys(groups).length > 0
+ const result = await client.isFeatureEnabled(flagKey, distinctId, hasGroups ? { groups } : undefined)
return result === true
} catch {
return false
@@ -12,16 +16,21 @@ export async function isFeatureFlagEnabled(flagKey: string, distinctId: string):
/**
* Evaluate multiple feature flags in parallel for the given user.
- * Returns a map of flag key → boolean.
+ * Returns a map of flag key → boolean. `groups` is forwarded to posthog-node
+ * so group-scoped rollouts (e.g. per-organization) evaluate correctly.
*/
-export async function evaluateFeatureFlags(flagKeys: string[], distinctId: string): Promise<Record<string, boolean>> {
+export async function evaluateFeatureFlags(
+ flagKeys: string[],
+ distinctId: string,
+ groups?: FlagGroups
+): Promise<Record<string, boolean>> {
if (flagKeys.length === 0) {
return {}
}
const results = await Promise.all(
flagKeys.map(async (key) => {
- const enabled = await isFeatureFlagEnabled(key, distinctId)
+ const enabled = await isFeatureFlagEnabled(key, distinctId, groups)
return [key, enabled] as const
})
)
diff --git a/services/mcp/src/mcp.ts b/services/mcp/src/mcp.ts
index 802574fd864d..03fd969518d6 100644
--- a/services/mcp/src/mcp.ts
+++ b/services/mcp/src/mcp.ts
@@ -28,7 +28,7 @@ import {
McpAnalyticsInitResult,
type MCPAnalyticsContext,
} from '@/lib/posthog/analytics'
-import { evaluateFeatureFlags, isFeatureFlagEnabled } from '@/lib/posthog/flags'
+import { 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'
@@ -564,9 +564,9 @@ export class MCP extends McpAgent<Env> {
// `resolveClientInfo` is only reachable post-init.
await this.resolveClientInfo()
- // Start feature flag resolution in parallel with cache seeding
+ // User-level flags resolve in parallel with cache seeding. Tool flags are
+ // deferred until orgId is known so org-group rollouts evaluate correctly.
const flagPromise = this.resolveVersionFlag()
- const toolFlagsPromise = this.resolveToolFeatureFlags(clientVersion)
const singleExecPromise = this.resolveSingleExecFlag()
// Seed cache with header-provided IDs before any fetches
@@ -596,6 +596,12 @@ export class MCP extends McpAgent<Env> {
await context.stateManager.setDefaultOrganizationAndProject()
}
+ // Flag-eval groups mirror analytics `$groups` so per-organization and per-project
+ // rollouts evaluate against the same entities — see `buildMCPAnalyticsGroups`.
+ const flagAnalyticsContext = await this.getAnalyticsContextSafe(context)
+ const flagGroups = flagAnalyticsContext ? buildMCPAnalyticsGroups(flagAnalyticsContext) : undefined
+ const toolFlagsPromise = this.resolveToolFeatureFlags(clientVersion, flagGroups)
+
const [flagVersion, toolFeatureFlags, singleExecFlagOn, _apiKey] = await Promise.all([
flagPromise,
toolFlagsPromise,
@@ -912,7 +918,10 @@ export class MCP extends McpAgent<Env> {
}
}
- private async resolveToolFeatureFlags(version?: number): Promise<Record<string, boolean> | undefined> {
+ private async resolveToolFeatureFlags(
+ version?: number,
+ groups?: FlagGroups
+ ): Promise<Record<string, boolean> | undefined> {
try {
const { getRequiredFeatureFlags } = await import('@/tools/toolDefinitions')
const flagKeys = getRequiredFeatureFlags(version)
@@ -920,7 +929,7 @@ export class MCP extends McpAgent<Env> {
return undefined
}
const distinctId = await this.getDistinctId()
- return await evaluateFeatureFlags(flagKeys, distinctId)
+ return await evaluateFeatureFlags(flagKeys, distinctId, groups)
} catch {
return undefined
}
diff --git a/services/mcp/tests/unit/feature-flag-version.test.ts b/services/mcp/tests/unit/feature-flag-version.test.ts
index 47bc636e3135..667e6d82f72a 100644
--- a/services/mcp/tests/unit/feature-flag-version.test.ts
+++ b/services/mcp/tests/unit/feature-flag-version.test.ts
@@ -8,7 +8,7 @@ vi.mock('posthog-node', () => ({
}))
// Must import after vi.mock
-import { isFeatureFlagEnabled } from '@/lib/posthog/flags'
+import { evaluateFeatureFlags, isFeatureFlagEnabled } from '@/lib/posthog/flags'
describe('isFeatureFlagEnabled', () => {
beforeEach(() => {
@@ -20,7 +20,7 @@ describe('isFeatureFlagEnabled', () => {
const result = await isFeatureFlagEnabled('mcp-version-2', 'user-123')
expect(result).toBe(true)
- expect(mockIsFeatureEnabled).toHaveBeenCalledWith('mcp-version-2', 'user-123')
+ expect(mockIsFeatureEnabled).toHaveBeenCalledWith('mcp-version-2', 'user-123', undefined)
})
it('should return false when the flag is disabled', async () => {
@@ -43,4 +43,49 @@ describe('isFeatureFlagEnabled', () => {
const result = await isFeatureFlagEnabled('mcp-version-2', 'user-123')
expect(result).toBe(false)
})
+
+ it('should forward groups as options when provided', async () => {
+ mockIsFeatureEnabled.mockResolvedValue(true)
+
+ await isFeatureFlagEnabled('notebooks-collaboration', 'user-123', { organization: 'org-abc' })
+
+ expect(mockIsFeatureEnabled).toHaveBeenCalledWith('notebooks-collaboration', 'user-123', {
+ groups: { organization: 'org-abc' },
+ })
+ })
+
+ it('should omit the options arg when groups is an empty object', async () => {
+ mockIsFeatureEnabled.mockResolvedValue(true)
+
+ await isFeatureFlagEnabled('flag-x', 'user-123', {})
+
+ expect(mockIsFeatureEnabled).toHaveBeenCalledWith('flag-x', 'user-123', undefined)
+ })
+})
+
+describe('evaluateFeatureFlags', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should evaluate multiple flags and forward groups on each call', async () => {
+ mockIsFeatureEnabled.mockImplementation((flagKey: string) => Promise.resolve(flagKey === 'flag-on'))
+
+ const result = await evaluateFeatureFlags(['flag-on', 'flag-off'], 'user-123', { organization: 'org-abc' })
+
+ expect(result).toEqual({ 'flag-on': true, 'flag-off': false })
+ expect(mockIsFeatureEnabled).toHaveBeenCalledWith('flag-on', 'user-123', {
+ groups: { organization: 'org-abc' },
+ })
+ expect(mockIsFeatureEnabled).toHaveBeenCalledWith('flag-off', 'user-123', {
+ groups: { organization: 'org-abc' },
+ })
+ })
+
+ it('should short-circuit when no flag keys are requested', async () => {
+ const result = await evaluateFeatureFlags([], 'user-123', { organization: 'org-abc' })
+
+ expect(result).toEqual({})
+ expect(mockIsFeatureEnabled).not.toHaveBeenCalled()
+ })
})