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): add feature flag test evaluation endpoint and UI app (#55153)

Gustavo H. Strassburger4c9ad819d170
diff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.yml
index c7ac2ee0b87d..acf9c43deb8a 100644
--- a/.github/workflows/ci-mcp.yml
+++ b/.github/workflows/ci-mcp.yml
@@ -251,6 +251,10 @@ jobs:
CLICKHOUSE_LOGS_CLUSTER_SECURE: 'False'
CELERY_METRICS_PORT: 8999
POSTHOG_FEATURE_FLAGS_FORCE_ENABLED: 'logs-alerting'
+ # Required for the feature_flags test_evaluation endpoint, which authenticates
+ # historical-flag override requests to the Rust flags service. Any non-empty
+ # value is fine for CI — the Rust service in the test stack accepts it.
+ INTERNAL_REQUEST_TOKEN: 'mcp-ci-internal-request-token'
steps:
- uses: actions/checkout@v6
@@ -364,6 +368,19 @@ jobs:
run: |
cargo install sqlx-cli --version 0.8.0 --features postgres --no-default-features --locked
+ - name: Build Rust flags service
+ working-directory: rust
+ env:
+ # Debug builds compile much faster than release (~4 min vs ~9 min).
+ # We disable debug assertions because the codebase contains
+ # debug_assert! checks that intentionally panic on data invariant
+ # violations, which would crash the service mid-test-run.
+ RUSTFLAGS: '-C debug-assertions=no'
+ run: cargo build -p feature-flags
+
+ - name: Download MaxMind Database
+ run: ./bin/download-mmdb
+
- name: Start Docker services
shell: bash
env:
@@ -389,6 +406,41 @@ jobs:
python manage.py migrate --noinput
python manage.py migrate_clickhouse
+ - name: Start Rust flags service
+ working-directory: rust
+ env:
+ BIND_HOST: '127.0.0.1'
+ BIND_PORT: '3001'
+ READ_DATABASE_URL: postgres://posthog:posthog@localhost:5432/posthog
+ WRITE_DATABASE_URL: postgres://posthog:posthog@localhost:5432/posthog
+ PERSONS_READ_DATABASE_URL: postgres://posthog:posthog@localhost:5432/posthog_persons
+ PERSONS_WRITE_DATABASE_URL: postgres://posthog:posthog@localhost:5432/posthog_persons
+ REDIS_URL: redis://localhost:6379/
+ CACHE_TTL_SECONDS: '0'
+ RUST_BACKTRACE: '1'
+ run: |
+ ./target/debug/feature-flags > /tmp/rust-flags.log 2>&1 &
+ RUST_FLAGS_PID=$!
+ echo "RUST_FLAGS_PID=$RUST_FLAGS_PID" >> $GITHUB_ENV
+ for i in {1..30}; do
+ if ! kill -0 "$RUST_FLAGS_PID" 2>/dev/null; then
+ echo "ERROR: Rust flags service exited unexpectedly"
+ cat /tmp/rust-flags.log || true
+ exit 1
+ fi
+ if curl -s http://127.0.0.1:3001/_readiness > /dev/null 2>&1; then
+ echo "Rust flags service is ready"
+ break
+ fi
+ echo "Waiting for Rust flags service... ($i/30)"
+ sleep 2
+ done
+ if ! curl -s http://127.0.0.1:3001/_readiness > /dev/null 2>&1; then
+ echo "ERROR: Rust flags service failed to start after 30 attempts"
+ cat /tmp/rust-flags.log || true
+ exit 1
+ fi
+
- name: Seed test data
run: python manage.py generate_demo_data --n-clusters 10 --days-past 7 --days-future 0 --skip-materialization --skip-flag-sync --skip-user-product-list
@@ -451,6 +503,10 @@ jobs:
if: failure()
run: cat /tmp/celery.log || true
+ - name: Show Rust flags service logs on failure
+ if: failure()
+ run: cat /tmp/rust-flags.log || true
+
- name: Show docker compose logs on failure
if: failure()
shell: bash
diff --git a/bin/start b/bin/start
index 2698be71ee37..391f83149881 100755
--- a/bin/start
+++ b/bin/start
@@ -37,6 +37,9 @@ fi
export BILLING_SERVICE_URL=${BILLING_SERVICE_URL:-https://billing.dev.posthog.dev}
export API_QUERIES_PER_TEAM='{"1": 100}'
+# Internal request token for Python <-> Rust service communication
+export INTERNAL_REQUEST_TOKEN=${INTERNAL_REQUEST_TOKEN:-dev-internal-token}
+
# Dagster
export DAGSTER_HOME=$REPOSITORY_ROOT/.dagster_home
export DAGSTER_UI_HOST=${DAGSTER_UI_HOST:-localhost}
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 798548dbecfa..761755f8aae7 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -3410,6 +3410,10 @@ snapshots:
hash: v1.k794b7964.aa3960b581d37e9a411559014b45e0aa699959d440188593cc795ca1696ef69a.lIF61tDsqxT2_hwn3-e0bJ9wJ-snwJSmrhf9BCGgfHQ
mcp-apps-feature-flags--multivariate-flag--light:
hash: v1.k794b7964.05705ec2ca5795bbe1c50bc6b51fdca45b8d9d771972996fdf91ef13f7e0a937.EzIU430T0Q9c_HI7WNVQr3Qf7huzFzLnUrEo_odl9Ds
+ mcp-apps-feature-flags--testing-matched--light:
+ hash: v1.k794b7964.41595a5f077c3d37eb8dd5bd872475e0a1b2d19297722336227757ac3595c89a.SmsLXf8poLxGeLJ4MW3AlLqLwiJCeGW6mzgVyO60GjA
+ mcp-apps-feature-flags--testing-no-match--light:
+ hash: v1.k794b7964.c1cbdb7b5d939c3f65e2893d31c31ab41d5932bf51d4b1491958052495f4f305.cIii_UkqMPXtF9oXeY_I4YBt37qty07EKb-GyAwpYOc
mcp-apps-llm-analytics--empty--light:
hash: v1.k794b7964.4b06add3c54b017f17dd3c72b937f6cb504505ab868caf2b82775afefc6de70c.eIIDY8rVtTESV2D2OU_HMregnxqOCdFR6nohVPm2R28
mcp-apps-llm-analytics--multi-model--light:
diff --git a/products/feature_flags/mcp/apps/FeatureFlagTestingView.tsx b/products/feature_flags/mcp/apps/FeatureFlagTestingView.tsx
new file mode 100644
index 000000000000..6723a8711806
--- /dev/null
+++ b/products/feature_flags/mcp/apps/FeatureFlagTestingView.tsx
@@ -0,0 +1,165 @@
+import type { ReactElement } from 'react'
+
+import { Badge, Card, Stack } from '@posthog/mosaic'
+
+import { PropertyFilterList, type PropertyFilter } from './PropertyFilterList'
+
+export interface ConditionAnalysis {
+ index: number
+ matched: boolean
+ rollout_percentage: number
+ variant?: string | null
+ properties?: Array<{ key: string; value: unknown; operator?: string; type?: string }>
+ reason?: string
+ explanation?: string
+}
+
+export interface FeatureFlagTestEvaluationResult {
+ flag_key: string
+ result: boolean | string
+ reason: string
+ condition_index: number | null
+ payload: unknown | null
+ person_properties: Record<string, unknown>
+ conditions: ConditionAnalysis[]
+}
+
+// Keep the original name for backward compatibility with the generated UI app
+export type FeatureFlagTestingData = FeatureFlagTestEvaluationResult
+
+export interface FeatureFlagTestingViewProps {
+ flag: FeatureFlagTestingData
+}
+
+export function FeatureFlagTestingView({ flag }: FeatureFlagTestingViewProps): ReactElement {
+ const getResultBadgeVariant = (): 'success' | 'danger' | 'info' => {
+ if (typeof flag.result === 'boolean') {
+ return flag.result ? 'success' : 'danger'
+ }
+ return 'info'
+ }
+
+ const formatResult = (): string => {
+ if (typeof flag.result === 'boolean') {
+ return flag.result ? 'True' : 'False'
+ }
+ return String(flag.result)
+ }
+
+ return (
+ <div className="p-4">
+ <Stack gap="md">
+ {/* Header */}
+ <Stack gap="xs">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-lg font-semibold text-text-primary">{flag.flag_key}</span>
+ <Badge variant="neutral" size="md">
+ Test Result
+ </Badge>
+ </div>
+ <span className="text-sm text-text-secondary">
+ Feature flag evaluation result for the tested user
+ </span>
+ </Stack>
+
+ {/* Evaluation Result */}
+ <Card>
+ <Stack gap="sm">
+ <span className="font-medium text-text-primary">Test Evaluation Results</span>
+ <span className="text-sm text-text-secondary">
+ This shows how the flag evaluated for the specified user, including which condition matched
+ and the person properties that were considered.
+ </span>
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">Result:</span>
+ <Badge variant={getResultBadgeVariant()} size="md">
+ {formatResult()}
+ </Badge>
+ </div>
+ <div className="text-sm">
+ <span className="font-medium">Reason: </span>
+ <span className="text-text-secondary">{flag.reason}</span>
+ </div>
+ {flag.condition_index !== null && (
+ <div className="text-sm">
+ <span className="font-medium">Matched condition: </span>
+ <span className="text-text-secondary">#{flag.condition_index + 1}</span>
+ </div>
+ )}
+ {flag.payload != null && (
+ <div className="text-sm">
+ <span className="font-medium">Payload: </span>
+ <code className="text-xs bg-bg-light p-1 rounded">
+ {JSON.stringify(flag.payload) || 'null'}
+ </code>
+ </div>
+ )}
+ </Stack>
+ </Card>
+
+ {/* Person Properties */}
+ {Object.keys(flag.person_properties).length > 0 && (
+ <Card>
+ <Stack gap="sm">
+ <span className="font-medium text-text-primary">Person Properties</span>
+ <div className="space-y-1">
+ {Object.entries(flag.person_properties).map(([key, value]) => (
+ <div key={key} className="flex items-center gap-2 text-sm">
+ <span className="font-mono text-text-primary">{key}:</span>
+ <span className="text-text-secondary">
+ {typeof value === 'object' ? String(JSON.stringify(value)) : String(value)}
+ </span>
+ </div>
+ ))}
+ </div>
+ </Stack>
+ </Card>
+ )}
+
+ {/* Condition Analysis */}
+ {flag.conditions.length > 0 && (
+ <Card>
+ <Stack gap="sm">
+ <span className="font-medium text-text-primary">Condition Analysis</span>
+ <span className="text-sm text-text-secondary">
+ Detailed breakdown of how each condition was evaluated
+ </span>
+ <Stack gap="sm">
+ {flag.conditions.map((condition, index) => (
+ <Card key={index}>
+ <Stack gap="xs">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">Condition</span>
+ <Badge variant={condition.matched ? 'success' : 'danger'} size="sm">
+ {condition.matched ? 'Matched' : 'No match'}
+ </Badge>
+ <Badge variant="neutral" size="sm">
+ {condition.rollout_percentage}% rollout
+ </Badge>
+ {condition.variant && (
+ <Badge variant="info" size="sm">
+ {condition.variant}
+ </Badge>
+ )}
+ </div>
+ {(condition.explanation || condition.reason) && (
+ <div className="text-sm text-text-secondary">
+ {condition.explanation || condition.reason}
+ </div>
+ )}
+ {condition.properties && condition.properties.length > 0 && (
+ <PropertyFilterList
+ filters={condition.properties as PropertyFilter[]}
+ />
+ )}
+ </Stack>
+ </Card>
+ ))}
+ </Stack>
+ </Stack>
+ </Card>
+ )}
+ </Stack>
+ </div>
+ )
+}
diff --git a/products/feature_flags/mcp/apps/FeatureFlags.stories.tsx b/products/feature_flags/mcp/apps/FeatureFlags.stories.tsx
index d4524a6e4532..d2a2d94cdcae 100644
--- a/products/feature_flags/mcp/apps/FeatureFlags.stories.tsx
+++ b/products/feature_flags/mcp/apps/FeatureFlags.stories.tsx
@@ -1,7 +1,14 @@
import { McpThemeDecorator } from '@common/mosaic/storybook/decorator'
import type { Meta, StoryObj } from '@storybook/react'
-import { type FeatureFlagData, type FeatureFlagListData, FeatureFlagListView, FeatureFlagView } from './index'
+import {
+ type FeatureFlagData,
+ type FeatureFlagListData,
+ FeatureFlagListView,
+ type FeatureFlagTestingData,
+ FeatureFlagTestingView,
+ FeatureFlagView,
+} from './index'
const meta: Meta = {
title: 'MCP Apps/Feature Flags',
@@ -114,3 +121,70 @@ export const FlagList: Story = {
render: () => <FeatureFlagListView data={sampleListData} />,
name: 'Flag list',
}
+
+const sampleTestingMatchedData: FeatureFlagTestingData = {
+ flag_key: 'enable-new-dashboard',
+ result: true,
+ reason: 'condition_match',
+ condition_index: 0,
+ payload: { variant: 'control', config: { layout: 'grid' } },
+ person_properties: {
+ email: '[email protected]',
+ plan: 'enterprise',
+ },
+ conditions: [
+ {
+ index: 0,
+ matched: true,
+ rollout_percentage: 100,
+ properties: [{ key: 'email', value: '@posthog.com', operator: 'icontains', type: 'person' }],
+ explanation: 'All properties matched and rollout passed',
+ },
+ {
+ index: 1,
+ matched: false,
+ rollout_percentage: 50,
+ properties: [],
+ explanation: 'Earlier condition already matched',
+ },
+ ],
+}
+
+const sampleTestingNoMatchData: FeatureFlagTestingData = {
+ flag_key: 'checkout-flow-variant',
+ result: false,
+ reason: 'no_condition_match',
+ condition_index: null,
+ payload: null,
+ person_properties: {
+ email: '[email protected]',
+ plan: 'free',
+ },
+ conditions: [
+ {
+ index: 0,
+ matched: false,
+ rollout_percentage: 100,
+ variant: 'test-a',
+ properties: [{ key: 'plan', value: 'enterprise', operator: 'exact', type: 'person' }],
+ explanation: 'Property "plan" did not match: expected "enterprise", got "free"',
+ },
+ {
+ index: 1,
+ matched: false,
+ rollout_percentage: 80,
+ properties: [],
+ explanation: 'User excluded by rollout percentage',
+ },
+ ],
+}
+
+export const TestingMatched: Story = {
+ render: () => <FeatureFlagTestingView flag={sampleTestingMatchedData} />,
+ name: 'Testing view — matched',
+}
+
+export const TestingNoMatch: Story = {
+ render: () => <FeatureFlagTestingView flag={sampleTestingNoMatchData} />,
+ name: 'Testing view — no match',
+}
diff --git a/products/feature_flags/mcp/apps/index.ts b/products/feature_flags/mcp/apps/index.ts
index 75f206fc937e..c6e0da82f60f 100644
--- a/products/feature_flags/mcp/apps/index.ts
+++ b/products/feature_flags/mcp/apps/index.ts
@@ -1,5 +1,12 @@
export { FeatureFlagView, type FeatureFlagData, type FeatureFlagViewProps } from './FeatureFlagView'
export { FeatureFlagListView, type FeatureFlagListData, type FeatureFlagListViewProps } from './FeatureFlagListView'
+export {
+ FeatureFlagTestingView,
+ type FeatureFlagTestingData,
+ type FeatureFlagTestEvaluationResult,
+ type FeatureFlagTestingViewProps,
+ type ConditionAnalysis,
+} from './FeatureFlagTestingView'
export { RolloutBar, type RolloutBarProps } from './RolloutBar'
export { PropertyFilterList, type PropertyFilter, type PropertyFilterListProps } from './PropertyFilterList'
export { VariantTable, type Variant, type VariantTableProps } from './VariantTable'
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index d94cd5a3d8df..9d8bb9e32750 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -17,6 +17,9 @@ ui_apps:
detail_args: '{ flagId: item.id }'
item_name_field: key
click_prop: onFlagClick
+ feature-flag-testing:
+ type: detail
+ view_prop: flag
tools:
create-feature-flag:
operation: feature_flags_create
@@ -213,7 +216,24 @@ tools:
cast: string-int
feature-flags-test-evaluation-create:
operation: feature_flags_test_evaluation_create
- enabled: false
+ enabled: true
+ scopes:
+ - feature_flag:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Test feature flag evaluation
+ description: >
+ Test how a feature flag evaluates for a specific user at an optional point in time. Provides detailed
+ reasoning about why the flag matched or didn't match, including condition analysis and person properties
+ used in evaluation.
+ param_overrides:
+ id:
+ cast: string-int
+ validators:
+ - validateDistinctIdPersonIdExclusive
+ ui_app: feature-flag-testing
feature-flags-update:
operation: feature_flags_update
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 108d86e7ff77..d34bf2855512 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2058,6 +2058,21 @@
"readOnlyHint": true
}
},
+ "feature-flags-test-evaluation-create": {
+ "description": "Test how a feature flag evaluates for a specific user at an optional point in time. Provides detailed reasoning about why the flag matched or didn't match, including condition analysis and person properties used in evaluation.",
+ "category": "Feature flags",
+ "feature": "flags",
+ "summary": "Test feature flag evaluation",
+ "title": "Test feature flag evaluation",
+ "required_scopes": ["feature_flag:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"feature-flags-user-blast-radius-create": {
"description": "Assess the impact of a feature flag release condition before applying it. Provide a condition object and optionally a group_type_index to see how many users would be affected relative to the total user count.",
"category": "Feature flags",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index a58f8cd28243..1fba1cbbb6e4 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2326,6 +2326,21 @@
"readOnlyHint": true
}
},
+ "feature-flags-test-evaluation-create": {
+ "description": "Test how a feature flag evaluates for a specific user at an optional point in time. Provides detailed reasoning about why the flag matched or didn't match, including condition analysis and person properties used in evaluation.",
+ "category": "Feature flags",
+ "feature": "flags",
+ "summary": "Test feature flag evaluation",
+ "title": "Test feature flag evaluation",
+ "required_scopes": ["feature_flag:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"feature-flags-user-blast-radius-create": {
"description": "Assess the impact of a feature flag release condition before applying it. Provide a condition object and optionally a group_type_index to see how many users would be affected relative to the total user count.",
"category": "Feature flags",
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index cf5ac7dacd30..093ab2c73ae4 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -792,7 +792,15 @@ function generateToolCode(
}
}
- const schemaDecl = `const ${schemaName} = ${composition.schemaExpr}`
+ let schemaExpr = composition.schemaExpr
+ if (config.validators && config.validators.length > 0) {
+ for (const fn of config.validators) {
+ schemaExpr = `(${schemaExpr}).superRefine(${fn})`
+ composition.toolInputsImports.push(fn)
+ }
+ }
+
+ const schemaDecl = `const ${schemaName} = ${schemaExpr}`
const localVarParams = new Set(Object.keys(composition.paramFallbacks))
const pathExpr = buildPathExpr(resolved.path, composition.pathParamNames, 'params.', localVarParams)
@@ -1016,8 +1024,17 @@ function generateCustomSchemaToolCode(
const mcpVersionLine = config.mcp_version !== undefined ? `\n mcpVersion: ${config.mcp_version},` : ''
+ let baseSchemaExpr = config.input_schema as string
+ const toolInputsImports: string[] = config.input_schema ? [config.input_schema] : []
+ if (config.validators && config.validators.length > 0) {
+ for (const fn of config.validators) {
+ baseSchemaExpr = `(${baseSchemaExpr}).superRefine(${fn})`
+ toolInputsImports.push(fn)
+ }
+ }
+
const code = `
-const ${schemaName} = ${config.input_schema}
+const ${schemaName} = ${baseSchemaExpr}
const ${factoryName} = (): ToolBase<typeof ${schemaName}, ${responseType ?? 'unknown'}> => ({
name: '${toolName}',
@@ -1030,7 +1047,7 @@ ${handlerBody} },
return {
code,
orvalImports: [],
- toolInputsImports: config.input_schema ? [config.input_schema] : [],
+ toolInputsImports,
castHelperImports: new Set(),
schemaRefBlocks: [],
responseType,
diff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.ts
index e50eb79158c7..de05c88a36ae 100644
--- a/services/mcp/scripts/yaml-config-schema.ts
+++ b/services/mcp/scripts/yaml-config-schema.ts
@@ -98,6 +98,15 @@ export const ToolConfigSchema = z
)
.optional(),
mcp_version: z.number().int().positive().optional(),
+ /**
+ * Cross-field refinements applied to the composed tool schema.
+ * Each entry names a function exported from `@/schema/tool-inputs` whose
+ * signature is `(data, ctx: z.RefinementCtx) => void`. The codegen wires
+ * one `.superRefine(<fn>)` call per entry, in order. Use this when a single
+ * field's schema can't express the rule (e.g. mutual exclusivity between
+ * two optional fields).
+ */
+ validators: z.array(z.string()).optional(),
/** References a key in ui_apps. */
ui_app: z.string().optional(),
/**
diff --git a/services/mcp/src/generated/feature_flags/api.ts b/services/mcp/src/generated/feature_flags/api.ts
index 06fcdbaa66a4..4c01b88dfe19 100644
--- a/services/mcp/src/generated/feature_flags/api.ts
+++ b/services/mcp/src/generated/feature_flags/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 16 enabled ops
+ * PostHog API - MCP 17 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -767,6 +767,40 @@ export const FeatureFlagsStatusRetrieveParams = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Test feature flag evaluation against a specific user at an optional point in time.
+
+This endpoint allows testing how a feature flag would evaluate for a specific user,
+optionally at a historical timestamp. When a timestamp is provided, both the flag
+conditions and person properties are evaluated as they existed at that time.
+ */
+export const FeatureFlagsTestEvaluationCreateParams = /* @__PURE__ */ zod.object({
+ id: zod.number().describe('A unique integer value identifying this feature flag.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const FeatureFlagsTestEvaluationCreateBody = /* @__PURE__ */ zod.object({
+ distinct_id: zod
+ .string()
+ .optional()
+ .describe('User distinct ID to test against (mutually exclusive with person_id)'),
+ person_id: zod.string().optional().describe('Person ID to test against (mutually exclusive with distinct_id)'),
+ timestamp: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe(
+ 'Optional point-in-time to evaluate the flag against — both flag conditions and person properties are reconstructed as they existed at that timestamp. ISO 8601 with timezone, e.g. ``2026-04-29T15:30:00Z`` or ``2026-04-29T15:30:00+00:00``. Naive timestamps (no timezone) are interpreted as UTC.'
+ ),
+ groups: zod
+ .unknown()
+ .optional()
+ .describe('Groups for feature flag evaluation (JSON object, defaults to empty dict)'),
+})
+
/**
* Create, read, update and delete feature flags. [See docs](https://posthog.com/docs/feature-flags) for more information on feature flags.
diff --git a/services/mcp/src/resources/ui-apps.generated.ts b/services/mcp/src/resources/ui-apps.generated.ts
index bbf798d5a9c0..0900e8411d63 100644
--- a/services/mcp/src/resources/ui-apps.generated.ts
+++ b/services/mcp/src/resources/ui-apps.generated.ts
@@ -13,6 +13,7 @@ export const EXPERIMENT_LIST_RESOURCE_URI = 'ui://posthog/experiment-list.html'
export const EXPERIMENT_RESULTS_RESOURCE_URI = 'ui://posthog/experiment-results.html'
export const FEATURE_FLAG_RESOURCE_URI = 'ui://posthog/feature-flag.html'
export const FEATURE_FLAG_LIST_RESOURCE_URI = 'ui://posthog/feature-flag-list.html'
+export const FEATURE_FLAG_TESTING_RESOURCE_URI = 'ui://posthog/feature-flag-testing.html'
export const INSIGHT_ACTORS_RESOURCE_URI = 'ui://posthog/insight-actors.html'
export const LLM_COSTS_RESOURCE_URI = 'ui://posthog/llm-costs.html'
export const QUERY_RESULTS_RESOURCE_URI = 'ui://posthog/query-results.html'
@@ -41,6 +42,7 @@ export type UiAppKey =
| 'experiment-results'
| 'feature-flag'
| 'feature-flag-list'
+ | 'feature-flag-testing'
| 'insight-actors'
| 'llm-costs'
| 'query-results'
@@ -69,6 +71,7 @@ export const URI_MAP: Record<UiAppKey, string> = {
'experiment-results': EXPERIMENT_RESULTS_RESOURCE_URI,
'feature-flag': FEATURE_FLAG_RESOURCE_URI,
'feature-flag-list': FEATURE_FLAG_LIST_RESOURCE_URI,
+ 'feature-flag-testing': FEATURE_FLAG_TESTING_RESOURCE_URI,
'insight-actors': INSIGHT_ACTORS_RESOURCE_URI,
'llm-costs': LLM_COSTS_RESOURCE_URI,
'query-results': QUERY_RESULTS_RESOURCE_URI,
@@ -168,6 +171,12 @@ export const UI_APPS: Array<{
description: 'Feature Flag List view',
appDir: 'generated/feature-flag-list',
},
+ {
+ name: 'PostHog Feature Flag Testing',
+ uri: FEATURE_FLAG_TESTING_RESOURCE_URI,
+ description: 'Feature Flag Testing detail view',
+ appDir: 'generated/feature-flag-testing',
+ },
{
name: 'PostHog Insight Actors',
uri: INSIGHT_ACTORS_RESOURCE_URI,
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 222804807e65..11cea83a69e2 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -665,3 +665,25 @@ export const ReadDataSchemaSchema = z.object({
])
.describe('The data schema query to execute.'),
})
+
+// Mirrors the Django serializer's `validate` rule so the MCP layer fails fast
+// instead of forwarding an empty/ambiguous body and waiting for a 400.
+export function validateDistinctIdPersonIdExclusive(
+ data: { distinct_id?: string | undefined; person_id?: string | undefined },
+ ctx: z.RefinementCtx
+): void {
+ const hasDistinctId = typeof data.distinct_id === 'string' && data.distinct_id.length > 0
+ const hasPersonId = typeof data.person_id === 'string' && data.person_id.length > 0
+ if (!hasDistinctId && !hasPersonId) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'Either distinct_id or person_id must be provided',
+ })
+ }
+ if (hasDistinctId && hasPersonId) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'Cannot provide both distinct_id and person_id (they are mutually exclusive)',
+ })
+ }
+}
diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.ts
index 0fdfaee457ad..0d863208f1e3 100644
--- a/services/mcp/src/tools/generated/feature_flags.ts
+++ b/services/mcp/src/tools/generated/feature_flags.ts
@@ -15,6 +15,8 @@ import {
FeatureFlagsPartialUpdateParams,
FeatureFlagsRetrieveParams,
FeatureFlagsStatusRetrieveParams,
+ FeatureFlagsTestEvaluationCreateBody,
+ FeatureFlagsTestEvaluationCreateParams,
FeatureFlagsUserBlastRadiusCreateBody,
ScheduledChangesCreateBody,
ScheduledChangesDestroyParams,
@@ -23,6 +25,8 @@ import {
ScheduledChangesPartialUpdateParams,
ScheduledChangesRetrieveParams,
} from '@/generated/feature_flags/api'
+import { withUiApp } from '@/resources/ui-apps'
+import { validateDistinctIdPersonIdExclusive } from '@/schema/tool-inputs'
import { castStringToInt } from '@/tools/cast-helpers'
import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
@@ -272,6 +276,42 @@ const featureFlagsStatusRetrieve = (): ToolBase<
},
})
+const FeatureFlagsTestEvaluationCreateSchema = FeatureFlagsTestEvaluationCreateParams.omit({ project_id: true })
+ .extend(FeatureFlagsTestEvaluationCreateBody.shape)
+ .extend({ id: z.preprocess(castStringToInt, FeatureFlagsTestEvaluationCreateParams.shape['id']) })
+ .superRefine(validateDistinctIdPersonIdExclusive)
+
+const featureFlagsTestEvaluationCreate = (): ToolBase<
+ typeof FeatureFlagsTestEvaluationCreateSchema,
+ Schemas.FeatureFlagTestEvaluationResponse
+> =>
+ withUiApp('feature-flag-testing', {
+ name: 'feature-flags-test-evaluation-create',
+ schema: FeatureFlagsTestEvaluationCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof FeatureFlagsTestEvaluationCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.distinct_id !== undefined) {
+ body['distinct_id'] = params.distinct_id
+ }
+ if (params.person_id !== undefined) {
+ body['person_id'] = params.person_id
+ }
+ if (params.timestamp !== undefined) {
+ body['timestamp'] = params.timestamp
+ }
+ if (params.groups !== undefined) {
+ body['groups'] = params.groups
+ }
+ const result = await context.api.request<Schemas.FeatureFlagTestEvaluationResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/test_evaluation/`,
+ body,
+ })
+ return result
+ },
+ })
+
const FeatureFlagsUserBlastRadiusCreateSchema = FeatureFlagsUserBlastRadiusCreateBody
const featureFlagsUserBlastRadiusCreate = (): ToolBase<
@@ -490,6 +530,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'feature-flags-dependent-flags-retrieve': featureFlagsDependentFlagsRetrieve,
'feature-flags-evaluation-reasons-retrieve': featureFlagsEvaluationReasonsRetrieve,
'feature-flags-status-retrieve': featureFlagsStatusRetrieve,
+ 'feature-flags-test-evaluation-create': featureFlagsTestEvaluationCreate,
'feature-flags-user-blast-radius-create': featureFlagsUserBlastRadiusCreate,
'scheduled-changes-create': scheduledChangesCreate,
'scheduled-changes-delete': scheduledChangesDelete,
diff --git a/services/mcp/src/ui-apps/apps/generated/feature-flag-testing.tsx b/services/mcp/src/ui-apps/apps/generated/feature-flag-testing.tsx
new file mode 100644
index 000000000000..9808567870b8
--- /dev/null
+++ b/services/mcp/src/ui-apps/apps/generated/feature-flag-testing.tsx
@@ -0,0 +1,21 @@
+// AUTO-GENERATED by generate-ui-apps.ts — do not edit
+import '../../styles/tailwind.css'
+
+import { createRoot } from 'react-dom/client'
+
+import { type FeatureFlagTestingData, FeatureFlagTestingView } from 'products/feature_flags/mcp/apps'
+
+import { AppWrapper } from '../../components/AppWrapper'
+
+function FeatureFlagTestingApp(): JSX.Element {
+ return (
+ <AppWrapper<FeatureFlagTestingData> appName="PostHog Feature Flag Testing">
+ {({ data }) => <FeatureFlagTestingView flag={data!} />}
+ </AppWrapper>
+ )
+}
+
+const container = document.getElementById('root')
+if (container) {
+ createRoot(container).render(<FeatureFlagTestingApp />)
+}
diff --git a/services/mcp/tests/tools/featureFlags.integration.test.ts b/services/mcp/tests/tools/featureFlags.integration.test.ts
index efd2b3e3bc50..34c78cd7b7aa 100644
--- a/services/mcp/tests/tools/featureFlags.integration.test.ts
+++ b/services/mcp/tests/tools/featureFlags.integration.test.ts
@@ -13,6 +13,7 @@ import {
validateEnvironmentVariables,
} from '@/shared/test-utils'
import { GENERATED_TOOLS } from '@/tools/generated/feature_flags'
+import { GENERATED_TOOLS as PERSONS_GENERATED_TOOLS } from '@/tools/generated/persons'
import type { Context } from '@/tools/types'
describe('Feature flags', { concurrent: false }, () => {
@@ -283,6 +284,50 @@ describe('Feature flags', { concurrent: false }, () => {
})
})
+ describe('feature-flags-test-evaluation-create tool', () => {
+ const testEvaluationTool = GENERATED_TOOLS['feature-flags-test-evaluation-create']!()
+ const createTool = GENERATED_TOOLS['create-feature-flag']!()
+ const personsListTool = PERSONS_GENERATED_TOOLS['persons-list']!()
+
+ it('should evaluate a feature flag for a real distinct_id', async () => {
+ const personsResult = await personsListTool.handler(context, { limit: 100 })
+ const personsResponse = parseToolResponse(personsResult)
+ const personWithDistinctId = personsResponse.results.find(
+ (p: { distinct_ids?: string[] }) => p.distinct_ids && p.distinct_ids.length > 0
+ )
+
+ if (!personWithDistinctId) {
+ console.warn('No persons with distinct_ids found in project, skipping test')
+ return
+ }
+
+ const distinctId: string = personWithDistinctId.distinct_ids[0]
+
+ const createResult = await createTool.handler(context, {
+ name: 'Test evaluation flag',
+ key: generateUniqueKey('test-eval'),
+ filters: {
+ groups: [{ properties: [], rollout_percentage: 100 }],
+ },
+ active: true,
+ })
+ const createdFlag = parseToolResponse(createResult)
+ createdResources.featureFlags.push(createdFlag.id)
+
+ const result = await testEvaluationTool.handler(context, {
+ id: createdFlag.id,
+ distinct_id: distinctId,
+ })
+ const evaluation = parseToolResponse(result)
+
+ expect(evaluation.flag_key).toBe(createdFlag.key)
+ expect(evaluation.result).toBe(true)
+ expect(typeof evaluation.reason).toBe('string')
+ expect(Array.isArray(evaluation.conditions)).toBe(true)
+ expect(evaluation.person_properties).toBeTruthy()
+ })
+ })
+
describe('Feature flag workflow', () => {
it('should support full CRUD workflow', async () => {
const createTool = GENERATED_TOOLS['create-feature-flag']!()
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/feature-flags-test-evaluation-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/feature-flags-test-evaluation-create.json
new file mode 100644
index 000000000000..6574fe01638f
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/feature-flags-test-evaluation-create.json
@@ -0,0 +1,35 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "distinct_id": {
+ "description": "User distinct ID to test against (mutually exclusive with person_id)",
+ "type": "string"
+ },
+ "groups": {
+ "description": "Groups for feature flag evaluation (JSON object, defaults to empty dict)"
+ },
+ "id": {
+ "description": "A unique integer value identifying this feature flag.",
+ "type": "number"
+ },
+ "person_id": {
+ "description": "Person ID to test against (mutually exclusive with distinct_id)",
+ "type": "string"
+ },
+ "timestamp": {
+ "anyOf": [
+ {
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional point-in-time to evaluate the flag against — both flag conditions and person properties are reconstructed as they existed at that timestamp. ISO 8601 with timezone, e.g. ``2026-04-29T15:30:00Z`` or ``2026-04-29T15:30:00+00:00``. Naive timestamps (no timezone) are interpreted as UTC."
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/feature-flag-test-evaluation-schema.test.ts b/services/mcp/tests/unit/feature-flag-test-evaluation-schema.test.ts
new file mode 100644
index 000000000000..91b63411177a
--- /dev/null
+++ b/services/mcp/tests/unit/feature-flag-test-evaluation-schema.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest'
+
+import { GENERATED_TOOLS } from '@/tools/generated/feature_flags'
+
+describe('feature-flags-test-evaluation-create schema', () => {
+ const tool = GENERATED_TOOLS['feature-flags-test-evaluation-create']!()
+
+ it('rejects when neither distinct_id nor person_id is provided', () => {
+ const result = tool.schema.safeParse({ id: 1 })
+ expect(result.success).toBe(false)
+ if (!result.success) {
+ expect(result.error.issues[0]?.message).toMatch(/distinct_id or person_id/i)
+ }
+ })
+
+ it('rejects when both distinct_id and person_id are provided', () => {
+ const result = tool.schema.safeParse({ id: 1, distinct_id: 'a', person_id: 'b' })
+ expect(result.success).toBe(false)
+ if (!result.success) {
+ expect(result.error.issues[0]?.message).toMatch(/mutually exclusive|both/i)
+ }
+ })
+
+ it('accepts with only distinct_id', () => {
+ const result = tool.schema.safeParse({ id: 1, distinct_id: 'a' })
+ expect(result.success).toBe(true)
+ })
+
+ it('accepts with only person_id', () => {
+ const result = tool.schema.safeParse({ id: 1, person_id: 'b' })
+ expect(result.success).toBe(true)
+ })
+
+ it('accepts a string id and casts it to a number', () => {
+ const result = tool.schema.safeParse({ id: '42', distinct_id: 'a' })
+ expect(result.success).toBe(true)
+ if (result.success) {
+ expect(result.data.id).toBe(42)
+ }
+ })
+})
diff --git a/services/mcp/tests/unit/ui-apps.test.ts b/services/mcp/tests/unit/ui-apps.test.ts
index 2a984d9d1708..91463fc3cffd 100644
--- a/services/mcp/tests/unit/ui-apps.test.ts
+++ b/services/mcp/tests/unit/ui-apps.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import { buildAppStubHtml } from '@/resources/ui-apps'
-import { UI_APPS } from '@/resources/ui-apps.generated'
+import { UI_APPS, URI_MAP } from '@/resources/ui-apps.generated'
describe('ui-apps', () => {
describe('buildAppStubHtml', () => {
@@ -116,7 +116,10 @@ describe('ui-apps', () => {
expect(registeredNames).toContain('MCP Apps Debug')
expect(registeredNames).toContain('Query Results')
expect(registeredNames).toContain('PostHog Feature Flag')
+ expect(registeredNames).toContain('PostHog Feature Flag Testing')
expect(registeredNames).toContain('PostHog Experiment Results')
+
+ expect(URI_MAP['feature-flag-testing']).toBe('ui://posthog/feature-flag-testing.html')
})
it('includes base URL in CSP resourceDomains', async () => {