: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(experiments): send flag config via the feature_flag object (#68867)
Andersa507648e88b8
diff --git a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.tsindex 2922be505809..3cef8a56a289 100644--- a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts+++ b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts@@ -34,6 +34,11 @@ describe('createExperimentLogic', () => {sessionStorage.clear()useMocks({+ get: {+ // saveExperiment verifies flag-key availability before building the payload+ '/api/projects/:team_id/feature_flags/': () => [200, { results: [], count: 0 }],+ '/api/projects/:team_id/experiments': () => [200, { results: [], count: 0 }],+ },post: {[`/api/projects/${MOCK_TEAM_ID}/experiments`]: async ({ request }) => {const body = (await request.json()) as Experimentdiff --git a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.tsindex 9165049229be..eee3f42fcc77 100644--- a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts@@ -24,6 +24,7 @@ import type { Experiment, FeatureFlagFilters, MultivariateFlagVariant } from '~/import { NEW_EXPERIMENT } from '../constants'import { FORM_MODES, experimentLogic } from '../experimentLogic'import { experimentSceneLogic } from '../experimentSceneLogic'+import { toExperimentWritePayload } from '../utils'import type { createExperimentLogicType } from './createExperimentLogicType'import { validateExperimentSubmission } from './experimentSubmissionValidation'import type { FeatureFlagKeyValidation } from './variantsPanelLogic'@@ -336,6 +337,27 @@ export const createExperimentLogic = kea<createExperimentLogicType>([// Set loading state after all validation passesactions.saveExperimentStarted()+ // Whether the key is available decides whether flag config is sent (an available key+ // means the backend creates the flag and applies the config; an existing key means the+ // experiment links to that flag as-is and explicit config is rejected). A missing or+ // stale availability check must not decide this silently: re-run it, and fail loud if+ // it still can't complete.+ const flagKey = values.experiment.feature_flag_key+ const panelLogic = variantsPanelLogic({ experiment: { ...NEW_EXPERIMENT }, disabled: false })+ if (values.featureFlagKeyValidation?.key !== flagKey) {+ try {+ await panelLogic.asyncActions.validateFeatureFlagKey(flagKey)+ } catch {+ // Handled below: featureFlagKeyValidation stays stale or null.+ }+ }+ const keyValidation = panelLogic.values.featureFlagKeyValidation+ if (keyValidation?.key !== flagKey) {+ lemonToast.error("Couldn't verify the feature flag key. Please try again.")+ actions.saveExperimentFailure()+ return+ }+try {const savedMetrics = [...values.sharedMetrics.primary.map((metric) => ({@@ -352,8 +374,13 @@ export const createExperimentLogic = kea<createExperimentLogicType>([})),]- const experimentPayload: Experiment = {- ...values.experiment,+ // A key confirmed available means the backend will create the flag and can apply+ // config to it; a taken key means the experiment links to the pre-existing flag+ // as-is, and the API rejects explicit flag config.+ const experimentPayload = {+ ...toExperimentWritePayload(values.experiment, {+ omitFlagConfig: keyValidation.valid !== true,+ }),saved_metrics_ids: savedMetrics,}diff --git a/frontend/src/scenes/experiments/ExperimentForm/variantsPanelLogic.ts b/frontend/src/scenes/experiments/ExperimentForm/variantsPanelLogic.tsindex f5dc3489ef44..c47bf64278ae 100644--- a/frontend/src/scenes/experiments/ExperimentForm/variantsPanelLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentForm/variantsPanelLogic.ts@@ -15,6 +15,8 @@ export type FeatureFlagKeyValidation = {valid: booleanerror: string | nullexistingFlag?: FeatureFlagType+ /** The key this result validated, so consumers can detect a stale result after the key changed. */+ key?: string}export const variantsPanelLogic = kea<variantsPanelLogicType>({@@ -90,7 +92,7 @@ export const variantsPanelLogic = kea<variantsPanelLogicType>({// First do client-side validationconst clientError = validateFeatureFlagKey(key)if (clientError) {- return { valid: false, error: clientError }+ return { valid: false, error: clientError, key }}// Check if key already exists in our unavailable keys set@@ -102,6 +104,7 @@ export const variantsPanelLogic = kea<variantsPanelLogicType>({valid: false,error: 'A feature flag with this key already exists.',existingFlag,+ key,}}@@ -117,11 +120,12 @@ export const variantsPanelLogic = kea<variantsPanelLogicType>({valid: false,error: 'A feature flag with this key already exists.',existingFlag: exactMatch,+ key,}}}- return { valid: true, error: null }+ return { valid: true, error: null, key }},clearFeatureFlagKeyValidation: () => null,},diff --git a/frontend/src/scenes/experiments/ExperimentTabContent/CreateDraftExperimentCard.tsx b/frontend/src/scenes/experiments/ExperimentTabContent/CreateDraftExperimentCard.tsxindex 7e76dd90e2ec..036da44c5d37 100644--- a/frontend/src/scenes/experiments/ExperimentTabContent/CreateDraftExperimentCard.tsx+++ b/frontend/src/scenes/experiments/ExperimentTabContent/CreateDraftExperimentCard.tsx@@ -14,7 +14,6 @@ export interface CreateDraftExperimentCardProps {export function CreateDraftExperimentCard({ featureFlag }: CreateDraftExperimentCardProps): JSX.Element {const logic = createDraftExperimentFromFlagLogic({featureFlagKey: featureFlag.key,- featureFlagVariants: featureFlag.filters.multivariate?.variants || [],})const { experimentName, experimentDescription, isLoading, error } = useValues(logic)diff --git a/frontend/src/scenes/experiments/ExperimentTabContent/createDraftExperimentFromFlagLogic.ts b/frontend/src/scenes/experiments/ExperimentTabContent/createDraftExperimentFromFlagLogic.tsindex 4861b613eafe..74296de57743 100644--- a/frontend/src/scenes/experiments/ExperimentTabContent/createDraftExperimentFromFlagLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentTabContent/createDraftExperimentFromFlagLogic.ts@@ -7,13 +7,12 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'-import type { Experiment, MultivariateFlagVariant } from '~/types'+import type { Experiment } from '~/types'import type { createDraftExperimentFromFlagLogicType } from './createDraftExperimentFromFlagLogicType'export interface CreateDraftExperimentFromFlagLogicProps {featureFlagKey: string- featureFlagVariants: MultivariateFlagVariant[]}export const createDraftExperimentFromFlagLogic = kea<createDraftExperimentFromFlagLogicType>([@@ -63,18 +62,13 @@ export const createDraftExperimentFromFlagLogic = kea<createDraftExperimentFromFreturn}+ // No flag config in the payload: the flag already exists, so the experiment links+ // to it as-is (its variants carry over) and explicit config would be rejected.const payload = {name,description: values.experimentDescription.trim() || '',type: 'product',feature_flag_key: props.featureFlagKey,- parameters: {- feature_flag_variants: props.featureFlagVariants.map((v) => ({- key: v.key,- rollout_percentage: v.rollout_percentage,- })),- rollout_percentage: 100,- },exposure_criteria: {filterTestAccounts: true,},diff --git a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsxindex 90d35658d0b6..bcf45e482d56 100644--- a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx+++ b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx@@ -207,6 +207,7 @@ describe('experimentWizardLogic', () => {vpLogic.actions.validateFeatureFlagKeySuccess({valid: false,error: 'A feature flag with this key already exists.',+ key: 'existing-flag',existingFlag: mockEligibleFlags[0] as FeatureFlagType,})@@ -238,6 +239,7 @@ describe('experimentWizardLogic', () => {vpLogic.actions.validateFeatureFlagKeySuccess({valid: false,error: 'A feature flag with this key already exists.',+ key: 'existing-flag',existingFlag: flag,})@@ -571,10 +573,15 @@ describe('experimentWizardLogic', () => {vpLogic.actions.validateFeatureFlagKeySuccess({valid: false,error: 'A feature flag with this key already exists.',+ key: 'existing-flag',})await expectLogic(logic).toMatchValues({- featureFlagKeyValidation: { valid: false, error: 'A feature flag with this key already exists.' },+ featureFlagKeyValidation: {+ valid: false,+ error: 'A feature flag with this key already exists.',+ key: 'existing-flag',+ },stepValidationErrors: partial({about: ['A feature flag with this key already exists.'],}),@@ -588,6 +595,7 @@ describe('experimentWizardLogic', () => {vpLogic.actions.validateFeatureFlagKeySuccess({valid: false,error: 'A feature flag with this key already exists.',+ key: 'existing-flag',})await expectLogic(logic).toMatchValues({@@ -679,6 +687,12 @@ describe('experimentWizardLogic', () => {it('posts the experiment to the backend on save', async () => {createLogic.actions.setExperimentValue('name', 'Ship it')createLogic.actions.setExperimentValue('feature_flag_key', 'ship-it')+ // The About step validates the key as the user types; a confirmed-available key is+ // what makes the save send the flag config (via the feature_flag object).+ logic.actions.validateFeatureFlagKey('ship-it')+ await waitFor(() => {+ expect(createLogic.values.featureFlagKeyValidation).toMatchObject({ valid: true })+ })logic.actions.saveExperiment()@@ -689,13 +703,19 @@ describe('experimentWizardLogic', () => {expect(capturedPayload).toMatchObject({name: 'Ship it',feature_flag_key: 'ship-it',- parameters: expect.objectContaining({- feature_flag_variants: expect.arrayContaining([- expect.objectContaining({ key: 'control' }),- expect.objectContaining({ key: 'test' }),- ]),- }),+ feature_flag: {+ filters: expect.objectContaining({+ multivariate: {+ variants: expect.arrayContaining([+ expect.objectContaining({ key: 'control' }),+ expect.objectContaining({ key: 'test' }),+ ]),+ },+ }),+ },})+ // Flag config no longer travels through the deprecated parameters keys.+ expect(capturedPayload.parameters).not.toHaveProperty('feature_flag_variants')})})diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.tsindex 7c297adcc9e9..73df067ed3ec 100644--- a/frontend/src/scenes/experiments/experimentLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts@@ -1657,19 +1657,24 @@ describe('experimentLogic', () => {expect(api.update).toHaveBeenCalledWith(expect.stringContaining('/experiments/'),expect.objectContaining({- parameters: expect.objectContaining({- feature_flag_variants: [- { key: 'control', rollout_percentage: 75 },- { key: 'test', rollout_percentage: 25 },- ],- }),+ feature_flag: {+ filters: {+ multivariate: {+ variants: [+ { key: 'control', rollout_percentage: 75 },+ { key: 'test', rollout_percentage: 25 },+ ],+ },+ },+ },holdout_id: experiment.holdout_id,update_feature_flag_params: true,}))- // Should not send rollout_percentage — it's not editable in the distribution modal- const sentParams = (api.update.mock.calls[0][1] as Record<string, any>).parameters- expect(sentParams).not.toHaveProperty('rollout_percentage')+ // No rollout group when the caller omits rolloutPercentage (the modal itself always+ // passes one; this covers the omit branch)+ const sentFlagFilters = (api.update.mock.calls[0][1] as Record<string, any>).feature_flag.filters+ expect(sentFlagFilters).not.toHaveProperty('groups')})it('does not call feature flag API directly', async () => {diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsxindex 275e3de3ffa9..635d13dabca5 100644--- a/frontend/src/scenes/experiments/experimentLogic.tsx+++ b/frontend/src/scenes/experiments/experimentLogic.tsx@@ -107,11 +107,14 @@ import { modalsLogic } from './modalsLogic'import { SharedMetric } from './SharedMetrics/sharedMetricLogic'import { sharedMetricsLogic } from './SharedMetrics/sharedMetricsLogic'import {+ type ExperimentUpdatePayload,featureFlagEligibleForExperiment,getExperimentVariants,getOrderedMetricsWithResults,initializeMetricOrdering,isLegacyExperiment,+ toExperimentWritePayload,+ toFlagVariantsInput,} from './utils'export const NEW_EXPERIMENT: Experiment = {@@ -1260,7 +1263,9 @@ export const experimentLogic = kea<experimentLogicType>([response = await api.update(`api/projects/${values.currentProjectId}/experiments/${values.experimentId}`,{- ...values.experiment,+ // Sends variant split and rollout through the feature_flag object,+ // dropping the deprecated flag-config parameters keys.+ ...toExperimentWritePayload(values.experiment),running_time_calculation: {...values.experiment?.running_time_calculation,recommended_running_time: recommendedRunningTime,@@ -1291,7 +1296,13 @@ export const experimentLogic = kea<experimentLogicType>([}} else {response = await api.create(`api/projects/${values.currentProjectId}/experiments`, {- ...values.experiment,+ // A pre-existing flag is linked as-is: the API rejects explicit flag+ // config for it, so only send config when the flag will be created.+ // Key-aware so a stale match for a previously typed key can't suppress+ // config for a fresh key.+ ...toExperimentWritePayload(values.experiment, {+ omitFlagConfig: values.validExistingFeatureFlag?.key === values.experiment.feature_flag_key,+ }),running_time_calculation:/*** only if we are creating a new experiment we need to reset@@ -1782,12 +1793,14 @@ export const experimentLogic = kea<experimentLogicType>([}},updateDistribution: async ({ variants, rolloutPercentage }) => {- const { rollout_percentage: _, ...otherParams } = values.experiment?.parameters || {}actions.updateExperiment({- parameters: {- ...otherParams,- feature_flag_variants: variants,- ...(rolloutPercentage !== undefined ? { rollout_percentage: rolloutPercentage } : {}),+ feature_flag: {+ filters: {+ multivariate: { variants: toFlagVariantsInput(variants) },+ ...(rolloutPercentage !== undefined+ ? { groups: [{ properties: [], rollout_percentage: rolloutPercentage }] }+ : {}),+ },},holdout_id: values.experiment.holdout_id,update_feature_flag_params: true,@@ -2502,7 +2515,7 @@ export const experimentLogic = kea<experimentLogicType>([experimentUpdate: [null as Experiment | null,{- updateExperiment: async (update: Partial<Experiment> & { update_feature_flag_params?: boolean }) => {+ updateExperiment: async (update: ExperimentUpdatePayload) => {const response: Experiment = await api.update(`api/projects/${values.currentProjectId}/experiments/${values.experimentId}`,updatediff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.tsindex 9d49ea8947fd..788ddcabe2ac 100644--- a/frontend/src/scenes/experiments/utils.test.ts+++ b/frontend/src/scenes/experiments/utils.test.ts@@ -41,6 +41,7 @@ import {isLegacyExperimentQuery,metricResults,percentageDistribution,+ toExperimentWritePayload,} from './utils'describe('utils', () => {@@ -1585,3 +1586,59 @@ describe('getEventCountQuery', () => {expect(query).toBeNull()})})++describe('toExperimentWritePayload', () => {+ const experiment = {+ name: 'test',+ feature_flag: { id: 456, key: 'test-flag' },+ parameters: {+ feature_flag_variants: [+ { key: 'control', name: null, rollout_percentage: 60 },+ { key: 'test', name: 'Test', rollout_percentage: 40 },+ ],+ rollout_percentage: 80,+ aggregation_group_type_index: 1,+ feature_flag_payloads: { test: '"v1"' },+ ensure_experience_continuity: false,+ variant_notes: { control: 'baseline' },+ },+ } as unknown as Experiment++ it('moves flag config from parameters into the feature_flag object and drops the echoed flag', () => {+ expect(toExperimentWritePayload(experiment)).toEqual({+ name: 'test',+ parameters: { variant_notes: { control: 'baseline' } },+ feature_flag: {+ filters: {+ multivariate: {+ variants: [+ { key: 'control', rollout_percentage: 60 },+ { key: 'test', name: 'Test', rollout_percentage: 40 },+ ],+ },+ groups: [{ properties: [], rollout_percentage: 80 }],+ aggregation_group_type_index: 1,+ payloads: { test: '"v1"' },+ },+ ensure_experience_continuity: false,+ },+ })+ })++ it('omits flag config entirely when linking a pre-existing flag', () => {+ expect(toExperimentWritePayload(experiment, { omitFlagConfig: true })).toEqual({+ name: 'test',+ parameters: { variant_notes: { control: 'baseline' } },+ })+ })++ it('sends no feature_flag object when parameters carry no flag config', () => {+ expect(toExperimentWritePayload({ parameters: { variant_notes: {} } } as unknown as Experiment)).toEqual({+ parameters: { variant_notes: {} },+ })+ })++ it('preserves a null parameters instead of coercing it to an empty object', () => {+ expect(toExperimentWritePayload({ parameters: null } as unknown as Experiment)).toEqual({ parameters: null })+ })+})diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.tsindex 49614f7c008b..0ada8cf73ace 100644--- a/frontend/src/scenes/experiments/utils.ts+++ b/frontend/src/scenes/experiments/utils.ts@@ -45,6 +45,11 @@ import {UniversalFiltersGroupValue,} from '~/types'+import type {+ ExperimentFeatureFlagFiltersApi,+ ExperimentFeatureFlagInputApi,+} from 'products/experiments/frontend/generated/api.schemas'+import { EXPERIMENT_VARIANT_MULTIPLE } from './constants'import { SharedMetric } from './SharedMetrics/sharedMetricLogic'@@ -982,6 +987,94 @@ export type MetricWithResult = {export const isSavedExperiment = (experiment: Experiment | null | undefined): experiment is Experiment =>experiment?.id != null && experiment.id !== 'new'+export type ExperimentWritePayload<T> = Omit<T, 'feature_flag'> & {+ feature_flag?: ExperimentFeatureFlagInputApi+}++/** Update payload for the experiment API: flag config travels in the write shape. An echoed+ * read-only flag is also accepted — the backend ignores flag objects carrying a non-null id. */+export type ExperimentUpdatePayload = Omit<Partial<Experiment>, 'feature_flag'> & {+ feature_flag?: ExperimentFeatureFlagInputApi | Experiment['feature_flag']+ update_feature_flag_params?: boolean+}++/** Maps UI variants to the flag's write shape, dropping null names the generated type disallows. */+export function toFlagVariantsInput(+ variants: MultivariateFlagVariant[]+): NonNullable<ExperimentFeatureFlagFiltersApi['multivariate']>['variants'] {+ return variants.map(({ key, name, rollout_percentage }) => ({+ key,+ ...(name != null ? { name } : {}),+ rollout_percentage,+ }))+}++/** The flag-config keys the GET projection mirrors into `parameters`. `ensure_experience_continuity`+ * is also user-set (the wizard's continuity toggle writes it); the others only echo the flag. */+type ProjectedFlagConfigParameters = Experiment['parameters'] & {+ ensure_experience_continuity?: boolean | null+ feature_flag_payloads?: Record<string, string>+}++/**+ * Builds an experiment write payload that sends flag config through the `feature_flag` object+ * (the flag's own filters shape) instead of the deprecated `parameters` keys, which are stripped.+ * The read-only `feature_flag` echoed by a GET response is dropped either way.+ *+ * Pass `omitFlagConfig` when the experiment links to a pre-existing flag: the flag is linked+ * as-is, and the API rejects explicit config for it.+ */+export function toExperimentWritePayload<T extends Pick<Experiment, 'parameters'>>(+ experiment: T,+ { omitFlagConfig = false }: { omitFlagConfig?: boolean } = {}+): ExperimentWritePayload<T> {+ const {+ feature_flag_variants,+ rollout_percentage,+ aggregation_group_type_index,+ feature_flag_payloads,+ ensure_experience_continuity,+ ...parameters+ } = (experiment.parameters ?? {}) as ProjectedFlagConfigParameters+ const { feature_flag: _echoedFlag, ...rest } = experiment as T & { feature_flag?: unknown }+ // Preserve a null/undefined parameters as-is: coercing it to {} would rewrite a stored+ // null on PATCH.+ const payload = {+ ...rest,+ parameters: experiment.parameters == null ? experiment.parameters : parameters,+ } as ExperimentWritePayload<T>++ if (omitFlagConfig) {+ return payload+ }++ const filters: ExperimentFeatureFlagFiltersApi = {}+ if (feature_flag_variants && feature_flag_variants.length > 0) {+ filters.multivariate = { variants: toFlagVariantsInput(feature_flag_variants) }+ }+ if (rollout_percentage != null) {+ filters.groups = [{ properties: [], rollout_percentage }]+ }+ // Forwarded rather than dropped: on update the backend would backfill these from the linked+ // flag anyway, but on create (e.g. the duplicate prefill) there is no flag to backfill from,+ // so dropping them would silently lose group aggregation and variant payloads.+ if (aggregation_group_type_index != null) {+ filters.aggregation_group_type_index = aggregation_group_type_index+ }+ if (feature_flag_payloads && Object.keys(feature_flag_payloads).length > 0) {+ filters.payloads = feature_flag_payloads+ }++ const featureFlag: ExperimentFeatureFlagInputApi = {+ ...(Object.keys(filters).length > 0 ? { filters } : {}),+ ...(ensure_experience_continuity != null ? { ensure_experience_continuity } : {}),+ }+ if (Object.keys(featureFlag).length > 0) {+ payload.feature_flag = featureFlag+ }+ return payload+}+/*** Pure zip of one metric type (`primary` | `secondary`) with its results and errors, in display order.* Same shaping as {@link getOrderedMetricsWithResults} but curried over the experiment, so a caller candiff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex a254874cd58e..c02a062e4c39 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -622,6 +622,16 @@ class ExperimentService:"supported via the experiment feature_flag input. Edit the feature flag directly."})+ # Same rationale inside the group object: a `variant` override or per-group+ # aggregation would be silently ignored, not applied.+ unsupported_group_keys = sorted(set(groups[0]) - {"properties", "rollout_percentage"}) if groups else []+ if unsupported_group_keys:+ raise ValidationError(+ {+ "feature_flag": f"Unsupported keys in filters.groups[0]: {', '.join(unsupported_group_keys)}. "+ "Only rollout_percentage is applied here; edit the feature flag directly for anything else."+ }+ )if groups:rollout_percentage = groups[0].get("rollout_percentage")if rollout_percentage is not None:diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 2d9ce9b0467d..96963f3761fb 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -22,6 +22,7 @@ from posthog.schema import (ExperimentRunningTimeCalculation,)+from posthog.api.documentation import FeatureFlagFiltersSchemaSerializerfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.shared import UserBasicSerializerfrom posthog.models.team.team import Team@@ -356,10 +357,11 @@ class ExperimentSerializer(ExperimentBaseSerializer):default=False,write_only=True,help_text=(- "When true, sync feature flag configuration from parameters "- "to the linked feature flag. Draft experiments always sync "- "regardless of update_feature_flag_params, so only required "- "for non-drafts."+ "When true, sync the flag config sent in this request (via the "+ "`feature_flag` object, or the deprecated `parameters` keys) to "+ "the linked feature flag. Draft experiments always sync "+ "regardless. On a running experiment, `feature_flag` config "+ "without this flag is rejected."),)_create_in_folder = serializers.CharField(required=False, allow_blank=True, write_only=True)@@ -691,6 +693,97 @@ class ExperimentSerializer(ExperimentBaseSerializer):)+class ExperimentFlagRolloutGroupSerializer(serializers.Serializer):+ """A single release-condition group carrying only the overall rollout percentage, the one+ groups entry the experiment input applies."""++ rollout_percentage = serializers.IntegerField(+ required=False,+ allow_null=True,+ min_value=0,+ max_value=100,+ help_text="Percentage of users who enter the experiment (0-100).",+ )+ properties = serializers.ListField(+ child=serializers.JSONField(),+ required=False,+ max_length=0,+ help_text=(+ "Must be empty or omitted: release-condition properties are not supported via the "+ "experiment input. Edit the feature flag directly for targeting."+ ),+ )+++# Subclassing the flag's canonical filters schema (rather than redeclaring the shape) keeps the+# experiment write surface from drifting when the flag filters schema changes. Constraints the+# schema can't express are enforced at runtime by+# ExperimentService.feature_flag_config_to_parameters.+class ExperimentFeatureFlagFiltersSerializer(FeatureFlagFiltersSchemaSerializer):+ """Feature-flag filters accepted by the experiment endpoints: the flag's own filters shape,+ minus the keys experiments don't apply."""++ # DRF's declarative field removal: assigning None drops the inherited field.+ feature_enrollment = None # type: ignore[assignment]+ early_exit = None # type: ignore[assignment]+ # The runtime applies only groups[0].rollout_percentage and rejects release conditions, so+ # advertise exactly that instead of the flag's full condition-group schema. The full schema+ # would invite payloads (property filters, variant overrides, multiple groups) that always+ # fail validation, and it adds ~10KB to each generated MCP tool schema.+ groups = ExperimentFlagRolloutGroupSerializer( # type: ignore[assignment,call-arg]+ many=True,+ required=False,+ max_length=1,+ help_text='Overall rollout as a single group: [{"properties": [], "rollout_percentage": N}].',+ )+++# Schema-only: runtime consumes the raw feature_flag object from initial_data (see+# ExperimentSerializer._normalize_feature_flag_input), so echoed read-only flag objects+# (carrying a non-null id) keep being tolerated instead of failing this validation.+class ExperimentFeatureFlagInputSerializer(serializers.Serializer):+ """Flag config for experiment create/update, sent through the linked feature flag's own shape."""++ filters = ExperimentFeatureFlagFiltersSerializer(+ required=False,+ help_text=(+ "Flag config to apply: `multivariate.variants` (exactly one variant key must be the literal "+ "string 'control'), `groups` (a single group with `rollout_percentage` only; release "+ "conditions are not supported here, edit the feature flag directly), "+ "`aggregation_group_type_index`, and `payloads` (JSON-encoded strings keyed by variant key). "+ "On update, config this object omits is preserved from the linked flag's current state."+ ),+ )+ ensure_experience_continuity = serializers.BooleanField(+ required=False,+ allow_null=True,+ help_text="Whether the flag persists variant assignment across authentication steps.",+ )+++# Schema-only request serializer: advertises the writable feature_flag input in OpenAPI. Runtime+# writes still validate through ExperimentSerializer (the viewset's serializer_class), which reads+# feature_flag from initial_data. Referenced only via extend_schema(request=...) on the+# create/update/partial_update methods.+class ExperimentWriteSerializer(ExperimentSerializer):+ """Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input."""++ feature_flag = ExperimentFeatureFlagInputSerializer( # type: ignore[assignment]+ required=False,+ help_text=(+ "Feature-flag config for the experiment, in the flag's own filters shape. The linked flag "+ "is the source of truth for variants, rollout, aggregation, payloads, and experience "+ "continuity: send config here instead of the deprecated `parameters` keys. On a running "+ "experiment, also send `update_feature_flag_params=true`. Cannot be combined with the key "+ "of a pre-existing feature flag on create (the experiment links to it as-is)."+ ),+ )++ class Meta(ExperimentSerializer.Meta):+ # feature_flag is writable in this schema-only variant, so it must leave read_only_fields.+ read_only_fields = [field for field in ExperimentSerializer.Meta.read_only_fields if field != "feature_flag"]++class ExperimentBasicSerializer(ExperimentBaseSerializer):"""Lightweight, read-only serializer for the experiment list endpoint.diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex e4edc63c6257..e6381959202b 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -59,6 +59,7 @@ from products.experiments.backend.presentation.serializers import (ExperimentBasicSerializer,ExperimentMetricsRecalculationSerializer,ExperimentSerializer,+ ExperimentWriteSerializer,RecalculateMetricsRequestSerializer,RunningTimeCalculationInputSerializer,RunningTimeCalculationResultSerializer,@@ -187,12 +188,18 @@ def _slugify_feature_flag_key(name: str, *, team_id: int) -> str:@extend_schema_view(# PATCH /experiments/{id}/# DRF mixin calls implementation at ExperimentSerializer.update+ # request=ExperimentWriteSerializer is schema-only: it adds the writable feature_flag input+ # to the OpenAPI request body; runtime validation stays on ExperimentSerializer.partial_update=extend_schema(- description="Update an experiment. Use this to modify experiment properties such as name, description, metrics, variants, and configuration. Metrics can be added, changed and removed at any time.",+ description="Update an experiment. Use this to modify experiment properties such as name, description, metrics, variants, and configuration. Metrics can be added, changed and removed at any time. Feature-flag config (variants, rollout, payloads) is sent via the feature_flag object.",+ request=ExperimentWriteSerializer,),+ # PUT /experiments/{id}/, same request shape as PATCH+ update=extend_schema(request=ExperimentWriteSerializer),# POST /experiments/ — DRF mixin calls ExperimentSerializer.createcreate=extend_schema(description="Create a new experiment in draft status with optional metrics.",+ request=ExperimentWriteSerializer,),# GET /experiments/{id}/ — DRF mixin, read-only serialization via ExperimentSerializerretrieve=extend_schema(diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex 446973e96054..54bd289351f3 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -2500,6 +2500,10 @@ class TestExperimentCRUD(APILicensedTest):"multiple_groups_unsupported",{"filters": {"groups": [{"rollout_percentage": 50}, {"rollout_percentage": 100}]}},),+ (+ "unknown_group_key",+ {"filters": {"groups": [{"properties": [], "rollout_percentage": 50, "variant": "test"}]}},+ ),("unknown_top_level_key",{"active": False, "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]}},diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 7714642972ef..622c80b38993 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -823,6 +823,75 @@ export interface PaginatedExperimentBasicListApi {results: ExperimentBasicApi[]}+/**+ * A single release-condition group carrying only the overall rollout percentage, the one+ * groups entry the experiment input applies.+ */+export interface ExperimentFlagRolloutGroupApi {+ /**+ * Percentage of users who enter the experiment (0-100).+ * @minimum 0+ * @maximum 100+ * @nullable+ */+ rollout_percentage?: number | null+ /**+ * Must be empty or omitted: release-condition properties are not supported via the experiment input. Edit the feature flag directly for targeting.+ * @maxItems 0+ */+ properties?: unknown[]+}++export interface FeatureFlagMultivariateVariantSchemaApi {+ /** Unique key for this variant. */+ key: string+ /** Human-readable name for this variant. */+ name?: string+ /** Variant rollout percentage. */+ rollout_percentage: number+}++export interface FeatureFlagMultivariateSchemaApi {+ /** Variant definitions for multivariate feature flags. */+ variants: FeatureFlagMultivariateVariantSchemaApi[]+}++/**+ * Optional payload values keyed by variant key.+ */+export type ExperimentFeatureFlagFiltersApiPayloads = { [key: string]: string }++/**+ * Feature-flag filters accepted by the experiment endpoints: the flag's own filters shape,+ * minus the keys experiments don't apply.+ */+export interface ExperimentFeatureFlagFiltersApi {+ /** Overall rollout as a single group: [{"properties": [], "rollout_percentage": N}]. */+ groups?: ExperimentFlagRolloutGroupApi[]+ /** Multivariate configuration for variant-based rollouts. */+ multivariate?: FeatureFlagMultivariateSchemaApi | null+ /**+ * Group type index for group-based feature flags.+ * @nullable+ */+ aggregation_group_type_index?: number | null+ /** Optional payload values keyed by variant key. */+ payloads?: ExperimentFeatureFlagFiltersApiPayloads+}++/**+ * Flag config for experiment create/update, sent through the linked feature flag's own shape.+ */+export interface ExperimentFeatureFlagInputApi {+ /** Flag config to apply: `multivariate.variants` (exactly one variant key must be the literal string 'control'), `groups` (a single group with `rollout_percentage` only; release conditions are not supported here, edit the feature flag directly), `aggregation_group_type_index`, and `payloads` (JSON-encoded strings keyed by variant key). On update, config this object omits is preserved from the linked flag's current state. */+ filters?: ExperimentFeatureFlagFiltersApi+ /**+ * Whether the flag persists variant assignment across authentication steps.+ * @nullable+ */+ ensure_experience_continuity?: boolean | null+}+export interface ExperimentToSavedMetricApi {readonly id: numberexperiment: number@@ -1274,6 +1343,108 @@ export interface ExperimentApiMetricApi {*/export type _ExperimentApiMetricsListApi = ExperimentApiMetricApi[]+/**+ * Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.+ */+export interface ExperimentWriteApi {+ readonly id: number+ /**+ * Name of the experiment.+ * @maxLength 400+ */+ name: string+ /**+ * Description of the experiment hypothesis and expected outcomes.+ * @maxLength 3000+ * @nullable+ */+ description?: string | null+ /** @nullable */+ start_date?: string | null+ /** @nullable */+ end_date?: string | null+ /** Unique key for the experiment's feature flag. Letters, numbers, hyphens, and underscores only. Search existing flags with the feature-flag-get-all tool first — reuse an existing flag when possible. */+ feature_flag_key: string+ /** Feature-flag config for the experiment, in the flag's own filters shape. The linked flag is the source of truth for variants, rollout, aggregation, payloads, and experience continuity: send config here instead of the deprecated `parameters` keys. On a running experiment, also send `update_feature_flag_params=true`. Cannot be combined with the key of a pre-existing feature flag on create (the experiment links to it as-is). */+ feature_flag?: ExperimentFeatureFlagInputApi+ readonly holdout: ExperimentHoldoutApi+ /**+ * ID of a holdout group to exclude from the experiment.+ * @nullable+ */+ holdout_id?: number | null+ /** @nullable */+ readonly exposure_cohort: number | null+ /** Experiment parameters JSON. Supported keys include `custom_exposure_filter` and `variant_notes` (free-text notes per variant, keyed by variant key). Flag config keys (`feature_flag_variants`, `rollout_percentage`) are a deprecated input surface kept for compatibility — the linked feature flag is the source of truth, and reads project its current config into this field. Excluded variants live on the top-level `excluded_variants` field, not here. */+ parameters?: ExperimentParametersApi | null+ /** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`. */+ running_time_calculation?: ExperimentRunningTimeCalculationApi | null+ /**+ * Variant keys to exclude from metric result calculations. Excluded variants are still served to users but omitted from statistical analysis. The baseline variant and holdout pseudo-variants cannot be excluded. Canonical home for what historically lived in `parameters.excluded_variants`.+ * @nullable+ */+ excluded_variants?: string[] | null+ secondary_metrics?: unknown+ readonly saved_metrics: readonly ExperimentToSavedMetricApi[]+ /**+ * IDs of shared saved metrics to attach to this experiment. Each item has 'id' (saved metric ID) and 'metadata' with 'type' (primary or secondary).+ * @nullable+ */+ saved_metrics_ids?: unknown[] | null+ filters?: unknown+ /** Whether the experiment is archived. */+ archived?: boolean+ /** @nullable */+ deleted?: boolean | null+ readonly created_by: UserBasicApi+ readonly created_at: string+ readonly updated_at: string+ /** Experiment type: web for frontend UI changes, product for backend/API changes.+ *+ * * `web` - web+ * * `product` - product */+ type?: ExperimentTypeEnumApi | null+ /** Exposure configuration including filter test accounts and custom exposure events. */+ exposure_criteria?: ExperimentApiExposureCriteriaApi | null+ /** Primary experiment metrics. Each metric must have kind='ExperimentMetric' and a metric_type: 'mean' (set source to an EventsNode with an event name), 'funnel' (set series to an array of EventsNode steps), 'ratio' (set numerator and denominator EventsNode entries), or 'retention' (set start_event and completion_event). Use the read-data-schema tool with query kind 'events' to find available events in the project. */+ metrics?: _ExperimentApiMetricsListApi | null+ /** Secondary metrics for additional measurements. Same format as primary metrics. */+ metrics_secondary?: _ExperimentApiMetricsListApi | null+ stats_config?: unknown+ scheduling_config?: unknown+ /** Suppresses the validation that rejects metrics referencing events not yet ingested by this project. REQUIRES explicit user confirmation before being set to true — never flip this silently to retry a failed call. The default validation catches typo'd event names and missing instrumentation. Set this to true only when the user has confirmed the event is intentional (e.g. they are about to instrument it). */+ allow_unknown_events?: boolean+ _create_in_folder?: string+ /** Experiment conclusion: won, lost, inconclusive, stopped_early, or invalid.+ *+ * * `won` - won+ * * `lost` - lost+ * * `inconclusive` - inconclusive+ * * `stopped_early` - stopped_early+ * * `invalid` - invalid */+ conclusion?: ConclusionEnumApi | null+ /**+ * Comment about the experiment conclusion.+ * @maxLength 4000+ * @nullable+ */+ conclusion_comment?: string | null+ primary_metrics_ordered_uuids?: unknown+ secondary_metrics_ordered_uuids?: unknown+ only_count_matured_users?: boolean+ /** When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */+ update_feature_flag_params?: boolean+ /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */+ readonly status: ExperimentStatusEnumApi+ /** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */+ readonly is_legacy: boolean+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level: string | null+}+/*** Full experiment representation for the detail, create, and update endpoints.*@@ -1367,7 +1538,7 @@ export interface ExperimentApi {primary_metrics_ordered_uuids?: unknownsecondary_metrics_ordered_uuids?: unknownonly_count_matured_users?: boolean- /** When true, sync feature flag configuration from parameters to the linked feature flag. Draft experiments always sync regardless of update_feature_flag_params, so only required for non-drafts. */+ /** When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */update_feature_flag_params?: boolean/** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */readonly status: ExperimentStatusEnumApi@@ -1381,14 +1552,9 @@ export interface ExperimentApi {}/**- * Full experiment representation for the detail, create, and update endpoints.- *- * Extends the shared read-side fields in ``ExperimentBaseSerializer`` with the metric- * definitions (``metrics``/``metrics_secondary``/``saved_metrics``) and the write-side- * fields, and refreshes stale action names while serializing. The list endpoint uses the- * leaner ``ExperimentBasicSerializer`` instead.+ * Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.*/-export interface PatchedExperimentApi {+export interface PatchedExperimentWriteApi {readonly id?: number/*** Name of the experiment.@@ -1407,7 +1573,8 @@ export interface PatchedExperimentApi {end_date?: string | null/** Unique key for the experiment's feature flag. Letters, numbers, hyphens, and underscores only. Search existing flags with the feature-flag-get-all tool first — reuse an existing flag when possible. */feature_flag_key?: string- readonly feature_flag?: MinimalFeatureFlagApi+ /** Feature-flag config for the experiment, in the flag's own filters shape. The linked flag is the source of truth for variants, rollout, aggregation, payloads, and experience continuity: send config here instead of the deprecated `parameters` keys. On a running experiment, also send `update_feature_flag_params=true`. Cannot be combined with the key of a pre-existing feature flag on create (the experiment links to it as-is). */+ feature_flag?: ExperimentFeatureFlagInputApireadonly holdout?: ExperimentHoldoutApi/*** ID of a holdout group to exclude from the experiment.@@ -1473,7 +1640,7 @@ export interface PatchedExperimentApi {primary_metrics_ordered_uuids?: unknownsecondary_metrics_ordered_uuids?: unknownonly_count_matured_users?: boolean- /** When true, sync feature flag configuration from parameters to the linked feature flag. Draft experiments always sync regardless of update_feature_flag_params, so only required for non-drafts. */+ /** When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */update_feature_flag_params?: boolean/** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */readonly status?: ExperimentStatusEnumApidiff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.tsindex 9dba1977298e..35e5ec633b61 100644--- a/products/experiments/frontend/generated/api.ts+++ b/products/experiments/frontend/generated/api.ts@@ -19,15 +19,16 @@ import type {ExperimentMetricsRecalculationApi,ExperimentSavedMetricApi,ExperimentSavedMetricsListParams,+ ExperimentWriteApi,ExperimentsListParams,ExperimentsPromptTemplatesRetrieve200Item,ExperimentsTimeseriesResultsRetrieveParams,PaginatedExperimentBasicListApi,PaginatedExperimentHoldoutListApi,PaginatedExperimentSavedMetricListApi,- PatchedExperimentApi,PatchedExperimentHoldoutApi,PatchedExperimentSavedMetricApi,+ PatchedExperimentWriteApi,RecalculateMetricsRequestApi,RunningTimeCalculationInputApi,RunningTimeCalculationResultApi,@@ -310,14 +311,14 @@ export const getExperimentsCreateUrl = (projectId: string) => {*/export const experimentsCreate = async (projectId: string,- experimentApi: NonReadonly<ExperimentApi>,+ experimentWriteApi: NonReadonly<ExperimentWriteApi>,options?: RequestInit): Promise<ExperimentApi> => {return apiMutator<ExperimentApi>(getExperimentsCreateUrl(projectId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(experimentApi),+ body: JSON.stringify(experimentWriteApi),})}@@ -353,14 +354,14 @@ export const getExperimentsUpdateUrl = (projectId: string, id: number) => {export const experimentsUpdate = async (projectId: string,id: number,- experimentApi: NonReadonly<ExperimentApi>,+ experimentWriteApi: NonReadonly<ExperimentWriteApi>,options?: RequestInit): Promise<ExperimentApi> => {return apiMutator<ExperimentApi>(getExperimentsUpdateUrl(projectId, id), {...options,method: 'PUT',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(experimentApi),+ body: JSON.stringify(experimentWriteApi),})}@@ -369,19 +370,19 @@ export const getExperimentsPartialUpdateUrl = (projectId: string, id: number) =>}/**- * Update an experiment. Use this to modify experiment properties such as name, description, metrics, variants, and configuration. Metrics can be added, changed and removed at any time.+ * Update an experiment. Use this to modify experiment properties such as name, description, metrics, variants, and configuration. Metrics can be added, changed and removed at any time. Feature-flag config (variants, rollout, payloads) is sent via the feature_flag object.*/export const experimentsPartialUpdate = async (projectId: string,id: number,- patchedExperimentApi?: NonReadonly<PatchedExperimentApi>,+ patchedExperimentWriteApi?: NonReadonly<PatchedExperimentWriteApi>,options?: RequestInit): Promise<ExperimentApi> => {return apiMutator<ExperimentApi>(getExperimentsPartialUpdateUrl(projectId, id), {...options,method: 'PATCH',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchedExperimentApi),+ body: JSON.stringify(patchedExperimentWriteApi),})}diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.tsindex 7ec19a7ba672..954128db9100 100644--- a/products/experiments/frontend/generated/api.zod.ts+++ b/products/experiments/frontend/generated/api.zod.ts@@ -877,7 +877,7 @@ export const ExperimentsUpdateBody = /* @__PURE__ */ zod.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')/**- * Update an experiment. Use this to modify experiment properties such as name, description, metrics, variants, and configuration. Metrics can be added, changed and removed at any time.+ * Update an experiment. Use this to modify experiment properties such as name, description, metrics, variants, and configuration. Metrics can be added, changed and removed at any time. Feature-flag config (variants, rollout, payloads) is sent via the feature_flag object.*/export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod.record(zod.string(), zod.unknown())diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex cb6fd1c23924..0de11b3ce6b5 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -192,24 +192,29 @@ tools:- name- description- feature_flag_key+ - feature_flag- parameters- stats_config- holdout_id- allow_unknown_events- exposure_criteriaparam_overrides:- parameters:+ feature_flag:description: >- Variant split and rollout scope. If the user mentions a specific percentage, load the- configuring-experiment-rollout skill and clarify before setting these values. Set rollout_percentage- (0-100) to control the overall fraction of users entering the experiment. Set feature_flag_variants- with split_percent on each variant to customize the variant split. Default: 50/50 control/test, 100%- rollout.--- HARD REQUIREMENT — when you provide feature_flag_variants, exactly one variant's `key` must be the- literal string `control` (lowercase, no variations). It is the baseline used for analysis and the- experiment runtime treats it specially. If the user describes variants as "A/B", "old/new",+ Variant split, rollout scope, payloads, and experience continuity for the auto-created feature flag,+ in the flag's own filters shape. This is the canonical input, do not send flag config via the+ deprecated parameters keys (feature_flag_variants, rollout_percentage). If the user mentions a+ specific percentage, load the configuring-experiment-rollout skill and clarify before setting these+ values. Set filters.multivariate.variants (each with key and rollout_percentage; percentages must+ sum to 100) to customize the variant split. Set filters.groups to a single group [{"properties": [],+ "rollout_percentage": N}] (0-100) to control the overall fraction of users entering the experiment.+ Default: 50/50 control/test, 100% rollout. Omit this parameter entirely when feature_flag_key refers+ to a pre-existing flag: the experiment links to that flag as-is and explicit config is rejected.+++ HARD REQUIREMENT — when you provide variants, exactly one variant's `key` must be the literal string+ `control` (lowercase, no variations). It is the baseline used for analysis and the experiment+ runtime treats it specially. If the user describes variants as "A/B", "old/new","original/redesign", or any other natural-language pair, map the baseline to `key: "control"` — not"A", "Control", "old", "original", or "baseline". Other variants can use any key (`test`,`variant_a`, etc.).@@ -932,8 +937,9 @@ tools:4. For running experiments, setupdate_feature_flag_params=true when changing- parameters — without it, changes save but do NOT- sync to the feature flag.+ feature_flag config — without it, the request is+ rejected because the change would not sync to the+ feature flag.5. Setting allow_unknown_events=true REQUIRES EXPLICITUSER CONFIRMATION. When the API returns@@ -959,6 +965,7 @@ tools:include_params:- name- description+ - feature_flag- parameters- running_time_calculation- excluded_variants@@ -976,6 +983,16 @@ tools:param_overrides:id:cast: string-int+ feature_flag:+ description: >+ Variant split, rollout scope, payloads, and experience continuity for the linked feature flag, in+ the flag's own filters shape. This is the canonical input, do not send flag config via the+ deprecated parameters keys (feature_flag_variants, rollout_percentage). Set+ filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100,+ exactly one key must be the literal string 'control') to change the variant split. Set+ filters.groups to a single group [{"properties": [], "rollout_percentage": N}] (0-100) to change the+ overall rollout. Config this object omits is preserved from the flag's current state. On a running+ experiment this requires update_feature_flag_params=true (see rule 1: warn the user first).running_time_calculation:description: >Persist a running-time / sample-size plan onto the experiment (the planning target shown in thediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 18dce6718483..bd2de4fa4670 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3312,7 +3312,7 @@}},"experiment-update": {- "description": "RULES (follow before calling):\n1. If changing rollout or variants on a RUNNING\n experiment, you MUST warn the user about user\n experience AND statistical implications BEFORE\n making the change and get explicit confirmation.\n Load the configuring-experiment-rollout skill for\n the full warning. Do NOT silently apply the change\n — even if the user asked directly.\n\n2. If the user mentions a percentage, clarify whether\n they mean variant split or overall rollout BEFORE\n calling.\n\n3. If adding or changing metrics, load the\n configuring-experiment-analytics skill first. Call\n read-data-schema to discover available events BEFORE\n suggesting or using any event name. Never suggest\n event names you haven't confirmed exist.\n\n4. For running experiments, set\n update_feature_flag_params=true when changing\n parameters — without it, changes save but do NOT\n sync to the feature flag.\n\n5. Setting allow_unknown_events=true REQUIRES EXPLICIT\n USER CONFIRMATION. When the API returns\n \"Event(s) '...' not found\", do NOT silently retry\n with allow_unknown_events=true. Default to\n course-correcting: surface the missing event names\n and ask whether the user meant a different (existing)\n event. Only set allow_unknown_events=true when the\n user explicitly confirms the event is intentional\n (e.g. about to be instrumented). Course-correcting\n to a known event is the expected default; flipping\n the flag is the exception.\n\n\nUpdate an experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Metrics can be changed at any time including while running. Cannot add/remove variants on non-draft experiments (changing percentages between existing variants is allowed). Cannot change holdout on non-draft experiments.\n\nDo NOT use this to change lifecycle state — use the dedicated launch, end, pause, resume, archive, or experiment-ship-variant tools instead.",+ "description": "RULES (follow before calling):\n1. If changing rollout or variants on a RUNNING\n experiment, you MUST warn the user about user\n experience AND statistical implications BEFORE\n making the change and get explicit confirmation.\n Load the configuring-experiment-rollout skill for\n the full warning. Do NOT silently apply the change\n — even if the user asked directly.\n\n2. If the user mentions a percentage, clarify whether\n they mean variant split or overall rollout BEFORE\n calling.\n\n3. If adding or changing metrics, load the\n configuring-experiment-analytics skill first. Call\n read-data-schema to discover available events BEFORE\n suggesting or using any event name. Never suggest\n event names you haven't confirmed exist.\n\n4. For running experiments, set\n update_feature_flag_params=true when changing\n feature_flag config — without it, the request is\n rejected because the change would not sync to the\n feature flag.\n\n5. Setting allow_unknown_events=true REQUIRES EXPLICIT\n USER CONFIRMATION. When the API returns\n \"Event(s) '...' not found\", do NOT silently retry\n with allow_unknown_events=true. Default to\n course-correcting: surface the missing event names\n and ask whether the user meant a different (existing)\n event. Only set allow_unknown_events=true when the\n user explicitly confirms the event is intentional\n (e.g. about to be instrumented). Course-correcting\n to a known event is the expected default; flipping\n the flag is the exception.\n\n\nUpdate an experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Metrics can be changed at any time including while running. Cannot add/remove variants on non-draft experiments (changing percentages between existing variants is allowed). Cannot change holdout on non-draft experiments.\n\nDo NOT use this to change lifecycle state — use the dedicated launch, end, pause, resume, archive, or experiment-ship-variant tools instead.","category": "Experiments","feature": "experiments","summary": "Update experiment",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 2e504febe72d..cba276fd01c9 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -3510,7 +3510,7 @@}},"experiment-update": {- "description": "RULES (follow before calling):\n1. If changing rollout or variants on a RUNNING\n experiment, you MUST warn the user about user\n experience AND statistical implications BEFORE\n making the change and get explicit confirmation.\n Load the configuring-experiment-rollout skill for\n the full warning. Do NOT silently apply the change\n — even if the user asked directly.\n\n2. If the user mentions a percentage, clarify whether\n they mean variant split or overall rollout BEFORE\n calling.\n\n3. If adding or changing metrics, load the\n configuring-experiment-analytics skill first. Call\n read-data-schema to discover available events BEFORE\n suggesting or using any event name. Never suggest\n event names you haven't confirmed exist.\n\n4. For running experiments, set\n update_feature_flag_params=true when changing\n parameters — without it, changes save but do NOT\n sync to the feature flag.\n\n5. Setting allow_unknown_events=true REQUIRES EXPLICIT\n USER CONFIRMATION. When the API returns\n \"Event(s) '...' not found\", do NOT silently retry\n with allow_unknown_events=true. Default to\n course-correcting: surface the missing event names\n and ask whether the user meant a different (existing)\n event. Only set allow_unknown_events=true when the\n user explicitly confirms the event is intentional\n (e.g. about to be instrumented). Course-correcting\n to a known event is the expected default; flipping\n the flag is the exception.\n\n\nUpdate an experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Metrics can be changed at any time including while running. Cannot add/remove variants on non-draft experiments (changing percentages between existing variants is allowed). Cannot change holdout on non-draft experiments.\n\nDo NOT use this to change lifecycle state — use the dedicated launch, end, pause, resume, archive, or experiment-ship-variant tools instead.",+ "description": "RULES (follow before calling):\n1. If changing rollout or variants on a RUNNING\n experiment, you MUST warn the user about user\n experience AND statistical implications BEFORE\n making the change and get explicit confirmation.\n Load the configuring-experiment-rollout skill for\n the full warning. Do NOT silently apply the change\n — even if the user asked directly.\n\n2. If the user mentions a percentage, clarify whether\n they mean variant split or overall rollout BEFORE\n calling.\n\n3. If adding or changing metrics, load the\n configuring-experiment-analytics skill first. Call\n read-data-schema to discover available events BEFORE\n suggesting or using any event name. Never suggest\n event names you haven't confirmed exist.\n\n4. For running experiments, set\n update_feature_flag_params=true when changing\n feature_flag config — without it, the request is\n rejected because the change would not sync to the\n feature flag.\n\n5. Setting allow_unknown_events=true REQUIRES EXPLICIT\n USER CONFIRMATION. When the API returns\n \"Event(s) '...' not found\", do NOT silently retry\n with allow_unknown_events=true. Default to\n course-correcting: surface the missing event names\n and ask whether the user meant a different (existing)\n event. Only set allow_unknown_events=true when the\n user explicitly confirms the event is intentional\n (e.g. about to be instrumented). Course-correcting\n to a known event is the expected default; flipping\n the flag is the exception.\n\n\nUpdate an experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Metrics can be changed at any time including while running. Cannot add/remove variants on non-draft experiments (changing percentages between existing variants is allowed). Cannot change holdout on non-draft experiments.\n\nDo NOT use this to change lifecycle state — use the dedicated launch, end, pause, resume, archive, or experiment-ship-variant tools instead.","category": "Experiments","feature": "experiments","summary": "Update experiment",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9731472829ff..4c21603f527c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -22506,7 +22506,7 @@ export namespace Schemas {primary_metrics_ordered_uuids?: unknown;secondary_metrics_ordered_uuids?: unknown;only_count_matured_users?: boolean;- /** When true, sync feature flag configuration from parameters to the linked feature flag. Draft experiments always sync regardless of update_feature_flag_params, so only required for non-drafts. */+ /** When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */update_feature_flag_params?: boolean;/** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */readonly status: ExperimentStatusEnum;@@ -22677,6 +22677,75 @@ export namespace Schemas {version?: number | null;}+ /**+ * Optional payload values keyed by variant key.+ */+ export type ExperimentFeatureFlagFiltersPayloads = {[key: string]: string};++ /**+ * A single release-condition group carrying only the overall rollout percentage, the one+ * groups entry the experiment input applies.+ */+ export interface ExperimentFlagRolloutGroup {+ /**+ * Percentage of users who enter the experiment (0-100).+ * @minimum 0+ * @maximum 100+ * @nullable+ */+ rollout_percentage?: number | null;+ /**+ * Must be empty or omitted: release-condition properties are not supported via the experiment input. Edit the feature flag directly for targeting.+ * @maxItems 0+ */+ properties?: unknown[];+ }++ export interface FeatureFlagMultivariateVariantSchema {+ /** Unique key for this variant. */+ key: string;+ /** Human-readable name for this variant. */+ name?: string;+ /** Variant rollout percentage. */+ rollout_percentage: number;+ }++ export interface FeatureFlagMultivariateSchema {+ /** Variant definitions for multivariate feature flags. */+ variants: FeatureFlagMultivariateVariantSchema[];+ }++ /**+ * Feature-flag filters accepted by the experiment endpoints: the flag's own filters shape,+ * minus the keys experiments don't apply.+ */+ export interface ExperimentFeatureFlagFilters {+ /** Overall rollout as a single group: [{"properties": [], "rollout_percentage": N}]. */+ groups?: ExperimentFlagRolloutGroup[];+ /** Multivariate configuration for variant-based rollouts. */+ multivariate?: FeatureFlagMultivariateSchema | null;+ /**+ * Group type index for group-based feature flags.+ * @nullable+ */+ aggregation_group_type_index?: number | null;+ /** Optional payload values keyed by variant key. */+ payloads?: ExperimentFeatureFlagFiltersPayloads;+ }++ /**+ * Flag config for experiment create/update, sent through the linked feature flag's own shape.+ */+ export interface ExperimentFeatureFlagInput {+ /** Flag config to apply: `multivariate.variants` (exactly one variant key must be the literal string 'control'), `groups` (a single group with `rollout_percentage` only; release conditions are not supported here, edit the feature flag directly), `aggregation_group_type_index`, and `payloads` (JSON-encoded strings keyed by variant key). On update, config this object omits is preserved from the linked flag's current state. */+ filters?: ExperimentFeatureFlagFilters;+ /**+ * Whether the flag persists variant assignment across authentication steps.+ * @nullable+ */+ ensure_experience_continuity?: boolean | null;+ }+/*** * `categorical` - categorical* * `numeric` - numeric@@ -22946,6 +23015,108 @@ export namespace Schemas {readonly user_access_level: string | null;}+ /**+ * Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.+ */+ export interface ExperimentWrite {+ readonly id: number;+ /**+ * Name of the experiment.+ * @maxLength 400+ */+ name: string;+ /**+ * Description of the experiment hypothesis and expected outcomes.+ * @maxLength 3000+ * @nullable+ */+ description?: string | null;+ /** @nullable */+ start_date?: string | null;+ /** @nullable */+ end_date?: string | null;+ /** Unique key for the experiment's feature flag. Letters, numbers, hyphens, and underscores only. Search existing flags with the feature-flag-get-all tool first — reuse an existing flag when possible. */+ feature_flag_key: string;+ /** Feature-flag config for the experiment, in the flag's own filters shape. The linked flag is the source of truth for variants, rollout, aggregation, payloads, and experience continuity: send config here instead of the deprecated `parameters` keys. On a running experiment, also send `update_feature_flag_params=true`. Cannot be combined with the key of a pre-existing feature flag on create (the experiment links to it as-is). */+ feature_flag?: ExperimentFeatureFlagInput;+ readonly holdout: ExperimentHoldout;+ /**+ * ID of a holdout group to exclude from the experiment.+ * @nullable+ */+ holdout_id?: number | null;+ /** @nullable */+ readonly exposure_cohort: number | null;+ /** Experiment parameters JSON. Supported keys include `custom_exposure_filter` and `variant_notes` (free-text notes per variant, keyed by variant key). Flag config keys (`feature_flag_variants`, `rollout_percentage`) are a deprecated input surface kept for compatibility — the linked feature flag is the source of truth, and reads project its current config into this field. Excluded variants live on the top-level `excluded_variants` field, not here. */+ parameters?: ExperimentParameters | null;+ /** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`. */+ running_time_calculation?: ExperimentRunningTimeCalculation | null;+ /**+ * Variant keys to exclude from metric result calculations. Excluded variants are still served to users but omitted from statistical analysis. The baseline variant and holdout pseudo-variants cannot be excluded. Canonical home for what historically lived in `parameters.excluded_variants`.+ * @nullable+ */+ excluded_variants?: string[] | null;+ secondary_metrics?: unknown;+ readonly saved_metrics: readonly ExperimentToSavedMetric[];+ /**+ * IDs of shared saved metrics to attach to this experiment. Each item has 'id' (saved metric ID) and 'metadata' with 'type' (primary or secondary).+ * @nullable+ */+ saved_metrics_ids?: unknown[] | null;+ filters?: unknown;+ /** Whether the experiment is archived. */+ archived?: boolean;+ /** @nullable */+ deleted?: boolean | null;+ readonly created_by: UserBasic;+ readonly created_at: string;+ readonly updated_at: string;+ /** Experiment type: web for frontend UI changes, product for backend/API changes.+ *+ * * `web` - web+ * * `product` - product */+ type?: ExperimentTypeEnum | null;+ /** Exposure configuration including filter test accounts and custom exposure events. */+ exposure_criteria?: ExperimentApiExposureCriteria | null;+ /** Primary experiment metrics. Each metric must have kind='ExperimentMetric' and a metric_type: 'mean' (set source to an EventsNode with an event name), 'funnel' (set series to an array of EventsNode steps), 'ratio' (set numerator and denominator EventsNode entries), or 'retention' (set start_event and completion_event). Use the read-data-schema tool with query kind 'events' to find available events in the project. */+ metrics?: _ExperimentApiMetricsList | null;+ /** Secondary metrics for additional measurements. Same format as primary metrics. */+ metrics_secondary?: _ExperimentApiMetricsList | null;+ stats_config?: unknown;+ scheduling_config?: unknown;+ /** Suppresses the validation that rejects metrics referencing events not yet ingested by this project. REQUIRES explicit user confirmation before being set to true — never flip this silently to retry a failed call. The default validation catches typo'd event names and missing instrumentation. Set this to true only when the user has confirmed the event is intentional (e.g. they are about to instrument it). */+ allow_unknown_events?: boolean;+ _create_in_folder?: string;+ /** Experiment conclusion: won, lost, inconclusive, stopped_early, or invalid.+ *+ * * `won` - won+ * * `lost` - lost+ * * `inconclusive` - inconclusive+ * * `stopped_early` - stopped_early+ * * `invalid` - invalid */+ conclusion?: ConclusionEnum | null;+ /**+ * Comment about the experiment conclusion.+ * @maxLength 4000+ * @nullable+ */+ conclusion_comment?: string | null;+ primary_metrics_ordered_uuids?: unknown;+ secondary_metrics_ordered_uuids?: unknown;+ only_count_matured_users?: boolean;+ /** When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */+ update_feature_flag_params?: boolean;+ /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */+ readonly status: ExperimentStatusEnum;+ /** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */+ readonly is_legacy: boolean;+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level: string | null;+ }+export type ExperimentsListWidgetCatalogEntryOpenApiWidgetType = typeof ExperimentsListWidgetCatalogEntryOpenApiWidgetType[keyof typeof ExperimentsListWidgetCatalogEntryOpenApiWidgetType];@@ -24306,20 +24477,6 @@ export namespace Schemas {properties: FeatureFlagConditionPropertyAnalysis[];}- export interface FeatureFlagMultivariateVariantSchema {- /** Unique key for this variant. */- key: string;- /** Human-readable name for this variant. */- name?: string;- /** Variant rollout percentage. */- rollout_percentage: number;- }-- export interface FeatureFlagMultivariateSchema {- /** Variant definitions for multivariate feature flags. */- variants: FeatureFlagMultivariateVariantSchema[];- }-/*** Optional payload values keyed by variant key.*/@@ -38858,14 +39015,66 @@ export namespace Schemas {}/**- * Full experiment representation for the detail, create, and update endpoints.- *- * Extends the shared read-side fields in ``ExperimentBaseSerializer`` with the metric- * definitions (``metrics``/``metrics_secondary``/``saved_metrics``) and the write-side- * fields, and refreshes stale action names while serializing. The list endpoint uses the- * leaner ``ExperimentBasicSerializer`` instead.+ * A holdout group — a stable slice of users excluded from experiment exposure.*/- export interface PatchedExperiment {+ export interface PatchedExperimentHoldout {+ readonly id?: number;+ /**+ * Human-readable name for the holdout group.+ * @maxLength 400+ */+ name?: string;+ /**+ * Optional description of what this holdout reserves and why.+ * @maxLength 400+ * @nullable+ */+ description?: string | null;+ /** Non-empty list of release-condition groups defining the held-out population, using the same shape as feature-flag release conditions. Each element's `rollout_percentage` (0–100, may be fractional) is the **exclusion** percentage — the share of users held back from all experiments that reference this holdout. `properties` optionally narrows the group by person/group properties. Do not set `variant`: the server normalizes it to `holdout-{id}`. Note that only the first element's `rollout_percentage` is embedded into each linked experiment's feature flag, and this population is shared across every experiment using the holdout. */+ filters?: FeatureFlagConditionGroupSchema[];+ readonly created_by?: UserBasic;+ readonly created_at?: string;+ readonly updated_at?: string;+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level?: string | null;+ }++ /**+ * Mixin for serializers to add user access control fields+ */+ export interface PatchedExperimentSavedMetric {+ readonly id?: number;+ /**+ * Name of the shared metric. Must be unique within the project (case-insensitive).+ * @maxLength 400+ */+ name?: string;+ /**+ * Short description of what the metric measures.+ * @maxLength 400+ * @nullable+ */+ description?: string | null;+ /** ExperimentMetric JSON. Must have kind='ExperimentMetric' and a metric_type: 'mean' (set source to an EventsNode with an event name), 'funnel' (set series to an array of EventsNode steps), 'ratio' (set numerator and denominator EventsNode entries), or 'retention' (set start_event and completion_event). Legacy kinds (ExperimentTrendsQuery, ExperimentFunnelsQuery) are rejected for new shared metrics. */+ query?: unknown;+ readonly created_by?: UserBasic;+ readonly created_at?: string;+ readonly updated_at?: string;+ tags?: unknown[];+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level?: string | null;+ }++ /**+ * Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.+ */+ export interface PatchedExperimentWrite {readonly id?: number;/*** Name of the experiment.@@ -38884,7 +39093,8 @@ export namespace Schemas {end_date?: string | null;/** Unique key for the experiment's feature flag. Letters, numbers, hyphens, and underscores only. Search existing flags with the feature-flag-get-all tool first — reuse an existing flag when possible. */feature_flag_key?: string;- readonly feature_flag?: MinimalFeatureFlag;+ /** Feature-flag config for the experiment, in the flag's own filters shape. The linked flag is the source of truth for variants, rollout, aggregation, payloads, and experience continuity: send config here instead of the deprecated `parameters` keys. On a running experiment, also send `update_feature_flag_params=true`. Cannot be combined with the key of a pre-existing feature flag on create (the experiment links to it as-is). */+ feature_flag?: ExperimentFeatureFlagInput;readonly holdout?: ExperimentHoldout;/*** ID of a holdout group to exclude from the experiment.@@ -38950,7 +39160,7 @@ export namespace Schemas {primary_metrics_ordered_uuids?: unknown;secondary_metrics_ordered_uuids?: unknown;only_count_matured_users?: boolean;- /** When true, sync feature flag configuration from parameters to the linked feature flag. Draft experiments always sync regardless of update_feature_flag_params, so only required for non-drafts. */+ /** When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */update_feature_flag_params?: boolean;/** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */readonly status?: ExperimentStatusEnum;@@ -38963,63 +39173,6 @@ export namespace Schemas {readonly user_access_level?: string | null;}- /**- * A holdout group — a stable slice of users excluded from experiment exposure.- */- export interface PatchedExperimentHoldout {- readonly id?: number;- /**- * Human-readable name for the holdout group.- * @maxLength 400- */- name?: string;- /**- * Optional description of what this holdout reserves and why.- * @maxLength 400- * @nullable- */- description?: string | null;- /** Non-empty list of release-condition groups defining the held-out population, using the same shape as feature-flag release conditions. Each element's `rollout_percentage` (0–100, may be fractional) is the **exclusion** percentage — the share of users held back from all experiments that reference this holdout. `properties` optionally narrows the group by person/group properties. Do not set `variant`: the server normalizes it to `holdout-{id}`. Note that only the first element's `rollout_percentage` is embedded into each linked experiment's feature flag, and this population is shared across every experiment using the holdout. */- filters?: FeatureFlagConditionGroupSchema[];- readonly created_by?: UserBasic;- readonly created_at?: string;- readonly updated_at?: string;- /**- * The effective access level the user has for this object- * @nullable- */- readonly user_access_level?: string | null;- }-- /**- * Mixin for serializers to add user access control fields- */- export interface PatchedExperimentSavedMetric {- readonly id?: number;- /**- * Name of the shared metric. Must be unique within the project (case-insensitive).- * @maxLength 400- */- name?: string;- /**- * Short description of what the metric measures.- * @maxLength 400- * @nullable- */- description?: string | null;- /** ExperimentMetric JSON. Must have kind='ExperimentMetric' and a metric_type: 'mean' (set source to an EventsNode with an event name), 'funnel' (set series to an array of EventsNode steps), 'ratio' (set numerator and denominator EventsNode entries), or 'retention' (set start_event and completion_event). Legacy kinds (ExperimentTrendsQuery, ExperimentFunnelsQuery) are rejected for new shared metrics. */- query?: unknown;- readonly created_by?: UserBasic;- readonly created_at?: string;- readonly updated_at?: string;- tags?: unknown[];- /**- * The effective access level the user has for this object- * @nullable- */- readonly user_access_level?: string | null;- }-/*** @nullable*/diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.tsindex e3146c1193a6..fad8e0a5af6c 100644--- a/services/mcp/src/generated/experiments/api.ts+++ b/services/mcp/src/generated/experiments/api.ts@@ -742,6 +742,11 @@ export const experimentsCreateBodyNameMax = 400export const experimentsCreateBodyDescriptionMax = 3000+export const experimentsCreateBodyFeatureFlagOneFiltersOneGroupsItemRolloutPercentageMin = 0+export const experimentsCreateBodyFeatureFlagOneFiltersOneGroupsItemRolloutPercentageMax = 100++export const experimentsCreateBodyFeatureFlagOneFiltersOneGroupsItemPropertiesMax = 0+export const experimentsCreateBodyArchivedDefault = falseexport const experimentsCreateBodyExposureCriteriaOneExposureConfigOnePropertiesItemOneOperatorDefault = `exact`export const experimentsCreateBodyExposureCriteriaOneExposureConfigOnePropertiesItemOneTypeDefault = `event`@@ -848,6 +853,88 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod.describe("Unique key for the experiment's feature flag. Letters, numbers, hyphens, and underscores only. Search existing flags with the feature-flag-get-all tool first — reuse an existing flag when possible."),+ feature_flag: zod+ .object({+ filters: zod+ .object({+ groups: zod+ .array(+ zod+ .object({+ rollout_percentage: zod+ .number()+ .min(+ experimentsCreateBodyFeatureFlagOneFiltersOneGroupsItemRolloutPercentageMin+ )+ .max(+ experimentsCreateBodyFeatureFlagOneFiltersOneGroupsItemRolloutPercentageMax+ )+ .nullish()+ .describe('Percentage of users who enter the experiment (0-100).'),+ properties: zod+ .array(zod.unknown())+ .max(experimentsCreateBodyFeatureFlagOneFiltersOneGroupsItemPropertiesMax)+ .optional()+ .describe(+ 'Must be empty or omitted: release-condition properties are not supported via the experiment input. Edit the feature flag directly for targeting.'+ ),+ })+ .describe(+ 'A single release-condition group carrying only the overall rollout percentage, the one\ngroups entry the experiment input applies.'+ )+ )+ .optional()+ .describe(+ 'Overall rollout as a single group: [{"properties": [], "rollout_percentage": N}].'+ ),+ multivariate: zod+ .union([+ zod.object({+ variants: zod+ .array(+ zod.object({+ key: zod.string().describe('Unique key for this variant.'),+ name: zod+ .string()+ .optional()+ .describe('Human-readable name for this variant.'),+ rollout_percentage: zod+ .number()+ .describe('Variant rollout percentage.'),+ })+ )+ .describe('Variant definitions for multivariate feature flags.'),+ }),+ zod.null(),+ ])+ .optional()+ .describe('Multivariate configuration for variant-based rollouts.'),+ aggregation_group_type_index: zod+ .number()+ .nullish()+ .describe('Group type index for group-based feature flags.'),+ payloads: zod+ .record(zod.string(), zod.string())+ .optional()+ .describe('Optional payload values keyed by variant key.'),+ })+ .describe(+ "Feature-flag filters accepted by the experiment endpoints: the flag's own filters shape,\nminus the keys experiments don't apply."+ )+ .optional()+ .describe(+ "Flag config to apply: `multivariate.variants` (exactly one variant key must be the literal string 'control'), `groups` (a single group with `rollout_percentage` only; release conditions are not supported here, edit the feature flag directly), `aggregation_group_type_index`, and `payloads` (JSON-encoded strings keyed by variant key). On update, config this object omits is preserved from the linked flag's current state."+ ),+ ensure_experience_continuity: zod+ .boolean()+ .nullish()+ .describe('Whether the flag persists variant assignment across authentication steps.'),+ })+ .describe("Flag config for experiment create/update, sent through the linked feature flag's own shape.")+ .optional()+ .describe(+ "Feature-flag config for the experiment, in the flag's own filters shape. The linked flag is the source of truth for variants, rollout, aggregation, payloads, and experience continuity: send config here instead of the deprecated `parameters` keys. On a running experiment, also send `update_feature_flag_params=true`. Cannot be combined with the key of a pre-existing feature flag on create (the experiment links to it as-is)."+ ),holdout_id: zod.number().nullish().describe('ID of a holdout group to exclude from the experiment.'),parameters: zod.union([@@ -4131,12 +4218,10 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod.boolean().default(experimentsCreateBodyUpdateFeatureFlagParamsDefault).describe(- 'When true, sync feature flag configuration from parameters to the linked feature flag. Draft experiments always sync regardless of update_feature_flag_params, so only required for non-drafts.'+ 'When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected.'),})- .describe(- 'Full experiment representation for the detail, create, and update endpoints.\n\nExtends the shared read-side fields in ``ExperimentBaseSerializer`` with the metric\ndefinitions (``metrics``/``metrics_secondary``/``saved_metrics``) and the write-side\nfields, and refreshes stale action names while serializing. The list endpoint uses the\nleaner ``ExperimentBasicSerializer`` instead.'- )+ .describe('Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.')/*** Retrieve a single experiment by ID, including its current status, metrics, feature flag, and results metadata.@@ -4151,7 +4236,7 @@ export const ExperimentsRetrieveParams = /* @__PURE__ */ zod.object({})/**- * Update an experiment. Use this to modify experiment properties such as name, description, metrics, variants, and configuration. Metrics can be added, changed and removed at any time.+ * Update an experiment. Use this to modify experiment properties such as name, description, metrics, variants, and configuration. Metrics can be added, changed and removed at any time. Feature-flag config (variants, rollout, payloads) is sent via the feature_flag object.*/export const ExperimentsPartialUpdateParams = /* @__PURE__ */ zod.object({id: zod.number().describe('A unique integer value identifying this experiment.'),@@ -4166,6 +4251,11 @@ export const experimentsPartialUpdateBodyNameMax = 400export const experimentsPartialUpdateBodyDescriptionMax = 3000+export const experimentsPartialUpdateBodyFeatureFlagOneFiltersOneGroupsItemRolloutPercentageMin = 0+export const experimentsPartialUpdateBodyFeatureFlagOneFiltersOneGroupsItemRolloutPercentageMax = 100++export const experimentsPartialUpdateBodyFeatureFlagOneFiltersOneGroupsItemPropertiesMax = 0+export const experimentsPartialUpdateBodyExposureCriteriaOneExposureConfigOnePropertiesItemOneOperatorDefault = `exact`export const experimentsPartialUpdateBodyExposureCriteriaOneExposureConfigOnePropertiesItemOneTypeDefault = `event`export const experimentsPartialUpdateBodyExposureCriteriaOneExposureConfigOnePropertiesItemTwoTypeDefault = `person`@@ -4269,6 +4359,90 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod.describe("Unique key for the experiment's feature flag. Letters, numbers, hyphens, and underscores only. Search existing flags with the feature-flag-get-all tool first — reuse an existing flag when possible."),+ feature_flag: zod+ .object({+ filters: zod+ .object({+ groups: zod+ .array(+ zod+ .object({+ rollout_percentage: zod+ .number()+ .min(+ experimentsPartialUpdateBodyFeatureFlagOneFiltersOneGroupsItemRolloutPercentageMin+ )+ .max(+ experimentsPartialUpdateBodyFeatureFlagOneFiltersOneGroupsItemRolloutPercentageMax+ )+ .nullish()+ .describe('Percentage of users who enter the experiment (0-100).'),+ properties: zod+ .array(zod.unknown())+ .max(+ experimentsPartialUpdateBodyFeatureFlagOneFiltersOneGroupsItemPropertiesMax+ )+ .optional()+ .describe(+ 'Must be empty or omitted: release-condition properties are not supported via the experiment input. Edit the feature flag directly for targeting.'+ ),+ })+ .describe(+ 'A single release-condition group carrying only the overall rollout percentage, the one\ngroups entry the experiment input applies.'+ )+ )+ .optional()+ .describe(+ 'Overall rollout as a single group: [{"properties": [], "rollout_percentage": N}].'+ ),+ multivariate: zod+ .union([+ zod.object({+ variants: zod+ .array(+ zod.object({+ key: zod.string().describe('Unique key for this variant.'),+ name: zod+ .string()+ .optional()+ .describe('Human-readable name for this variant.'),+ rollout_percentage: zod+ .number()+ .describe('Variant rollout percentage.'),+ })+ )+ .describe('Variant definitions for multivariate feature flags.'),+ }),+ zod.null(),+ ])+ .optional()+ .describe('Multivariate configuration for variant-based rollouts.'),+ aggregation_group_type_index: zod+ .number()+ .nullish()+ .describe('Group type index for group-based feature flags.'),+ payloads: zod+ .record(zod.string(), zod.string())+ .optional()+ .describe('Optional payload values keyed by variant key.'),+ })+ .describe(+ "Feature-flag filters accepted by the experiment endpoints: the flag's own filters shape,\nminus the keys experiments don't apply."+ )+ .optional()+ .describe(+ "Flag config to apply: `multivariate.variants` (exactly one variant key must be the literal string 'control'), `groups` (a single group with `rollout_percentage` only; release conditions are not supported here, edit the feature flag directly), `aggregation_group_type_index`, and `payloads` (JSON-encoded strings keyed by variant key). On update, config this object omits is preserved from the linked flag's current state."+ ),+ ensure_experience_continuity: zod+ .boolean()+ .nullish()+ .describe('Whether the flag persists variant assignment across authentication steps.'),+ })+ .describe("Flag config for experiment create/update, sent through the linked feature flag's own shape.")+ .optional()+ .describe(+ "Feature-flag config for the experiment, in the flag's own filters shape. The linked flag is the source of truth for variants, rollout, aggregation, payloads, and experience continuity: send config here instead of the deprecated `parameters` keys. On a running experiment, also send `update_feature_flag_params=true`. Cannot be combined with the key of a pre-existing feature flag on create (the experiment links to it as-is)."+ ),holdout_id: zod.number().nullish().describe('ID of a holdout group to exclude from the experiment.'),parameters: zod.union([@@ -7557,12 +7731,10 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod.boolean().optional().describe(- 'When true, sync feature flag configuration from parameters to the linked feature flag. Draft experiments always sync regardless of update_feature_flag_params, so only required for non-drafts.'+ 'When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected.'),})- .describe(- 'Full experiment representation for the detail, create, and update endpoints.\n\nExtends the shared read-side fields in ``ExperimentBaseSerializer`` with the metric\ndefinitions (``metrics``/``metrics_secondary``/``saved_metrics``) and the write-side\nfields, and refreshes stale action names while serializing. The list endpoint uses the\nleaner ``ExperimentBasicSerializer`` instead.'- )+ .describe('Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.')/*** Hard delete of this model is not allowed. Use a patch API call to set "deleted" to true@@ -11040,7 +11212,7 @@ export const ExperimentsDuplicateCreateBody = /* @__PURE__ */ zod.boolean().default(experimentsDuplicateCreateBodyUpdateFeatureFlagParamsDefault).describe(- 'When true, sync feature flag configuration from parameters to the linked feature flag. Draft experiments always sync regardless of update_feature_flag_params, so only required for non-drafts.'+ 'When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected.'),}).describe(diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.tsindex 8b8ebd120ffc..00829c7b84b8 100644--- a/services/mcp/src/tools/generated/experiments.ts+++ b/services/mcp/src/tools/generated/experiments.ts@@ -180,8 +180,8 @@ const ExperimentCreateSchema = ExperimentsCreateBody.omit({only_count_matured_users: true,update_feature_flag_params: true,}).extend({- parameters: ExperimentsCreateBody.shape['parameters'].describe(- 'Variant split and rollout scope. If the user mentions a specific percentage, load the configuring-experiment-rollout skill and clarify before setting these values. Set rollout_percentage (0-100) to control the overall fraction of users entering the experiment. Set feature_flag_variants with split_percent on each variant to customize the variant split. Default: 50/50 control/test, 100% rollout. HARD REQUIREMENT — when you provide feature_flag_variants, exactly one variant\'s `key` must be the literal string `control` (lowercase, no variations). It is the baseline used for analysis and the experiment runtime treats it specially. If the user describes variants as "A/B", "old/new", "original/redesign", or any other natural-language pair, map the baseline to `key: "control"` — not "A", "Control", "old", "original", or "baseline". Other variants can use any key (`test`, `variant_a`, etc.).'+ feature_flag: ExperimentsCreateBody.shape['feature_flag'].describe(+ 'Variant split, rollout scope, payloads, and experience continuity for the auto-created feature flag, in the flag\'s own filters shape. This is the canonical input, do not send flag config via the deprecated parameters keys (feature_flag_variants, rollout_percentage). If the user mentions a specific percentage, load the configuring-experiment-rollout skill and clarify before setting these values. Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100) to customize the variant split. Set filters.groups to a single group [{"properties": [], "rollout_percentage": N}] (0-100) to control the overall fraction of users entering the experiment. Default: 50/50 control/test, 100% rollout. Omit this parameter entirely when feature_flag_key refers to a pre-existing flag: the experiment links to that flag as-is and explicit config is rejected. HARD REQUIREMENT — when you provide variants, exactly one variant\'s `key` must be the literal string `control` (lowercase, no variations). It is the baseline used for analysis and the experiment runtime treats it specially. If the user describes variants as "A/B", "old/new", "original/redesign", or any other natural-language pair, map the baseline to `key: "control"` — not "A", "Control", "old", "original", or "baseline". Other variants can use any key (`test`, `variant_a`, etc.).'),})@@ -201,6 +201,9 @@ const experimentCreate = (): ToolBase<typeof ExperimentCreateSchema, WithPostHogif (params.feature_flag_key !== undefined) {body['feature_flag_key'] = params.feature_flag_key}+ if (params.feature_flag !== undefined) {+ body['feature_flag'] = params.feature_flag+ }if (params.holdout_id !== undefined) {body['holdout_id'] = params.holdout_id}@@ -896,6 +899,9 @@ const ExperimentUpdateSchema = ExperimentsPartialUpdateParams.omit({ project_id:).extend({id: z.preprocess(castStringToInt, ExperimentsPartialUpdateParams.shape['id']),+ feature_flag: ExperimentsPartialUpdateBody.shape['feature_flag'].describe(+ 'Variant split, rollout scope, payloads, and experience continuity for the linked feature flag, in the flag\'s own filters shape. This is the canonical input, do not send flag config via the deprecated parameters keys (feature_flag_variants, rollout_percentage). Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100, exactly one key must be the literal string \'control\') to change the variant split. Set filters.groups to a single group [{"properties": [], "rollout_percentage": N}] (0-100) to change the overall rollout. Config this object omits is preserved from the flag\'s current state. On a running experiment this requires update_feature_flag_params=true (see rule 1: warn the user first).'+ ),running_time_calculation: ExperimentsPartialUpdateBody.shape['running_time_calculation'].describe("Persist a running-time / sample-size plan onto the experiment (the planning target shown in the experiment's running-time panel). Object with optional keys: minimum_detectable_effect (percentage, e.g. 20 for a 20% lift), recommended_sample_size (total across all variants), recommended_running_time (days), and exposure_estimate_config."),@@ -915,6 +921,9 @@ const experimentUpdate = (): ToolBase<typeof ExperimentUpdateSchema, WithPostHogif (params.description !== undefined) {body['description'] = params.description}+ if (params.feature_flag !== undefined) {+ body['feature_flag'] = params.feature_flag+ }if (params.holdout_id !== undefined) {body['holdout_id'] = params.holdout_id}diff --git a/services/mcp/tests/tools/experiments.integration.test.ts b/services/mcp/tests/tools/experiments.integration.test.tsindex 14275bb29d7e..3b3af3b02e6a 100644--- a/services/mcp/tests/tools/experiments.integration.test.ts+++ b/services/mcp/tests/tools/experiments.integration.test.ts@@ -150,12 +150,16 @@ describe('Experiments', { concurrent: false }, () => {const params = {name: 'Variant Test Experiment',feature_flag_key: flagKey,- parameters: {- feature_flag_variants: [- { key: 'control', name: 'Control Group', split_percent: 33 },- { key: 'variant_a', name: 'Variant A', split_percent: 33 },- { key: 'variant_b', name: 'Variant B', split_percent: 34 },- ],+ feature_flag: {+ filters: {+ multivariate: {+ variants: [+ { key: 'control', name: 'Control Group', rollout_percentage: 33 },+ { key: 'variant_a', name: 'Variant A', rollout_percentage: 33 },+ { key: 'variant_b', name: 'Variant B', rollout_percentage: 34 },+ ],+ },+ },},allow_unknown_events: true,}@@ -588,11 +592,17 @@ describe('Experiments', { concurrent: false }, () => {description: 'Testing complete experiment workflow with all features',feature_flag_key: flagKey,type: 'product',+ feature_flag: {+ filters: {+ multivariate: {+ variants: [+ { key: 'control', name: 'Control', rollout_percentage: 50 },+ { key: 'test', name: 'Test Variant', rollout_percentage: 50 },+ ],+ },+ },+ },parameters: {- feature_flag_variants: [- { key: 'control', name: 'Control', split_percent: 50 },- { key: 'test', name: 'Test Variant', split_percent: 50 },- ],minimum_detectable_effect: 20,},exposure_criteria: {@@ -770,11 +780,15 @@ describe('Experiments', { concurrent: false }, () => {const params = {name: 'Invalid Rollout Experiment',feature_flag_key: flagKey,- parameters: {- feature_flag_variants: [- { key: 'control', split_percent: 60 },- { key: 'test', split_percent: 60 }, // Total > 100%- ],+ feature_flag: {+ filters: {+ multivariate: {+ variants: [+ { key: 'control', rollout_percentage: 60 },+ { key: 'test', rollout_percentage: 60 }, // Total > 100%+ ],+ },+ },},allow_unknown_events: true,}@@ -1156,17 +1170,17 @@ describe('Experiments', { concurrent: false }, () => {const createParams = {name: 'Variants Update Test',feature_flag_key: flagKey,- parameters: {- feature_flag_variants: [- { key: 'control', split_percent: 50 },- { key: 'test', split_percent: 50 },- ],+ feature_flag: {+ filters: {+ multivariate: {+ variants: [+ { key: 'control', rollout_percentage: 50 },+ { key: 'test', rollout_percentage: 50 },+ ],+ },+ },},allow_unknown_events: true,- feature_flag_variants: [- { key: 'control', split_percent: 50 },- { key: 'test', split_percent: 50 },- ],}const createResult = await createTool.handler(context, createParams as any)diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.jsonindex 4ed01217f6d4..1ed7201f88e1 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.json@@ -1975,6 +1975,115 @@],"description": "Exposure configuration including filter test accounts and custom exposure events."},+ "feature_flag": {+ "description": "Variant split, rollout scope, payloads, and experience continuity for the auto-created feature flag, in the flag's own filters shape. This is the canonical input, do not send flag config via the deprecated parameters keys (feature_flag_variants, rollout_percentage). If the user mentions a specific percentage, load the configuring-experiment-rollout skill and clarify before setting these values. Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100) to customize the variant split. Set filters.groups to a single group [{\"properties\": [], \"rollout_percentage\": N}] (0-100) to control the overall fraction of users entering the experiment. Default: 50/50 control/test, 100% rollout. Omit this parameter entirely when feature_flag_key refers to a pre-existing flag: the experiment links to that flag as-is and explicit config is rejected. HARD REQUIREMENT — when you provide variants, exactly one variant's `key` must be the literal string `control` (lowercase, no variations). It is the baseline used for analysis and the experiment runtime treats it specially. If the user describes variants as \"A/B\", \"old/new\", \"original/redesign\", or any other natural-language pair, map the baseline to `key: \"control\"` — not \"A\", \"Control\", \"old\", \"original\", or \"baseline\". Other variants can use any key (`test`, `variant_a`, etc.).",+ "properties": {+ "ensure_experience_continuity": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "description": "Whether the flag persists variant assignment across authentication steps."+ },+ "filters": {+ "description": "Flag config to apply: `multivariate.variants` (exactly one variant key must be the literal string 'control'), `groups` (a single group with `rollout_percentage` only; release conditions are not supported here, edit the feature flag directly), `aggregation_group_type_index`, and `payloads` (JSON-encoded strings keyed by variant key). On update, config this object omits is preserved from the linked flag's current state.",+ "properties": {+ "aggregation_group_type_index": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Group type index for group-based feature flags."+ },+ "groups": {+ "description": "Overall rollout as a single group: [{\"properties\": [], \"rollout_percentage\": N}].",+ "items": {+ "description": "A single release-condition group carrying only the overall rollout percentage, the one\ngroups entry the experiment input applies.",+ "properties": {+ "properties": {+ "description": "Must be empty or omitted: release-condition properties are not supported via the experiment input. Edit the feature flag directly for targeting.",+ "items": {},+ "maxItems": 0,+ "type": "array"+ },+ "rollout_percentage": {+ "anyOf": [+ {+ "maximum": 100,+ "minimum": 0,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Percentage of users who enter the experiment (0-100)."+ }+ },+ "type": "object"+ },+ "type": "array"+ },+ "multivariate": {+ "anyOf": [+ {+ "properties": {+ "variants": {+ "description": "Variant definitions for multivariate feature flags.",+ "items": {+ "properties": {+ "key": {+ "description": "Unique key for this variant.",+ "type": "string"+ },+ "name": {+ "description": "Human-readable name for this variant.",+ "type": "string"+ },+ "rollout_percentage": {+ "description": "Variant rollout percentage.",+ "type": "number"+ }+ },+ "required": ["key", "rollout_percentage"],+ "type": "object"+ },+ "type": "array"+ }+ },+ "required": ["variants"],+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Multivariate configuration for variant-based rollouts."+ },+ "payloads": {+ "additionalProperties": {+ "type": "string"+ },+ "description": "Optional payload values keyed by variant key.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ }+ },+ "type": "object"+ }+ },+ "type": "object"+ },"feature_flag_key": {"description": "Unique key for the experiment's feature flag. Letters, numbers, hyphens, and underscores only. Search existing flags with the feature-flag-get-all tool first — reuse an existing flag when possible.","type": "string"@@ -2098,7 +2207,7 @@"type": "null"}],- "description": "Variant split and rollout scope. If the user mentions a specific percentage, load the configuring-experiment-rollout skill and clarify before setting these values. Set rollout_percentage (0-100) to control the overall fraction of users entering the experiment. Set feature_flag_variants with split_percent on each variant to customize the variant split. Default: 50/50 control/test, 100% rollout. HARD REQUIREMENT — when you provide feature_flag_variants, exactly one variant's `key` must be the literal string `control` (lowercase, no variations). It is the baseline used for analysis and the experiment runtime treats it specially. If the user describes variants as \"A/B\", \"old/new\", \"original/redesign\", or any other natural-language pair, map the baseline to `key: \"control\"` — not \"A\", \"Control\", \"old\", \"original\", or \"baseline\". Other variants can use any key (`test`, `variant_a`, etc.)."+ "description": "Experiment parameters JSON. Supported keys include `custom_exposure_filter` and `variant_notes` (free-text notes per variant, keyed by variant key). Flag config keys (`feature_flag_variants`, `rollout_percentage`) are a deprecated input surface kept for compatibility — the linked feature flag is the source of truth, and reads project its current config into this field. Excluded variants live on the top-level `excluded_variants` field, not here."},"stats_config": {}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.jsonindex 290499df5d17..af24ba3fdc96 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json@@ -2017,6 +2017,115 @@],"description": "Exposure configuration including filter test accounts and custom exposure events."},+ "feature_flag": {+ "description": "Variant split, rollout scope, payloads, and experience continuity for the linked feature flag, in the flag's own filters shape. This is the canonical input, do not send flag config via the deprecated parameters keys (feature_flag_variants, rollout_percentage). Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100, exactly one key must be the literal string 'control') to change the variant split. Set filters.groups to a single group [{\"properties\": [], \"rollout_percentage\": N}] (0-100) to change the overall rollout. Config this object omits is preserved from the flag's current state. On a running experiment this requires update_feature_flag_params=true (see rule 1: warn the user first).",+ "properties": {+ "ensure_experience_continuity": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "description": "Whether the flag persists variant assignment across authentication steps."+ },+ "filters": {+ "description": "Flag config to apply: `multivariate.variants` (exactly one variant key must be the literal string 'control'), `groups` (a single group with `rollout_percentage` only; release conditions are not supported here, edit the feature flag directly), `aggregation_group_type_index`, and `payloads` (JSON-encoded strings keyed by variant key). On update, config this object omits is preserved from the linked flag's current state.",+ "properties": {+ "aggregation_group_type_index": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Group type index for group-based feature flags."+ },+ "groups": {+ "description": "Overall rollout as a single group: [{\"properties\": [], \"rollout_percentage\": N}].",+ "items": {+ "description": "A single release-condition group carrying only the overall rollout percentage, the one\ngroups entry the experiment input applies.",+ "properties": {+ "properties": {+ "description": "Must be empty or omitted: release-condition properties are not supported via the experiment input. Edit the feature flag directly for targeting.",+ "items": {},+ "maxItems": 0,+ "type": "array"+ },+ "rollout_percentage": {+ "anyOf": [+ {+ "maximum": 100,+ "minimum": 0,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Percentage of users who enter the experiment (0-100)."+ }+ },+ "type": "object"+ },+ "type": "array"+ },+ "multivariate": {+ "anyOf": [+ {+ "properties": {+ "variants": {+ "description": "Variant definitions for multivariate feature flags.",+ "items": {+ "properties": {+ "key": {+ "description": "Unique key for this variant.",+ "type": "string"+ },+ "name": {+ "description": "Human-readable name for this variant.",+ "type": "string"+ },+ "rollout_percentage": {+ "description": "Variant rollout percentage.",+ "type": "number"+ }+ },+ "required": ["key", "rollout_percentage"],+ "type": "object"+ },+ "type": "array"+ }+ },+ "required": ["variants"],+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Multivariate configuration for variant-based rollouts."+ },+ "payloads": {+ "additionalProperties": {+ "type": "string"+ },+ "description": "Optional payload values keyed by variant key.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ }+ },+ "type": "object"+ }+ },+ "type": "object"+ },"holdout_id": {"anyOf": [{@@ -5569,7 +5678,7 @@},"stats_config": {},"update_feature_flag_params": {- "description": "When true, sync feature flag configuration from parameters to the linked feature flag. Draft experiments always sync regardless of update_feature_flag_params, so only required for non-drafts.",+ "description": "When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected.","type": "boolean"}},