: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(mcp): return condition_id from feature flag read tools (#120691)
Phil Haack8c626c87f0c8
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex e5f71cd83070..f14f32a70cef 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -5968,6 +5968,10 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):"detail": "groups[0].properties[0]: Group properties must match the condition set's group type.","attr": "filters",},+ "services/mcp/src/tools/featureFlags/updateFeatureFlagHooks.ts matches this code (GROUP_TYPE_MISMATCH) "+ "and the `groups[i].properties[j]: ` prefix (PROPERTY_REJECTION) to add a recovery step to the "+ "update-feature-flag error. If either changes, update that hook and "+ "services/mcp/tests/unit/update-feature-flag-preserving-groups.test.ts, then this assertion.",)person_request = self._create_flag_with_properties(diff --git a/products/feature_flags/backend/test/test_filters_validation.py b/products/feature_flags/backend/test/test_filters_validation.pyindex 6d08aacd0c19..bbbd304f4a48 100644--- a/products/feature_flags/backend/test/test_filters_validation.py+++ b/products/feature_flags/backend/test/test_filters_validation.py@@ -388,7 +388,7 @@ class TestFiltersValidation(SimpleTestCase):assert not serializer.is_valid()assert str(serializer.errors["filters"][0]).startswith("groups[1].properties[0].type: "), ("services/mcp/src/tools/featureFlags/updateFeatureFlagHooks.ts matches this prefix "- "(PROPERTY_TYPE_REJECTION) to add a recovery step to the update-feature-flag error. "+ "(PROPERTY_REJECTION) to add a recovery step to the update-feature-flag error. ""If the prefix changes, update that regex and ""services/mcp/tests/unit/update-feature-flag-preserving-groups.test.ts, then this assertion.")diff --git a/products/feature_flags/evals/scorers.py b/products/feature_flags/evals/scorers.pyindex efb36cf937ad..76ae5d2442e6 100644--- a/products/feature_flags/evals/scorers.py+++ b/products/feature_flags/evals/scorers.py@@ -376,7 +376,11 @@ def _canonical_group(group: dict) -> str:are sorted because an agent that rewrites the definition may emit them in any order."""properties = group.get("properties")- canonical: dict[str, Any] = {key: value for key, value in group.items() if key != "properties"}+ # condition_id is a hash the MCP read tools add and the update tool strips before the PATCH.+ # The seeded filters never carry it, so a correct write that echoes it must still match.+ canonical: dict[str, Any] = {+ key: value for key, value in group.items() if key not in ("properties", "condition_id")+ }canonical["properties"] = (sorted(json.dumps(prop, sort_keys=True) for prop in properties) if isinstance(properties, list) else properties)diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yamlindex fecbb5131d28..d688bfbabcde 100644--- a/products/feature_flags/mcp/tools.yaml+++ b/products/feature_flags/mcp/tools.yaml@@ -70,6 +70,7 @@ tools:description:Identifier used to bucket users into rollout percentages and variants — `distinct_id` (user ID, thedefault) or `device_id`. Using `device_id` is incompatible with `ensure_experience_continuity=true`.+ hooks: featureFlags/conditionIdHooksdelete-feature-flag:operation: feature_flags_destroyenabled: true@@ -90,6 +91,7 @@ tools:- flag_id- feature_flag_id- featureFlagId+ hooks: featureFlags/conditionIdHookssoft_delete: truefeature-flag-archive:operation: feature_flags_archive_create@@ -317,6 +319,7 @@ tools:- flag_id- feature_flag_id- featureFlagId+ hooks: featureFlags/conditionIdHooksfeature-flag-roll-out-to-everyone:operation: feature_flags_roll_out_to_everyone_createenabled: true@@ -396,6 +399,7 @@ tools:- flag_id- feature_flag_id- featureFlagId+ hooks: featureFlags/conditionIdHooksresponse:include:- id@@ -456,6 +460,7 @@ tools:- flag_id- feature_flag_id- featureFlagId+ hooks: featureFlags/conditionIdHooksresponse:include:- id@@ -672,6 +677,7 @@ tools:specific flags. This is strongly recommended on projects with many flags, since omitting it returns an entryfor every flag and can produce a very large payload. Optionally pass `groups` as a JSON object to evaluategroup-based flags.+ hooks: featureFlags/conditionIdHooksfeature-flags-status-retrieve:operation: feature_flags_status_retrieveenabled: true@@ -850,16 +856,23 @@ tools:Rollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters`- replaces the whole object, so read the flag first and merge your change. When the flag targets groups, keep- `type: "group"`, `group_type_index`, and `filters.aggregation_group_type_index` in what you send; if you- omit them this tool restores them from the existing flag so group targeting is not silently converted to- person targeting. When the flag's conditions don't all target the same thing (some target persons and others- a group type, or they target different group types), set `aggregation_group_type_index` on every condition- whenever you add, remove, reorder, or change the properties of conditions. Use null for persons. Otherwise- this tool can't tell which target each condition keeps, and it refuses the update. Use- `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full- definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at- a future time instead, use `scheduled-changes-create`.+ replaces the whole object, so read the flag first and merge your change. Each release condition you read has+ a `condition_id`. Send it unchanged on every condition you keep, edit, or move, and leave it off a new+ condition. A `condition_id` belongs to the flag you read it from, so leave it off a condition copied from a+ different flag. Once any condition has a `condition_id`, a condition without one is treated as new. This+ tool uses the ID to restore each condition's property types and targeting, so a reorder, deletion, or edit+ keeps every condition on the persons or group type it targeted. If a `condition_id` matches no condition on+ the flag, the flag may have changed after your read, and the update is refused. Read the flag again and+ rebuild the update. When the flag targets groups, keep `type: "group"`, `group_type_index`, and+ `filters.aggregation_group_type_index` in what you send; if you omit them this tool restores them from the+ existing flag so group targeting is not silently converted to person targeting. When the flag's conditions+ don't all target the same thing (some target persons and others a group type, or they target different group+ types), set `aggregation_group_type_index` on every new condition. Use null for persons. If you send no+ `condition_id` values, set `aggregation_group_type_index` on every condition whenever you add, remove,+ reorder, or change the properties of conditions. Otherwise this tool can't tell which target each condition+ keeps, and it refuses the update. Use `feature-flag-get-definition-by-key` when you have the string key: it+ returns the numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you+ already have the ID. To apply a change at a future time instead, use `scheduled-changes-create`.include_params:- key- name@@ -881,14 +894,7 @@ tools:- feature_flag_id- featureFlagIdfilters:- description: >- Full release-condition object (replaces filters at the API). For group flags set- aggregation_group_type_index and property type "group" + group_type_index. Omitted type /- group_type_index / aggregation_group_type_index are filled from the existing flag to prevent silent- person demotion (see #46501). When conditions don't all target the same thing (persons and a group- type, or different group types) and you add, remove, reorder, or change the properties of- conditions, set aggregation_group_type_index on each condition (null for persons), or the update is- refused.+ input_schema: UpdateFeatureFlagFiltersSchemais_remote_configuration:description:Whether this flag delivers a payload instead of gating a feature (Remote Config mode). When true, set thediff --git a/products/posthog_ai/eval_harness/test/test_flag_lifecycle_scorers.py b/products/posthog_ai/eval_harness/test/test_flag_lifecycle_scorers.pyindex 48905411711e..c4bd9a3ee6c9 100644--- a/products/posthog_ai/eval_harness/test/test_flag_lifecycle_scorers.py+++ b/products/posthog_ai/eval_harness/test/test_flag_lifecycle_scorers.py@@ -118,6 +118,13 @@ def _flattened_filters() -> dict[str, Any]:return {"groups": [{"properties": [], "rollout_percentage": ROLLOUT_TO_PERCENTAGE}]}+def _with_condition_ids() -> dict[str, Any]:+ filters = _merged_filters()+ for index, group in enumerate(filters["groups"]):+ group["condition_id"] = f"condition-{index}"+ return filters++def _without(key: str) -> dict[str, Any]:filters = _merged_filters()filters.pop(key)@@ -436,6 +443,9 @@ def test_created_flag_with_tags_grades_the_asked_for_key(_name: str, created_key# An agent that rewrites the definition may reorder keys and conditions without# changing who the flag serves. Failing that would fail every correct run.("rewrote_the_definition_in_a_different_order", _reordered_filters(), 1.0),+ # The MCP read tools add a condition_id to each condition. update-feature-flag asks+ # the agent to send it back.+ ("echoed_the_condition_ids", _with_condition_ids(), 1.0),("dropped_the_variants", _without("multivariate"), 0.0),("dropped_the_payloads", _without("payloads"), 0.0),(diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex e7ffbcf9d6a8..e5c259548bbc 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -14502,7 +14502,7 @@"feature_flag": "tasks"},"update-feature-flag": {- "description": "Update a feature flag by numeric ID (partial update: only the fields you include are changed). Use this for edits that have no dedicated tool, such as property filters, adding and removing release conditions, variant definitions, payloads, tags and the description.\n\nPrefer a dedicated tool whenever the request matches one. `feature-flag-enable`, `feature-flag-disable`, `feature-flag-archive` and `feature-flag-unarchive` each change one state field and send no `filters`. A targeting change someone else made between your read and your write is therefore not overwritten. Send `active` or `archived` here only when the same request also changes targeting or another field, so the whole edit lands in one write.\n\n`feature-flag-set-release-condition-rollout` changes one release condition's percentage and `feature-flag-roll-out-to-everyone` serves the flag to its whole audience. Both send no `filters` and both refuse the write when the flag changed after the version you read, so a concurrent edit cannot be lost. This tool sends no `version`, so it writes even when the flag changed after your read. It replaces the whole `filters` object with your copy of it. Use it for a rollout change only when those two tools cannot express it, such as changing the split between variants while leaving the audience alone.\n\nRollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters` replaces the whole object, so read the flag first and merge your change. When the flag targets groups, keep `type: \"group\"`, `group_type_index`, and `filters.aggregation_group_type_index` in what you send; if you omit them this tool restores them from the existing flag so group targeting is not silently converted to person targeting. When the flag's conditions don't all target the same thing (some target persons and others a group type, or they target different group types), set `aggregation_group_type_index` on every condition whenever you add, remove, reorder, or change the properties of conditions. Use null for persons. Otherwise this tool can't tell which target each condition keeps, and it refuses the update. Use `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at a future time instead, use `scheduled-changes-create`.",+ "description": "Update a feature flag by numeric ID (partial update: only the fields you include are changed). Use this for edits that have no dedicated tool, such as property filters, adding and removing release conditions, variant definitions, payloads, tags and the description.\n\nPrefer a dedicated tool whenever the request matches one. `feature-flag-enable`, `feature-flag-disable`, `feature-flag-archive` and `feature-flag-unarchive` each change one state field and send no `filters`. A targeting change someone else made between your read and your write is therefore not overwritten. Send `active` or `archived` here only when the same request also changes targeting or another field, so the whole edit lands in one write.\n\n`feature-flag-set-release-condition-rollout` changes one release condition's percentage and `feature-flag-roll-out-to-everyone` serves the flag to its whole audience. Both send no `filters` and both refuse the write when the flag changed after the version you read, so a concurrent edit cannot be lost. This tool sends no `version`, so it writes even when the flag changed after your read. It replaces the whole `filters` object with your copy of it. Use it for a rollout change only when those two tools cannot express it, such as changing the split between variants while leaving the audience alone.\n\nRollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters` replaces the whole object, so read the flag first and merge your change. Each release condition you read has a `condition_id`. Send it unchanged on every condition you keep, edit, or move, and leave it off a new condition. A `condition_id` belongs to the flag you read it from, so leave it off a condition copied from a different flag. Once any condition has a `condition_id`, a condition without one is treated as new. This tool uses the ID to restore each condition's property types and targeting, so a reorder, deletion, or edit keeps every condition on the persons or group type it targeted. If a `condition_id` matches no condition on the flag, the flag may have changed after your read, and the update is refused. Read the flag again and rebuild the update. When the flag targets groups, keep `type: \"group\"`, `group_type_index`, and `filters.aggregation_group_type_index` in what you send; if you omit them this tool restores them from the existing flag so group targeting is not silently converted to person targeting. When the flag's conditions don't all target the same thing (some target persons and others a group type, or they target different group types), set `aggregation_group_type_index` on every new condition. Use null for persons. If you send no `condition_id` values, set `aggregation_group_type_index` on every condition whenever you add, remove, reorder, or change the properties of conditions. Otherwise this tool can't tell which target each condition keeps, and it refuses the update. Use `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at a future time instead, use `scheduled-changes-create`.","category": "Feature flags","feature": "flags","summary": "Update feature flag",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 7862763957f8..0024e72616e5 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -15248,7 +15248,7 @@"feature_flag": "tasks"},"update-feature-flag": {- "description": "Update a feature flag by numeric ID (partial update: only the fields you include are changed). Use this for edits that have no dedicated tool, such as property filters, adding and removing release conditions, variant definitions, payloads, tags and the description.\n\nPrefer a dedicated tool whenever the request matches one. `feature-flag-enable`, `feature-flag-disable`, `feature-flag-archive` and `feature-flag-unarchive` each change one state field and send no `filters`. A targeting change someone else made between your read and your write is therefore not overwritten. Send `active` or `archived` here only when the same request also changes targeting or another field, so the whole edit lands in one write.\n\n`feature-flag-set-release-condition-rollout` changes one release condition's percentage and `feature-flag-roll-out-to-everyone` serves the flag to its whole audience. Both send no `filters` and both refuse the write when the flag changed after the version you read, so a concurrent edit cannot be lost. This tool sends no `version`, so it writes even when the flag changed after your read. It replaces the whole `filters` object with your copy of it. Use it for a rollout change only when those two tools cannot express it, such as changing the split between variants while leaving the audience alone.\n\nRollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters` replaces the whole object, so read the flag first and merge your change. When the flag targets groups, keep `type: \"group\"`, `group_type_index`, and `filters.aggregation_group_type_index` in what you send; if you omit them this tool restores them from the existing flag so group targeting is not silently converted to person targeting. When the flag's conditions don't all target the same thing (some target persons and others a group type, or they target different group types), set `aggregation_group_type_index` on every condition whenever you add, remove, reorder, or change the properties of conditions. Use null for persons. Otherwise this tool can't tell which target each condition keeps, and it refuses the update. Use `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at a future time instead, use `scheduled-changes-create`.",+ "description": "Update a feature flag by numeric ID (partial update: only the fields you include are changed). Use this for edits that have no dedicated tool, such as property filters, adding and removing release conditions, variant definitions, payloads, tags and the description.\n\nPrefer a dedicated tool whenever the request matches one. `feature-flag-enable`, `feature-flag-disable`, `feature-flag-archive` and `feature-flag-unarchive` each change one state field and send no `filters`. A targeting change someone else made between your read and your write is therefore not overwritten. Send `active` or `archived` here only when the same request also changes targeting or another field, so the whole edit lands in one write.\n\n`feature-flag-set-release-condition-rollout` changes one release condition's percentage and `feature-flag-roll-out-to-everyone` serves the flag to its whole audience. Both send no `filters` and both refuse the write when the flag changed after the version you read, so a concurrent edit cannot be lost. This tool sends no `version`, so it writes even when the flag changed after your read. It replaces the whole `filters` object with your copy of it. Use it for a rollout change only when those two tools cannot express it, such as changing the split between variants while leaving the audience alone.\n\nRollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters` replaces the whole object, so read the flag first and merge your change. Each release condition you read has a `condition_id`. Send it unchanged on every condition you keep, edit, or move, and leave it off a new condition. A `condition_id` belongs to the flag you read it from, so leave it off a condition copied from a different flag. Once any condition has a `condition_id`, a condition without one is treated as new. This tool uses the ID to restore each condition's property types and targeting, so a reorder, deletion, or edit keeps every condition on the persons or group type it targeted. If a `condition_id` matches no condition on the flag, the flag may have changed after your read, and the update is refused. Read the flag again and rebuild the update. When the flag targets groups, keep `type: \"group\"`, `group_type_index`, and `filters.aggregation_group_type_index` in what you send; if you omit them this tool restores them from the existing flag so group targeting is not silently converted to person targeting. When the flag's conditions don't all target the same thing (some target persons and others a group type, or they target different group types), set `aggregation_group_type_index` on every new condition. Use null for persons. If you send no `condition_id` values, set `aggregation_group_type_index` on every condition whenever you add, remove, reorder, or change the properties of conditions. Otherwise this tool can't tell which target each condition keeps, and it refuses the update. Use `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at a future time instead, use `scheduled-changes-create`.","category": "Feature flags","feature": "flags","summary": "Update feature flag",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex b75efdb6ae12..070a353b16d6 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -1865,6 +1865,486 @@},"required": ["id"]},+ "UpdateFeatureFlagFiltersSchema": {+ "type": "object",+ "properties": {+ "groups": {+ "description": "Release condition groups for the feature flag.",+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "properties": {+ "description": "Property conditions for this release condition group.",+ "type": "array",+ "items": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "key": {+ "type": "string",+ "description": "Property key used in this feature flag condition."+ },+ "type": {+ "description": "Property filter type. Set it on every property. Use `group` with `group_type_index` to filter on a group's properties.\n\n* `cohort` - cohort\n* `person` - person\n* `group` - group",+ "type": "string",+ "enum": ["cohort", "person", "group"]+ },+ "cohort_name": {+ "description": "Resolved cohort name for cohort-type filters.",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "group_type_index": {+ "description": "Group type index a `group` filter reads properties from. Defaults to the condition set's `aggregation_group_type_index`.",+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ },+ "value": {+ "description": "Comparison value for the property filter. Supports strings, numbers, booleans, and arrays."+ },+ "operator": {+ "type": "string",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte"+ ],+ "description": "Operator used to compare the property value.\n\n* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `starts_with` - starts_with\n* `not_starts_with` - not_starts_with\n* `ends_with` - ends_with\n* `not_ends_with` - not_ends_with\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `gte` - gte\n* `lt` - lt\n* `lte` - lte"+ }+ },+ "required": ["key", "value", "operator"]+ },+ {+ "type": "object",+ "properties": {+ "key": {+ "type": "string",+ "description": "Property key used in this feature flag condition."+ },+ "type": {+ "description": "Property filter type. Set it on every property. Use `group` with `group_type_index` to filter on a group's properties.\n\n* `cohort` - cohort\n* `person` - person\n* `group` - group",+ "type": "string",+ "enum": ["cohort", "person", "group"]+ },+ "cohort_name": {+ "description": "Resolved cohort name for cohort-type filters.",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "group_type_index": {+ "description": "Group type index a `group` filter reads properties from. Defaults to the condition set's `aggregation_group_type_index`.",+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ },+ "operator": {+ "type": "string",+ "enum": ["is_set", "is_not_set"],+ "description": "Existence operator.\n\n* `is_set` - is_set\n* `is_not_set` - is_not_set"+ },+ "value": {+ "description": "Optional value. Runtime behavior determines whether this is ignored."+ }+ },+ "required": ["key", "operator"]+ },+ {+ "type": "object",+ "properties": {+ "key": {+ "type": "string",+ "description": "Property key used in this feature flag condition."+ },+ "type": {+ "description": "Property filter type. Set it on every property. Use `group` with `group_type_index` to filter on a group's properties.\n\n* `cohort` - cohort\n* `person` - person\n* `group` - group",+ "type": "string",+ "enum": ["cohort", "person", "group"]+ },+ "cohort_name": {+ "description": "Resolved cohort name for cohort-type filters.",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "group_type_index": {+ "description": "Group type index a `group` filter reads properties from. Defaults to the condition set's `aggregation_group_type_index`.",+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ },+ "operator": {+ "type": "string",+ "enum": ["is_date_exact", "is_date_before", "is_date_after"],+ "description": "Date comparison operator.\n\n* `is_date_exact` - is_date_exact\n* `is_date_after` - is_date_after\n* `is_date_before` - is_date_before"+ },+ "value": {+ "type": "string",+ "description": "Date value in ISO format or relative date expression."+ }+ },+ "required": ["key", "operator", "value"]+ },+ {+ "type": "object",+ "properties": {+ "key": {+ "type": "string",+ "description": "Property key used in this feature flag condition."+ },+ "type": {+ "description": "Property filter type. Set it on every property. Use `group` with `group_type_index` to filter on a group's properties.\n\n* `cohort` - cohort\n* `person` - person\n* `group` - group",+ "type": "string",+ "enum": ["cohort", "person", "group"]+ },+ "cohort_name": {+ "description": "Resolved cohort name for cohort-type filters.",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "group_type_index": {+ "description": "Group type index a `group` filter reads properties from. Defaults to the condition set's `aggregation_group_type_index`.",+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ },+ "operator": {+ "type": "string",+ "enum": [+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_eq",+ "semver_neq",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard"+ ],+ "description": "Semantic version comparison operator.\n\n* `semver_gt` - semver_gt\n* `semver_gte` - semver_gte\n* `semver_lt` - semver_lt\n* `semver_lte` - semver_lte\n* `semver_eq` - semver_eq\n* `semver_neq` - semver_neq\n* `semver_tilde` - semver_tilde\n* `semver_caret` - semver_caret\n* `semver_wildcard` - semver_wildcard"+ },+ "value": {+ "type": "string",+ "description": "Semantic version string."+ }+ },+ "required": ["key", "operator", "value"]+ },+ {+ "type": "object",+ "properties": {+ "key": {+ "type": "string",+ "description": "Property key used in this feature flag condition."+ },+ "type": {+ "description": "Property filter type. Set it on every property. Use `group` with `group_type_index` to filter on a group's properties.\n\n* `cohort` - cohort\n* `person` - person\n* `group` - group",+ "type": "string",+ "enum": ["cohort", "person", "group"]+ },+ "cohort_name": {+ "description": "Resolved cohort name for cohort-type filters.",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "group_type_index": {+ "description": "Group type index a `group` filter reads properties from. Defaults to the condition set's `aggregation_group_type_index`.",+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ },+ "operator": {+ "type": "string",+ "enum": ["icontains_multi", "not_icontains_multi"],+ "description": "Multi-contains operator.\n\n* `icontains_multi` - icontains_multi\n* `not_icontains_multi` - not_icontains_multi"+ },+ "value": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "List of strings to evaluate against."+ }+ },+ "required": ["key", "operator", "value"]+ },+ {+ "type": "object",+ "properties": {+ "key": {+ "type": "string",+ "description": "Property key used in this feature flag condition."+ },+ "type": {+ "type": "string",+ "enum": ["cohort"],+ "description": "Cohort property type required for in/not_in operators.\n\n* `cohort` - cohort"+ },+ "cohort_name": {+ "description": "Resolved cohort name for cohort-type filters.",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "group_type_index": {+ "description": "Group type index a `group` filter reads properties from. Defaults to the condition set's `aggregation_group_type_index`.",+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ },+ "operator": {+ "type": "string",+ "enum": ["in", "not_in"],+ "description": "Membership operator for cohort properties.\n\n* `in` - in\n* `not_in` - not_in"+ },+ "value": {+ "description": "Cohort comparison value (single or list, depending on usage)."+ },+ "cohort_deleted": {+ "description": "Set to true in responses when the cohort is deleted or does not exist. The flag cannot evaluate this condition. Ignored on write.",+ "type": "boolean"+ },+ "cohort_missing": {+ "description": "Set to true in responses when no cohort with this id exists in the project, so it cannot be restored. `cohort_deleted` is also true. Absent for a soft-deleted cohort. Ignored on write.",+ "type": "boolean"+ }+ },+ "required": ["key", "type", "operator", "value"]+ },+ {+ "type": "object",+ "properties": {+ "key": {+ "type": "string",+ "description": "Property key used in this feature flag condition."+ },+ "type": {+ "type": "string",+ "enum": ["flag"],+ "description": "Flag property type required for flag dependency checks.\n\n* `flag` - flag"+ },+ "cohort_name": {+ "description": "Resolved cohort name for cohort-type filters.",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "group_type_index": {+ "description": "Group type index a `group` filter reads properties from. Defaults to the condition set's `aggregation_group_type_index`.",+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ },+ "operator": {+ "type": "string",+ "enum": ["flag_evaluates_to"],+ "description": "Operator for feature flag dependency evaluation.\n\n* `flag_evaluates_to` - flag_evaluates_to"+ },+ "value": {+ "description": "Value to compare flag evaluation against."+ }+ },+ "required": ["key", "type", "operator", "value"]+ }+ ]+ }+ },+ "rollout_percentage": {+ "description": "Rollout percentage for this release condition group.",+ "type": "number"+ },+ "variant": {+ "description": "Variant key override for multivariate flags.",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "aggregation_group_type_index": {+ "description": "Group type index for this condition set. None means person-level aggregation.",+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ },+ "condition_id": {+ "description": "The condition_id this condition had when you read the flag. Send it unchanged when you keep, edit, or move the condition. Leave it off a new condition or one copied from a different flag. The update is refused when no condition on the flag has this ID.",+ "type": "string"+ }+ }+ }+ },+ "multivariate": {+ "description": "Multivariate configuration for variant-based rollouts.",+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "variants": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "key": {+ "type": "string",+ "description": "Unique key for this variant."+ },+ "name": {+ "description": "Human-readable name for this variant.",+ "type": "string"+ },+ "rollout_percentage": {+ "type": "number",+ "description": "Variant rollout percentage."+ }+ },+ "required": ["key", "rollout_percentage"]+ },+ "description": "Variant definitions for multivariate feature flags."+ }+ },+ "required": ["variants"]+ },+ {+ "type": "null"+ }+ ]+ },+ "aggregation_group_type_index": {+ "description": "Group type index for group-based feature flags.",+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ },+ "payloads": {+ "description": "Optional payload values keyed by variant key.",+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {+ "type": "string"+ }+ },+ "feature_enrollment": {+ "description": "Whether this flag has early access feature enrollment enabled. When true, the flag is evaluated against the person property $feature_enrollment/{flag_key}.",+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "early_exit": {+ "default": false,+ "description": "When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.",+ "type": "boolean"+ }+ },+ "description": "Full release-condition object. It replaces the stored filters, so read the flag first and send every condition you want to keep. The tool description covers condition_id and group targeting."+ },"UsageMetricFiltersSchema": {"anyOf": [{diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex ec104e232b84..89f06eb49e15 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -6,6 +6,7 @@ import {aiObservabilityOfflineExperimentsUploadCreateBodyResultsMax,} from '../generated/ai_observability/api'import { BillingUsageRetrieveQueryParams } from '../generated/billing/api'+import { FeatureFlagsPartialUpdateBody } from '../generated/feature_flags/api'// Relative (not `@/`) imports: this module is loaded by the tsx schema-generation// script, and both modules are pure constants/functions — no `.md` imports to choke on.import { castStringToInt, normalizeParamAliases } from '../tools/cast-helpers'@@ -1322,3 +1323,27 @@ export const WorkflowActionEmailPatchSchema = z})}})++const FeatureFlagUpdateFilters = FeatureFlagsPartialUpdateBody().shape.filters.unwrap()+const FeatureFlagUpdateConditionGroup = FeatureFlagUpdateFilters.shape.groups.unwrap().element++export const UpdateFeatureFlagFiltersSchema = FeatureFlagUpdateFilters.extend({+ groups: z+ .array(+ FeatureFlagUpdateConditionGroup.extend({+ condition_id: z+ .string()+ .optional()+ .describe(+ 'The condition_id this condition had when you read the flag. Send it unchanged when you ' ++ 'keep, edit, or move the condition. Leave it off a new condition or one copied from a ' ++ 'different flag. The update is refused when no condition on the flag has this ID.'+ ),+ })+ )+ .optional()+ .describe(FeatureFlagUpdateFilters.shape.groups.description!),+}).describe(+ 'Full release-condition object. It replaces the stored filters, so read the flag first and send every ' ++ 'condition you want to keep. The tool description covers condition_id and group targeting.'+)diff --git a/services/mcp/src/tools/featureFlags/conditionIdHooks.ts b/services/mcp/src/tools/featureFlags/conditionIdHooks.tsnew file mode 100644index 000000000000..101ebe08e783--- /dev/null+++ b/services/mcp/src/tools/featureFlags/conditionIdHooks.ts@@ -0,0 +1,7 @@+import type { ToolHooks } from '@/tools/tool-hooks'++import { withConditionIds } from './conditionIds'++export default {+ afterResponse: (_context, _params, result) => withConditionIds(result),+} satisfies ToolHooks<unknown>diff --git a/services/mcp/src/tools/featureFlags/getDefinitionByKey.ts b/services/mcp/src/tools/featureFlags/getDefinitionByKey.tsindex 4961e1c4ef60..91947a53c820 100644--- a/services/mcp/src/tools/featureFlags/getDefinitionByKey.ts+++ b/services/mcp/src/tools/featureFlags/getDefinitionByKey.ts@@ -3,6 +3,7 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import { ToolInputValidationError } from '@/lib/errors'import { normalizeParamAliases } from '@/tools/cast-helpers'+import { withConditionIds } from '@/tools/featureFlags/conditionIds'import { resolveFlagsByKey } from '@/tools/featureFlags/resolveFlagsByKey'import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase } from '@/tools/types'@@ -86,7 +87,7 @@ const featureFlagGetDefinitionByKey = (): ToolBase<typeof schema, Result> => ({// The list row is already the full flag, so it's wrapped directly instead of// triggering a redundant fetch-by-id round trip.const flagWithUrl = await withPostHogUrl(context, flag, `/feature-flags/${flag.id}`)- return { ...flagWithUrl, found: true }+ return { ...withConditionIds(flagWithUrl), found: true }},})diff --git a/services/mcp/src/tools/featureFlags/preserveGroupTargeting.ts b/services/mcp/src/tools/featureFlags/preserveGroupTargeting.tsindex ed3b4834898d..ce5edf185fa4 100644--- a/services/mcp/src/tools/featureFlags/preserveGroupTargeting.ts+++ b/services/mcp/src/tools/featureFlags/preserveGroupTargeting.ts@@ -26,6 +26,15 @@* same payload. On a flag whose sets all aggregate the same way, a set that keeps its keys at its* index keeps its source even when other sets change.*+ * A group-aggregated set on an older flag can hold a group property on another group type than its+ * own. A deletion or a swap can pair a set with the wrong stored set. On such a flag the pairing+ * decides which group type that property keeps, and the set's group type when the agent echoes the+ * property. The merge therefore refuses a payload without IDs on such a flag unless each set repeats+ * the filters of the stored set at its index and no other stored set has the same filters. A payload+ * with IDs can drop the ID of a stored set that holds such a property. The merge refuses each set+ * without an ID that repeats the filters of such a stored set when no ID in the payload names that+ * stored set. As a new set, it would move the property to its own group type.+ ** A set's aggregation then decides its property types. A group-aggregated set restores a* person-aggregated type that its source holds for the key. A group-aggregated set with no source* looks the key up in every stored set instead when the stored sets all aggregate the same way, or@@ -47,8 +56,9 @@* On a flag whose stored sets all aggregate on persons, a set without a source compares its echo* against every stored set instead. An appended set also has no source.* check_property_types_match_aggregation in products/feature_flags/backend/filters_validation.py- * reports a group property in a person set and a person-aggregated property in a group set. The- * evaluator supports both shapes. The merge keeps them where the stored flag already has them.+ * reports a group property in a person set, a person-aggregated property in a group set, and a group+ * property on another group type than its set. The evaluator supports these shapes. The merge keeps+ * them where the stored flag already has them.** In either kind of set, the stored filters that decide a type narrow to the ones that match the* incoming operator and value, then to the ones with its operator. When the rest hold more than one@@ -331,6 +341,21 @@ function groupPersonSetsByFilters(existingSets: (ExistingSet | undefined)[]): Mareturn new Map([...byFilters].map(([filters, byTyping]) => [filters, [...byTyping.values()]]))}+/** A person-aggregated set does not count. The person-set rules in the module doc decide its group properties. */+function holdsCrossGroupProperty(existingSet: ExistingSet): boolean {+ return (+ existingSet.aggregation !== null &&+ [...existingSet.propsByKey.values()]+ .flat()+ .some(+ (prop) =>+ prop.type === 'group' &&+ isPresentGroupIndex(prop.group_type_index) &&+ prop.group_type_index !== existingSet.aggregation+ )+ )+}+function keepsKeys(incoming: FlagConditionGroup | undefined, existingSet: ExistingSet | undefined): boolean {const incomingKeys = isRecord(incoming) ? indexProperties(incoming.properties) : new Map()return hasSameKeySet(incomingKeys, existingSet?.propsByKey ?? new Map())@@ -374,14 +399,49 @@ function unambiguousPersonCandidates(return matching.some((candidate) => candidate.type === 'group') ? [] : matching}-type SourceAggregation = 'person' | 'group'+/**+ * A group property follows its set's group type, so a retarget moves it with the set. That holds for a+ * property with no index, which the evaluator reads on its set's group type, and for a property on the+ * group type its source aggregates on. Older flags can also hold a group property on another group type+ * than its set. The evaluator reads the property's own group type, so moving such a property would+ * change which group the filter reads. The property therefore keeps that index. A person-aggregated+ * source aggregates on no group type, so every group property with an index in it keeps that index.+ * Undefined means the stored filters on the key disagree and the agent sent no index. The caller then+ * returns the property as the agent sent it, because the API rejects an untyped property whatever+ * FEATURE_FLAG_FILTERS_ENFORCED_RULES holds. A typed group property without an index saves while that+ * setting leaves out `group_property_type_index_mismatch`, and the evaluator then reads it on the+ * set's group type.+ */+function groupTypeIndexFor(+ prop: FlagProperty,+ candidates: FlagProperty[] | undefined,+ sourceAggregation: ExistingSet['aggregation'] | undefined,+ setGroupTypeIndex: number+): number | undefined {+ const mergedIndex = (index: number | null | undefined): number =>+ sourceAggregation !== undefined && isPresentGroupIndex(index) && index !== sourceAggregation+ ? index+ : setGroupTypeIndex+ if (isPresentGroupIndex(prop.group_type_index)) {+ return mergedIndex(prop.group_type_index)+ }+ const storedGroupFilters = usableCandidates(candidates, (type) => type === 'group').map((stored) => ({+ ...stored,+ group_type_index: mergedIndex(stored.group_type_index),+ }))+ if (storedGroupFilters.length === 0) {+ return setGroupTypeIndex+ }+ return pickTyping(storedGroupFilters, prop)?.group_type_index ?? undefined+}+/** `sourceAggregation` is undefined when no source holds the key. */function mergeProperty(incoming: FlagProperty,candidates: FlagProperty[] | undefined,otherCandidates: FlagProperty[] | undefined,setGroupTypeIndex: number | undefined,- source: SourceAggregation | undefined+ sourceAggregation: ExistingSet['aggregation'] | undefined): FlagProperty {const out: FlagProperty = { ...incoming }@@ -401,10 +461,11 @@ function mergeProperty(// included. Any other candidate restores only a person-aggregated type, because// restoring `group` from it would name fields the agent never sent. Leaving the type// unset then makes the API report the property the agent actually sent.- const fromSource = source- ? usableCandidates(candidates, source === 'person' ? isPresentType : isPersonAggregatedType)+ const hasSource = sourceAggregation !== undefined+ const fromSource = hasSource+ ? usableCandidates(candidates, sourceAggregation === null ? isPresentType : isPersonAggregatedType): []- const others = source ? otherCandidates : unambiguousPersonCandidates(otherCandidates, out)+ const others = hasSource ? otherCandidates : unambiguousPersonCandidates(otherCandidates, out)const usable = fromSource.length > 0 ? fromSource : usableCandidates(others, isPersonAggregatedType)const typing = pickTyping(usable, out)if (typing) {@@ -413,10 +474,12 @@ function mergeProperty(}}- // A group property carries the index its own set aggregates on. The set's index therefore- // replaces an index the agent echoed back from the group type it retargets away from.if (out.type === 'group' && isPresentGroupIndex(setGroupTypeIndex)) {- out.group_type_index = setGroupTypeIndex+ const groupTypeIndex = groupTypeIndexFor(out, candidates, sourceAggregation, setGroupTypeIndex)+ if (groupTypeIndex === undefined) {+ return incoming+ }+ out.group_type_index = groupTypeIndex}return out@@ -427,8 +490,8 @@ type MergeConditionOptions = {payloadChangesFlagAggregation: boolean/** This set never gains group aggregation. See isPinnedToPerson. */pinnedToPerson: boolean- /** Property maps of the stored person sets that this set may come from. */- personSetProps: (Map<string, FlagProperty[]> | undefined)[]+ /** Property maps of the stored sets that this set may come from. */+ storedSetProps: (Map<string, FlagProperty[]> | undefined)[]}function holdsGroupProperty(propsByKey: Map<string, FlagProperty[]> | undefined, prop: FlagProperty): boolean {@@ -442,14 +505,14 @@ function holdsGroupProperty(propsByKey: Map<string, FlagProperty[]> | undefined,function explicitGroupPropertyIndex(group: FlagConditionGroup,- personSetProps: (Map<string, FlagProperty[]> | undefined)[]+ storedSetProps: (Map<string, FlagProperty[]> | undefined)[]): number | undefined {const properties = Array.isArray(group.properties) ? group.properties : []const typed = properties.filter((prop): prop is FlagProperty & { group_type_index: number } =>prop?.type === 'group' && isPresentGroupIndex(prop.group_type_index))- if (personSetProps.some((propsByKey) => typed.every((prop) => holdsGroupProperty(propsByKey, prop)))) {+ if (storedSetProps.some((propsByKey) => typed.every((prop) => holdsGroupProperty(propsByKey, prop)))) {return undefined}const unique = [...new Set(typed.map((prop) => prop.group_type_index))]@@ -470,18 +533,19 @@ function resolveSetAggregation(out.aggregation_group_type_index = null}- const { pinnedToPerson, payloadChangesFlagAggregation, personSetProps } = options+ const { pinnedToPerson, payloadChangesFlagAggregation, storedSetProps } = options// Fill only when the key is absent. An explicit null means person aggregation. A payload// that changes the flag level already decides this set, the same way the API distributes// the flag level into every set that sends no index of its own. A group property that the// agent typed with an index names the group type of its own set. A retarget that the agent// sends only on the property therefore survives. A set whose typed group properties all- // repeat ones that a single map in personSetProps holds names no group type, because the- // stored person-aggregated set filters on them without aggregating on their group type.+ // repeat ones that a single map in storedSetProps holds names no group type, because they echo+ // stored filters. A person-aggregated set filters on such properties without aggregating on+ // their group type. A group-aggregated source can hold them on another group type than its own.if (!pinnedToPerson && !payloadChangesFlagAggregation && !hasKey(out, 'aggregation_group_type_index')) {const restored =- explicitGroupPropertyIndex(incoming, personSetProps) ?? sourceSet?.group.aggregation_group_type_index+ explicitGroupPropertyIndex(incoming, storedSetProps) ?? sourceSet?.group.aggregation_group_type_indexif (isPresentGroupIndex(restored)) {out.aggregation_group_type_index = restored}@@ -498,7 +562,6 @@ function typeSetProperties(setGroupTypeIndex: number | undefined,matchedSets: ExistingSet[]): FlagConditionGroup {- const source: SourceAggregation | undefined = sourceSet && (sourceSet.aggregation === null ? 'person' : 'group')const out: FlagConditionGroup = { ...group }if (Array.isArray(out.properties)) {out.properties = out.properties.map((prop) => {@@ -518,20 +581,20 @@ function typeSetProperties(sourceHoldsKey ? candidates : fallbackCandidatesByKey?.get(key),crossSetPropsByKey.get(key),setGroupTypeIndex,- sourceHoldsKey ? source : undefined+ sourceHoldsKey ? sourceSet?.aggregation : undefined)}// The set either moved from one of the matched sets or copies its filters in place. Each// reading types the property from a different person set. Only a type that every reading// gives is safe.- const fromSource = mergeProperty(prop, candidates, undefined, setGroupTypeIndex, 'person')+ const fromSource = mergeProperty(prop, candidates, undefined, setGroupTypeIndex, sourceSet?.aggregation)const allAgree = matchedSets.every((matched) => {const fromMatched = mergeProperty(prop,matched.propsByKey.get(key),undefined,setGroupTypeIndex,- 'person'+ matched.aggregation)return hasSameTypeAndGroupIndex(fromMatched, fromSource)})@@ -553,7 +616,9 @@ function unresolvedAggregationMessage(unresolved: number[]): string {'group type, or they target different group types. This update adds, removes, or reorders conditions, ' +"or changes the properties they filter on, so the tool can't tell which target each condition should keep. " +`Set aggregation_group_type_index on each of these conditions: ${paths}. ` +- 'Use a group type index to target that group type, or null to target persons. Then send the update again.'+ 'Use a group type index to target that group type, or null to target persons. Alternatively, send the ' ++ 'condition_id from the read on each condition that came from the flag, and set ' ++ 'aggregation_group_type_index only on new conditions. Then send the update again.')}@@ -562,13 +627,27 @@ function staleConditionIdMessage(stale: number[]): string {return (`The condition_id on ${paths} matches no condition on the flag. ` +'A condition_id only matches conditions on the flag you read it from. If you copied this condition ' +- 'from another flag or an experiment, remove its condition_id and send it as a new condition. ' ++ 'from a different flag, remove its condition_id and send it as a new condition. ' +'Otherwise the flag may have changed after you read it. Read the flag again, then build the update ' +'from its current conditions and their condition_id values.')}+function crossGroupPropertyMessage(unpaired: number[]): string {+ const paths = groupPaths(unpaired)+ return (+ "At least one of this flag's conditions filters on a group property of a group type that the condition " ++ "doesn't target. The flag checks each such property on the property's own group type. This update " ++ "changes, adds, removes, or reorders conditions without condition_id, so the tool can't tell which " ++ `stored condition these come from: ${paths}. It needs that to keep each property on its group type. ` ++ 'Read the flag with feature-flag-get-definition or feature-flag-get-definition-by-key to get each ' ++ "condition's condition_id. Send it on each condition that came from the flag, and leave it off new " ++ 'conditions. Then send the update again.'+ )+}+function sourcesByConditionId(+ incomingGroups: FlagConditionGroup[],conditionIds: (string | undefined)[],existingSets: (ExistingSet | undefined)[],existingFlagGroupIndex: number | undefined@@ -589,6 +668,22 @@ function sourcesByConditionId(fields: ['filters.groups.N.condition_id:stale_condition_id'],})}+ const sentIds = new Set(conditionIds)+ const unnamedCrossGroupSets = [...storedById].flatMap(([id, existingSet]) =>+ !sentIds.has(id) && holdsCrossGroupProperty(existingSet) ? [existingSet] : []+ )+ const lostIds = incomingGroups.flatMap((group, index) =>+ isRecord(group) &&+ conditionIds[index] === undefined &&+ unnamedCrossGroupSets.some((existingSet) => keepsFilters(group, existingSet))+ ? [index]+ : []+ )+ if (lostIds.length > 0) {+ throw new ToolInputValidationError(crossGroupPropertyMessage(lostIds), {+ fields: ['filters.groups.N.condition_id:cross_group_property'],+ })+ }return conditionIds.map((id) => (id === undefined ? undefined : storedById.get(id)))}@@ -641,6 +736,23 @@ function matchSetsByPositionAndContent().map((sameTyping) => sameTyping.set)})+ if (existingSets.some((existingSet) => existingSet && holdsCrossGroupProperty(existingSet))) {+ const signatures = existingSets.map((existingSet) => existingSet && filterSignature(existingSet.propsByKey))+ const unpaired = incomingGroups.flatMap((group, index) => {+ const sourceSet = sourceSets[index]+ const paired =+ !isRecord(group) ||+ (!!sourceSet &&+ signatures.filter((signature) => signature === signatures[index]).length === 1 &&+ keepsFilters(group, sourceSet))+ return paired ? [] : [index]+ })+ if (unpaired.length > 0) {+ throw new ToolInputValidationError(crossGroupPropertyMessage(unpaired), {+ fields: ['filters.groups.N.condition_id:cross_group_property'],+ })+ }+ }return { sourceSets, matchedPersonSets }}@@ -649,8 +761,9 @@ function matchSetsByPositionAndContent(* values always win, `null` included, and only missing `type`, `group_type_index`, and* `aggregation_group_type_index` keys are filled from the existing flag. The one exception* is a group property's `group_type_index`, which follows the index its own condition set- * aggregates on. Any other index contradicts the set. The API reports that contradiction as- * `group_property_type_index_mismatch`.+ * aggregates on, so a retarget moves the property with its set. A property whose sent or stored+ * index names a group type other than the one its source aggregates on keeps that index (see+ * groupTypeIndexFor). The API reports that contradiction as `group_property_type_index_mismatch`.*/export function preserveGroupTargetingFilters(existing: FlagFilters | null | undefined,@@ -707,15 +820,14 @@ export function preserveGroupTargetingFilters(const aggregatesOnPersonsOnly = storedAggregations.size === 1 && storedAggregations.has(null)const { sourceSets, matchedPersonSets }: SetSources = carriesConditionIds? {- sourceSets: sourcesByConditionId(conditionIds, existingSets, existingFlagGroupIndex),+ sourceSets: sourcesByConditionId(result.groups, conditionIds, existingSets, existingFlagGroupIndex),matchedPersonSets: [],}: matchSetsByPositionAndContent(result.groups, existingSets, mixedAggregation)- const personSources = sourceSets.map((sourceSet) => (sourceSet?.aggregation === null ? sourceSet : undefined))- const personSetPropsFor = (index: number): (Map<string, FlagProperty[]> | undefined)[] =>+ const storedSetPropsFor = (index: number): (Map<string, FlagProperty[]> | undefined)[] =>sourceSets[index]- ? [personSources[index], ...(matchedPersonSets[index] ?? [])].map((personSet) => personSet?.propsByKey)+ ? [sourceSets[index], ...(matchedPersonSets[index] ?? [])].map((storedSet) => storedSet?.propsByKey): [aggregatesOnPersonsOnly ? crossSetPropsByKey : undefined]const resolvedGroups = result.groups.map((group, index) =>@@ -723,7 +835,7 @@ export function preserveGroupTargetingFilters(? resolveSetAggregation(group, sourceSets[index], {payloadChangesFlagAggregation,pinnedToPerson: pinnedToPerson[index] ?? false,- personSetProps: personSetPropsFor(index),+ storedSetProps: storedSetPropsFor(index),}): group)diff --git a/services/mcp/src/tools/featureFlags/updateFeatureFlagHooks.ts b/services/mcp/src/tools/featureFlags/updateFeatureFlagHooks.tsindex 87e903b862ab..07c0b9fcbcf4 100644--- a/services/mcp/src/tools/featureFlags/updateFeatureFlagHooks.ts+++ b/services/mcp/src/tools/featureFlags/updateFeatureFlagHooks.ts@@ -1,15 +1,19 @@/*** Hooks for the generated `update-feature-flag` tool. They intercept only `filters`, to- * preserve group targeting (PostHog/posthog#46501) and to explain a rejected property type,- * and leave everything else to the generated handler. Re-sync is needed if the `filters`- * param shape changes, or if the API changes the `groups[i].properties[j].type: ` prefix- * of its property type rejection.+ * preserve group targeting (PostHog/posthog#46501) and to explain a rejected property type or+ * group type, and leave everything else to the generated handler. Re-sync is needed if the+ * `filters` param shape changes, if the API changes the `groups[i].properties[j].type: ` prefix+ * of its property type rejection, or if it changes the code or the `groups[i].properties[j]: `+ * prefix of its group type mismatch rejection.+ * The merge removes each `condition_id` before the PATCH, because the API does not store it.+ * afterResponse adds a `condition_id` to each condition in the returned flag.*/import type { Schemas } from '@/api/generated'import { PostHogValidationError } from '@/lib/errors'import type { ToolHooks } from '@/tools/tool-hooks'import type { Context } from '@/tools/types'+import conditionIdHooks from './conditionIdHooks'import { preserveGroupTargetingFilters, type FlagFilters } from './preserveGroupTargeting'type UpdateParams = {@@ -18,9 +22,11 @@ type UpdateParams = {[key: string]: unknown}-// Matches both the API's serde guard ("invalid property type") and its structural tier-// ("This field is required.", "... is not a valid choice."), which differ only after the path.-const PROPERTY_TYPE_REJECTION = /^(groups\[(\d+)\]\.properties\[(\d+)\])\.type: /+// The `.type` form matches both the API's serde guard ("invalid property type") and its structural+// tier ("This field is required.", "... is not a valid choice."), which differ only after the path.+const PROPERTY_REJECTION = /^(groups\[(\d+)\]\.properties\[(\d+)\])(\.type)?: /++const GROUP_TYPE_MISMATCH = 'cross_field.group_property_type_index_mismatch'async function beforeRequest<T extends UpdateParams>(context: Context, params: T): Promise<T> {if (params.filters === undefined) {@@ -40,27 +46,32 @@ async function beforeRequest<T extends UpdateParams>(context: Context, params: Treturn { ...params, filters: mergedFilters }}-// The API reports a rejected property type by path only. This adds the key from the sent filters-// and the recovery step, whether `beforeRequest` left the type unset or the agent sent a bad one.-// The rewrite keeps the PostHogValidationError class for two reasons. `handleToolError` returns+// The API reports a rejected property type or group type by path only. This adds the key from the+// sent filters and the recovery step, whether `beforeRequest` restored the value or the agent sent+// it. The rewrite keeps the PostHogValidationError class for two reasons. `handleToolError` returns// that class's message to the agent. Telemetry records only its code and attr, so the property// key stays out of analytics.function onError(_context: Context, params: UpdateParams, error: unknown): never {if (!(error instanceof PostHogValidationError) || error.method !== 'PATCH' || error.attr !== 'filters') {throw error}- const match = PROPERTY_TYPE_REJECTION.exec(error.detail)+ const match = PROPERTY_REJECTION.exec(error.detail)if (!match) {throw error}- const [, path, groupIndex, propertyIndex] = match+ const [, path, groupIndex, propertyIndex, typeField] = match+ const recoveryStep = typeField+ ? propertyTypeRecoveryStep+ : error.code === GROUP_TYPE_MISMATCH+ ? groupTypeRecoveryStep+ : undefinedconst key: unknown = params.filters?.groups?.[Number(groupIndex)]?.properties?.[Number(propertyIndex)]?.key- if (typeof key !== 'string') {+ if (!recoveryStep || typeof key !== 'string') {throw error}throw new PostHogValidationError({...error,- detail: `${error.detail}\n\n${propertyTypeRecoveryStep(`filters.${path}`, key)}`,+ detail: `${error.detail}\n\n${recoveryStep(`filters.${path}`, key)}`,})}@@ -76,4 +87,18 @@ function propertyTypeRecoveryStep(path: string, key: string): string {)}-export default { beforeRequest, onError } satisfies ToolHooks<UpdateParams>+function groupTypeRecoveryStep(path: string, key: string): string {+ return (+ `The group property at ${path} (key ${JSON.stringify(key)}) is on a different group type than its condition aggregates on. ` ++ `If the flag you read already has it this way, the flag checks this property on the property's own group type. ` ++ `Changing the property's \`group_type_index\` or the condition's \`aggregation_group_type_index\` to make them match ` ++ `changes which group the flag checks, so don't pick one yourself. ` ++ `Ask the user which group type the condition should target, then set both to that group type's index.`+ )+}++export default {+ ...conditionIdHooks,+ beforeRequest,+ onError,+} satisfies ToolHooks<UpdateParams>diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.tsindex 655256703789..bdec76234877 100644--- a/services/mcp/src/tools/generated/feature_flags.ts+++ b/services/mcp/src/tools/generated/feature_flags.ts@@ -4,8 +4,14 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import * as orvalSchemas from '@/generated/feature_flags/api'import { withUiApp } from '@/resources/ui-apps'-import { validateDistinctIdPersonIdExclusive } from '@/schema/tool-inputs'+import { UpdateFeatureFlagFiltersSchema, validateDistinctIdPersonIdExclusive } from '@/schema/tool-inputs'import { castStringToInt, normalizeParamAliases } from '@/tools/cast-helpers'+import hooks_createFeatureFlag from '@/tools/featureFlags/conditionIdHooks'+import hooks_deleteFeatureFlag from '@/tools/featureFlags/conditionIdHooks'+import hooks_featureFlagGetDefinition from '@/tools/featureFlags/conditionIdHooks'+import hooks_featureFlagRollOutToEveryone from '@/tools/featureFlags/conditionIdHooks'+import hooks_featureFlagSetReleaseConditionRollout from '@/tools/featureFlags/conditionIdHooks'+import hooks_featureFlagsMyFlagsRetrieve from '@/tools/featureFlags/conditionIdHooks'import hooks_updateFeatureFlag from '@/tools/featureFlags/updateFeatureFlagHooks'import { transformRequestBody, withToolHooks } from '@/tools/tool-hooks'import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'@@ -35,46 +41,49 @@ const createFeatureFlag = (): ToolBase<> => ({name: 'create-feature-flag',schema: CreateFeatureFlagSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof CreateFeatureFlagSchema>>) => {- const projectId = await context.stateManager.getProjectId()- const body: Record<string, unknown> = {}- if (params.key !== undefined) {- body['key'] = params.key- }- if (params.name !== undefined) {- body['name'] = params.name- }- if (params.filters !== undefined) {- body['filters'] = params.filters- }- if (params.active !== undefined) {- body['active'] = params.active- }- if (params.tags !== undefined) {- body['tags'] = params.tags- }- if (params.evaluation_contexts !== undefined) {- body['evaluation_contexts'] = params.evaluation_contexts- }- if (params.is_remote_configuration !== undefined) {- body['is_remote_configuration'] = params.is_remote_configuration- }- if (params.ensure_experience_continuity !== undefined) {- body['ensure_experience_continuity'] = params.ensure_experience_continuity- }- if (params.evaluation_runtime !== undefined) {- body['evaluation_runtime'] = params.evaluation_runtime- }- if (params.bucketing_identifier !== undefined) {- body['bucketing_identifier'] = params.bucketing_identifier+ handler: withToolHooks(+ hooks_createFeatureFlag,+ async (context: Context, params: z.infer<ReturnType<typeof CreateFeatureFlagSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.key !== undefined) {+ body['key'] = params.key+ }+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.filters !== undefined) {+ body['filters'] = params.filters+ }+ if (params.active !== undefined) {+ body['active'] = params.active+ }+ if (params.tags !== undefined) {+ body['tags'] = params.tags+ }+ if (params.evaluation_contexts !== undefined) {+ body['evaluation_contexts'] = params.evaluation_contexts+ }+ if (params.is_remote_configuration !== undefined) {+ body['is_remote_configuration'] = params.is_remote_configuration+ }+ if (params.ensure_experience_continuity !== undefined) {+ body['ensure_experience_continuity'] = params.ensure_experience_continuity+ }+ if (params.evaluation_runtime !== undefined) {+ body['evaluation_runtime'] = params.evaluation_runtime+ }+ if (params.bucketing_identifier !== undefined) {+ body['bucketing_identifier'] = params.bucketing_identifier+ }+ const result = await context.api.request<Schemas.FeatureFlag>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/`,+ body: await transformRequestBody(hooks_createFeatureFlag, context, params, body),+ })+ return await withPostHogUrl(context, result, `/feature-flags/${result.id}`)}- const result = await context.api.request<Schemas.FeatureFlag>({- method: 'POST',- path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/`,- body,- })- return await withPostHogUrl(context, result, `/feature-flags/${result.id}`)- },+ ),})const DeleteFeatureFlagSchema = () => {@@ -90,15 +99,18 @@ const DeleteFeatureFlagSchema = () => {const deleteFeatureFlag = (): ToolBase<ReturnType<typeof DeleteFeatureFlagSchema>, Schemas.FeatureFlag> => ({name: 'delete-feature-flag',schema: DeleteFeatureFlagSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof DeleteFeatureFlagSchema>>) => {- const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<Schemas.FeatureFlag>({- method: 'PATCH',- path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/`,- body: { deleted: true },- })- return result- },+ handler: withToolHooks(+ hooks_deleteFeatureFlag,+ async (context: Context, params: z.infer<ReturnType<typeof DeleteFeatureFlagSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.FeatureFlag>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/`,+ body: { deleted: true },+ })+ return result+ }+ ),})const FeatureFlagArchiveSchema = () => {@@ -290,14 +302,17 @@ const featureFlagGetDefinition = (): ToolBase<> => ({name: 'feature-flag-get-definition',schema: FeatureFlagGetDefinitionSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof FeatureFlagGetDefinitionSchema>>) => {- const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<Schemas.FeatureFlag>({- method: 'GET',- path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/`,- })- return await withPostHogUrl(context, result, `/feature-flags/${result.id}`)- },+ handler: withToolHooks(+ hooks_featureFlagGetDefinition,+ async (context: Context, params: z.infer<ReturnType<typeof FeatureFlagGetDefinitionSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.FeatureFlag>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/`,+ })+ return await withPostHogUrl(context, result, `/feature-flags/${result.id}`)+ }+ ),})const FeatureFlagRollOutToEveryoneSchema = () => {@@ -317,31 +332,34 @@ const featureFlagRollOutToEveryone = (): ToolBase<> => ({name: 'feature-flag-roll-out-to-everyone',schema: FeatureFlagRollOutToEveryoneSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof FeatureFlagRollOutToEveryoneSchema>>) => {- const projectId = await context.stateManager.getProjectId()- const body: Record<string, unknown> = {}- if (params.version !== undefined) {- body['version'] = params.version- }- if (params.variant_key !== undefined) {- body['variant_key'] = params.variant_key+ handler: withToolHooks(+ hooks_featureFlagRollOutToEveryone,+ async (context: Context, params: z.infer<ReturnType<typeof FeatureFlagRollOutToEveryoneSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.version !== undefined) {+ body['version'] = params.version+ }+ if (params.variant_key !== undefined) {+ body['variant_key'] = params.variant_key+ }+ const result = await context.api.request<Schemas.FeatureFlag>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/roll_out_to_everyone/`,+ body: await transformRequestBody(hooks_featureFlagRollOutToEveryone, context, params, body),+ })+ const filtered = pickResponseFields(result, [+ 'id',+ 'key',+ 'active',+ 'archived',+ 'status',+ 'version',+ 'filters',+ ]) as typeof result+ return await withPostHogUrl(context, filtered, `/feature-flags/${filtered.id}`)}- const result = await context.api.request<Schemas.FeatureFlag>({- method: 'POST',- path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/roll_out_to_everyone/`,- body,- })- const filtered = pickResponseFields(result, [- 'id',- 'key',- 'active',- 'archived',- 'status',- 'version',- 'filters',- ]) as typeof result- return await withPostHogUrl(context, filtered, `/feature-flags/${filtered.id}`)- },+ ),})const FeatureFlagSetReleaseConditionRolloutSchema = () => {@@ -365,37 +383,37 @@ const featureFlagSetReleaseConditionRollout = (): ToolBase<> => ({name: 'feature-flag-set-release-condition-rollout',schema: FeatureFlagSetReleaseConditionRolloutSchema(),- handler: async (- context: Context,- params: z.infer<ReturnType<typeof FeatureFlagSetReleaseConditionRolloutSchema>>- ) => {- const projectId = await context.stateManager.getProjectId()- const body: Record<string, unknown> = {}- if (params.condition_index !== undefined) {- body['condition_index'] = params.condition_index- }- if (params.rollout_percentage !== undefined) {- body['rollout_percentage'] = params.rollout_percentage- }- if (params.version !== undefined) {- body['version'] = params.version+ handler: withToolHooks(+ hooks_featureFlagSetReleaseConditionRollout,+ async (context: Context, params: z.infer<ReturnType<typeof FeatureFlagSetReleaseConditionRolloutSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.condition_index !== undefined) {+ body['condition_index'] = params.condition_index+ }+ if (params.rollout_percentage !== undefined) {+ body['rollout_percentage'] = params.rollout_percentage+ }+ if (params.version !== undefined) {+ body['version'] = params.version+ }+ const result = await context.api.request<Schemas.FeatureFlag>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/set_release_condition_rollout/`,+ body: await transformRequestBody(hooks_featureFlagSetReleaseConditionRollout, context, params, body),+ })+ const filtered = pickResponseFields(result, [+ 'id',+ 'key',+ 'active',+ 'archived',+ 'status',+ 'version',+ 'filters',+ ]) as typeof result+ return await withPostHogUrl(context, filtered, `/feature-flags/${filtered.id}`)}- const result = await context.api.request<Schemas.FeatureFlag>({- method: 'POST',- path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/set_release_condition_rollout/`,- body,- })- const filtered = pickResponseFields(result, [- 'id',- 'key',- 'active',- 'archived',- 'status',- 'version',- 'filters',- ]) as typeof result- return await withPostHogUrl(context, filtered, `/feature-flags/${filtered.id}`)- },+ ),})const FeatureFlagUnarchiveSchema = () => {@@ -691,18 +709,21 @@ const featureFlagsMyFlagsRetrieve = (): ToolBase<> => ({name: 'feature-flags-my-flags-retrieve',schema: FeatureFlagsMyFlagsRetrieveSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof FeatureFlagsMyFlagsRetrieveSchema>>) => {- const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<Schemas.MyFlagsResponse[]>({- method: 'GET',- path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/my_flags/`,- query: {- flag_keys: params.flag_keys,- groups: params.groups,- },- })- return await withPostHogUrl(context, result, '/feature-flags')- },+ handler: withToolHooks(+ hooks_featureFlagsMyFlagsRetrieve,+ async (context: Context, params: z.infer<ReturnType<typeof FeatureFlagsMyFlagsRetrieveSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.MyFlagsResponse[]>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/my_flags/`,+ query: {+ flag_keys: params.flag_keys,+ groups: params.groups,+ },+ })+ return await withPostHogUrl(context, result, '/feature-flags')+ }+ ),})const FeatureFlagsStatusRetrieveSchema = () => {@@ -982,9 +1003,7 @@ const UpdateFeatureFlagSchema = () => {.extend(FeatureFlagsPartialUpdateBody.shape).extend({id: z.preprocess(castStringToInt, FeatureFlagsPartialUpdateParams.shape['id']),- filters: FeatureFlagsPartialUpdateBody.shape['filters'].describe(- 'Full release-condition object (replaces filters at the API). For group flags set aggregation_group_type_index and property type "group" + group_type_index. Omitted type / group_type_index / aggregation_group_type_index are filled from the existing flag to prevent silent person demotion (see #46501). When conditions don\'t all target the same thing (persons and a group type, or different group types) and you add, remove, reorder, or change the properties of conditions, set aggregation_group_type_index on each condition (null for persons), or the update is refused.'- ),+ filters: UpdateFeatureFlagFiltersSchema.optional(),is_remote_configuration: FeatureFlagsPartialUpdateBody.shape['is_remote_configuration'].describe('Whether this flag delivers a payload instead of gating a feature (Remote Config mode). When true, set the delivered payload through the `filters` param under `filters.payloads.true` as a JSON-encoded string. There is no dedicated payload parameter.'),diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.jsonindex a0a52bda37b8..21c63afdcb97 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json@@ -54,7 +54,7 @@"description": "Where this flag is allowed to evaluate — `server` (server-side SDKs only), `client` (client-side SDKs only), or `all` (both). Defaults to `all`."},"filters": {- "description": "Full release-condition object (replaces filters at the API). For group flags set aggregation_group_type_index and property type \"group\" + group_type_index. Omitted type / group_type_index / aggregation_group_type_index are filled from the existing flag to prevent silent person demotion (see #46501). When conditions don't all target the same thing (persons and a group type, or different group types) and you add, remove, reorder, or change the properties of conditions, set aggregation_group_type_index on each condition (null for persons), or the update is refused.",+ "description": "Full release-condition object. It replaces the stored filters, so read the flag first and send every condition you want to keep. The tool description covers condition_id and group targeting.","properties": {"aggregation_group_type_index": {"anyOf": [@@ -98,6 +98,10 @@],"description": "Group type index for this condition set. None means person-level aggregation."},+ "condition_id": {+ "description": "The condition_id this condition had when you read the flag. Send it unchanged when you keep, edit, or move the condition. Leave it off a new condition or one copied from a different flag. The update is refused when no condition on the flag has this ID.",+ "type": "string"+ },"properties": {"description": "Property conditions for this release condition group.","items": {diff --git a/services/mcp/tests/unit/condition-ids.test.ts b/services/mcp/tests/unit/condition-ids.test.tsindex 8fef17da00fb..6009ff464f6b 100644--- a/services/mcp/tests/unit/condition-ids.test.ts+++ b/services/mcp/tests/unit/condition-ids.test.ts@@ -1,12 +1,14 @@-import { describe, expect, it } from 'vitest'+import { describe, expect, it, vi } from 'vitest'import { isRecord } from '@/lib/plain-object'+import { getToolByName } from '@/shared/test-utils'import { withConditionIds } from '@/tools/featureFlags/conditionIds'import {type FlagConditionGroup,type FlagFilters,preserveGroupTargetingFilters,} from '@/tools/featureFlags/preserveGroupTargeting'+import type { Context } from '@/tools/types'const planOn = (group_type_index: number, value: string): FlagConditionGroup => ({properties: [{ key: 'plan', type: 'group', group_type_index, operator: 'exact', value }],@@ -119,6 +121,47 @@ function withoutConditionIds(value: unknown): unknown {return JSON.parse(JSON.stringify(value, (key, nested) => (key === 'condition_id' ? undefined : nested)))}+function contextReturning(responses: unknown[]): Context {+ const request = vi.fn()+ for (const response of responses) {+ request.mockResolvedValueOnce(response)+ }+ return {+ api: { request, getProjectBaseUrl: (projectId: string) => `https://us.posthog.com/project/${projectId}` },+ stateManager: { getProjectId: vi.fn().mockResolvedValue('42') },+ } as unknown as Context+}++// feature-flag-get-all, feature-flag-enable, feature-flag-disable, feature-flag-archive, and+// feature-flag-unarchive keep no `filters` in their responses, so they are not listed.+const CONDITION_TOOLS: { tool: string; params: Record<string, unknown>; responses: unknown[] }[] = [+ { tool: 'create-feature-flag', params: { key: 'flag-9', name: 'Flag 9' }, responses: [flag(9)] },+ { tool: 'delete-feature-flag', params: { id: 9 }, responses: [{ ...flag(9), deleted: true }] },+ { tool: 'feature-flag-get-definition', params: { id: 9 }, responses: [flag(9)] },+ {+ tool: 'feature-flag-get-definition-by-key',+ params: { key: 'flag-9' },+ responses: [{ results: [flag(9)] }],+ },+ { tool: 'feature-flag-roll-out-to-everyone', params: { id: 9, version: 3 }, responses: [flag(9)] },+ {+ tool: 'feature-flag-set-release-condition-rollout',+ params: { id: 9, condition_index: 0, rollout_percentage: 25, version: 3 },+ responses: [flag(9)],+ },+ {+ tool: 'feature-flags-my-flags-retrieve',+ params: {},+ responses: [+ [+ { feature_flag: flag(9), value: true },+ { feature_flag: flag(10), value: 'test' },+ ],+ ],+ },+ { tool: 'update-feature-flag', params: { id: 9, name: 'Renamed' }, responses: [flag(9)] },+]+describe('condition ids', () => {it('gives the same ID to one stored condition however the API renders it', () => {const stored = {@@ -212,6 +255,14 @@ describe('condition ids', () => {expect(withoutConditionIds(result)).toEqual(withoutConditionIds(value))})+ it.each(CONDITION_TOOLS)('$tool returns each condition with its ID', async ({ tool, params, responses }) => {+ const expected = conditionsIn(responses.at(-1)).map((group) => idOnRead(group))++ const result = await getToolByName(tool).handler(contextReturning(responses), params)++ expect(conditionsIn(result).map((group) => group.condition_id)).toEqual(expected)+ })+it.each<MergeRow>([{name: 'two person sets on different group types trade places',@@ -358,6 +409,28 @@ describe('condition ids', () => {[null, ['group', 0]],],},+ {+ name: 'a group set changes the value of a property on another group type',+ flagLevel: 0,+ stored: [planOn(2, 'pro')],+ sent: (stored) => [+ echoWithId(stored[0]!, { properties: [{ key: 'plan', operator: 'exact', value: 'business' }] }),+ ],+ expected: [[null, ['group', 2]]],+ },+ {+ name: 'the agent adds a condition without an ID that repeats a property on another group type',+ flagLevel: 0,+ stored: [planOn(1, 'pro')],+ sent: (stored) => [+ echoWithId(stored[0]!),+ { properties: [{ key: 'plan', operator: 'exact', value: 'pro' }], rollout_percentage: 100 },+ ],+ expected: [+ [null, ['group', 1]],+ [null, ['group', 0]],+ ],+ },])('restores each condition from the stored condition with its ID when $name',({ flagLevel, stored, sent, expected }) => {@@ -412,12 +485,40 @@ describe('condition ids', () => {expect.objectContaining({fields: ['filters.groups.N.condition_id:stale_condition_id'],message: expect.stringMatching(- /on filters\.groups\[1\] matches no condition.*copied this condition from another flag .* remove its condition_id/+ /on filters\.groups\[1\] matches no condition.*copied this condition from a different flag, remove its condition_id/),}))})+ it('refuses a condition that drops its ID when it repeats a stored condition with a group property on another group type', () => {+ const existing = {+ aggregation_group_type_index: 0,+ groups: [+ planOn(1, 'pro'),+ {+ properties: [{ key: 'size', type: 'group', group_type_index: 0, operator: 'exact', value: 'L' }],+ rollout_percentage: 100,+ },+ ],+ }+ const [, kept] = readGroups(existing)++ expect(() =>+ preserveGroupTargetingFilters(existing, {+ groups: [+ { properties: [{ key: 'plan', operator: 'exact', value: 'pro' }], rollout_percentage: 50 },+ echoWithId(kept!),+ ],+ })+ ).toThrow(+ expect.objectContaining({+ fields: ['filters.groups.N.condition_id:cross_group_property'],+ message: expect.stringContaining('come from: filters.groups[0]. '),+ })+ )+ })+it('refuses a new condition in front of the stored ones on a mixed flag when it states no aggregation', () => {const mixed = [{ ...personPlan('free'), aggregation_group_type_index: null },diff --git a/services/mcp/tests/unit/preserve-group-targeting.test.ts b/services/mcp/tests/unit/preserve-group-targeting.test.tsindex 77014e1efb52..b50285175ca8 100644--- a/services/mcp/tests/unit/preserve-group-targeting.test.ts+++ b/services/mcp/tests/unit/preserve-group-targeting.test.ts@@ -75,12 +75,15 @@ function aggregationViolations(existing: FlagFilters, merged: FlagFilters | null}/** The condition set paths a refusal names, or none when the merge goes through. */-function refusedSets(merge: () => unknown): string[] {+function refusedSets(+ merge: () => unknown,+ field = 'filters.groups.N.aggregation_group_type_index:unresolved_aggregation'+): string[] {try {merge()} catch (error) {if (error instanceof ToolInputValidationError) {- expect(error.fields).toEqual(['filters.groups.N.aggregation_group_type_index:unresolved_aggregation'])+ expect(error.fields).toEqual([field])return [...error.message.matchAll(/filters\.groups\[\d+\]/g)].map((match) => match[0])}throw error@@ -327,8 +330,24 @@ describe('preserveGroupTargetingFilters', () => {expect(merged?.groups?.[1]?.properties?.[0]?.group_type_index).toBe(1)})- it('fills group_type_index when the agent sets type "group" but omits the index', () => {- const merged = preserveGroupTargetingFilters(existingGroupFlag, {+ // The evaluator reads a group property stored without an index on its set's group type.+ it.each([+ { name: 'the stored property has one', existing: existingGroupFlag },+ {+ name: 'the stored property has none either',+ existing: {+ aggregation_group_type_index: 0,+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [{ key: 'plan', type: 'group', operator: 'exact', value: 'enterprise' }],+ rollout_percentage: 100,+ },+ ],+ },+ },+ ])('fills group_type_index when the agent sets type "group" but omits the index and $name', ({ existing }) => {+ const merged = preserveGroupTargetingFilters(existing, {groups: [{properties: [{ key: 'plan', type: 'group', operator: 'exact', value: 'pro' }],@@ -1988,6 +2007,182 @@ describe('preserveGroupTargetingFilters', () => {expect(aggregationViolations(existingGroupFlag, merged)).toEqual([])})+ const planOnGroupType1 = { key: 'plan', type: 'group', group_type_index: 1, operator: 'exact', value: 'pro' }+ const untypedPlan = { key: 'plan', operator: 'exact', value: 'pro' }++ // The evaluator reads a group property on its own group type, so moving it to its set's group type+ // would change which group the filter reads. The API reports the stored shape instead.+ it.each([+ {+ name: 'the set states its group type and the agent echoes the property',+ set: { aggregation_group_type_index: 0 },+ sent: planOnGroupType1,+ },+ {+ name: 'the set states its group type and the agent sends the property untyped',+ set: { aggregation_group_type_index: 0 },+ sent: untypedPlan,+ },+ { name: 'the set takes the flag level and the agent echoes the property', set: {}, sent: planOnGroupType1 },+ { name: 'the set takes the flag level and the agent sends the property untyped', set: {}, sent: untypedPlan },+ ])("does not move a stored group property to its set's group type when $name", ({ set, sent }) => {+ const existing = {+ aggregation_group_type_index: 0,+ groups: [{ ...set, properties: [planOnGroupType1], rollout_percentage: 100 }],+ }++ const merged = preserveGroupTargetingFilters(existing, {+ groups: [{ ...set, properties: [sent], rollout_percentage: 50 }],+ })++ expect(merged?.groups?.[0]?.properties).toEqual([planOnGroupType1])+ expect(merged?.groups?.[0]?.aggregation_group_type_index).toBe(set.aggregation_group_type_index)+ expect(aggregationViolations(existing, merged)).toEqual([+ 'groups[0].properties[0]: group_property_type_index_mismatch',+ ])+ })++ // The stored set holds `plan` on group types 1 and 0. When the set keeps group type 0, the two stored+ // typings disagree, and an untyped property fails the API's serde guard whichever filter rules the API+ // enforces. A move to group type 1 keeps the first on its own group type and moves the second with+ // the set, so both agree.+ it.each([+ { name: 'the set keeps its group type', aggregation: 0, expected: [untypedPlan, untypedPlan] },+ { name: 'the set moves to group type 1', aggregation: 1, expected: [planOnGroupType1, planOnGroupType1] },+ ])('types a key that its source holds on two group types when $name', ({ aggregation, expected }) => {+ const existing = {+ aggregation_group_type_index: 0,+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [planOnGroupType1, { ...planOnGroupType1, group_type_index: 0 }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existing, {+ groups: [+ {+ aggregation_group_type_index: aggregation,+ properties: [untypedPlan, untypedPlan],+ rollout_percentage: 100,+ },+ ],+ })++ expect(merged?.groups?.[0]?.properties).toEqual(expected)+ })++ const onFlagLevel0 = (...sets: FlagProperty[][]): FlagFilters => ({+ aggregation_group_type_index: 0,+ groups: sets.map((properties) => ({ properties, rollout_percentage: 100 })),+ })+ const planOnGroupType0 = (value: string): FlagProperty => ({ ...planOnGroupType1, group_type_index: 0, value })+ it.each([+ {+ name: 'the agent changes the value and sends the index',+ existing: onFlagLevel0([planOnGroupType1]),+ sent: [[{ ...planOnGroupType1, value: 'ent' }]],+ unpaired: ['filters.groups[0]'],+ },+ {+ name: 'the agent changes the value and sends the property untyped',+ existing: onFlagLevel0([planOnGroupType1]),+ sent: [[{ ...untypedPlan, value: 'ent' }]],+ unpaired: ['filters.groups[0]'],+ },+ {+ name: 'the condition that holds the property is deleted',+ existing: onFlagLevel0([planOnGroupType1], [planOnGroupType0('ent')]),+ sent: [[{ ...untypedPlan, value: 'ent' }]],+ unpaired: ['filters.groups[0]'],+ },+ {+ name: 'the condition in front of the one that holds the property is deleted',+ existing: onFlagLevel0([planOnGroupType0('ent')], [planOnGroupType1]),+ sent: [[planOnGroupType1]],+ unpaired: ['filters.groups[0]'],+ },+ {+ name: 'a condition is added in front of the one that holds the property',+ existing: onFlagLevel0([planOnGroupType1]),+ sent: [[{ key: 'size', operator: 'exact', value: 'large' }], [planOnGroupType1]],+ unpaired: ['filters.groups[0]', 'filters.groups[1]'],+ },+ {+ name: 'another condition has the same filters',+ existing: onFlagLevel0([planOnGroupType1], [planOnGroupType0('pro')]),+ sent: [[untypedPlan], [untypedPlan]],+ unpaired: ['filters.groups[0]', 'filters.groups[1]'],+ },+ ])(+ 'refuses an edit without condition_id to a flag with a group property on another group type when $name',+ ({ existing, sent, unpaired }) => {+ const merge = (): unknown =>+ preserveGroupTargetingFilters(existing, {+ groups: sent.map((properties) => ({ properties, rollout_percentage: 100 })),+ })++ expect(refusedSets(merge, 'filters.groups.N.condition_id:cross_group_property')).toEqual(unpaired)+ }+ )++ // An index the agent sends stays when its condition has a source, and the API reports the mismatch. A+ // new condition has no stored group type to keep, so its property takes the condition's group type.+ it.each([+ { name: 'the condition that holds the key keeps it', appended: false, value: undefined, expected: 2 },+ {+ name: 'the condition that holds the key keeps it with a new value',+ appended: false,+ value: 'ent',+ expected: 2,+ },+ {+ name: "a new condition replaces it with the condition's group type",+ appended: true,+ value: undefined,+ expected: 0,+ },+ ])('decides an index the agent sends on another group type when $name', ({ appended, value, expected }) => {+ const sent = {+ aggregation_group_type_index: 0,+ properties: existingGroupFlag.groups[0]?.properties.map((prop) => ({+ ...prop,+ group_type_index: 2,+ value: value ?? prop.value,+ })),+ rollout_percentage: 100,+ }++ const merged = preserveGroupTargetingFilters(existingGroupFlag, {+ groups: appended ? [...existingGroupFlag.groups, sent] : [sent],+ })++ expect(merged?.groups?.at(-1)?.properties?.[0]?.group_type_index).toBe(expected)+ })++ // A person-aggregated set aggregates on no group type, so its group property sits on another group+ // type than any group type the set moves to.+ it.each([+ { name: 'the agent echoes the property', sent: planOnGroupType1 },+ { name: 'the agent sends the property untyped', sent: untypedPlan },+ ])(+ 'does not move a group property of a person-aggregated set to the group type the set moves to when $name',+ ({ sent }) => {+ const existing = { groups: [{ properties: [planOnGroupType1], rollout_percentage: 100 }] }++ const merged = preserveGroupTargetingFilters(existing, {+ groups: [{ aggregation_group_type_index: 0, properties: [sent], rollout_percentage: 50 }],+ })++ expect(merged?.groups?.[0]?.properties).toEqual([planOnGroupType1])+ expect(aggregationViolations(existing, merged)).toEqual([+ 'groups[0].properties[0]: group_property_type_index_mismatch',+ ])+ }+ )+// The merge walks both sides by index. A malformed entry on either side must not throw.it.each([{ name: 'null groups on the existing flag', existing: { groups: null } },diff --git a/services/mcp/tests/unit/update-feature-flag-preserving-groups.test.ts b/services/mcp/tests/unit/update-feature-flag-preserving-groups.test.tsindex 14333db18c6f..71bc29d16809 100644--- a/services/mcp/tests/unit/update-feature-flag-preserving-groups.test.ts+++ b/services/mcp/tests/unit/update-feature-flag-preserving-groups.test.ts@@ -1,6 +1,7 @@import { describe, expect, it, vi } from 'vitest'import { PostHogValidationError } from '@/lib/errors'+import { withConditionIds } from '@/tools/featureFlags/conditionIds'import { GENERATED_TOOLS } from '@/tools/generated/feature_flags'import type { Context } from '@/tools/types'@@ -102,6 +103,44 @@ describe('update-feature-flag preserving groups', () => {expect(result).toMatchObject({ id: 9 })})+ it.each([+ { name: 'no flag-level aggregation', flagLevel: {} },+ { name: 'a flag-level aggregation', flagLevel: { aggregation_group_type_index: 0 } },+ ])(+ 'matches conditions by condition_id and keeps the IDs out of the PATCH on a flag with $name',+ async ({ flagLevel }) => {+ const storedGroups = [0, 1].map((group_type_index) => ({+ properties: [{ key: 'plan', type: 'group', group_type_index, operator: 'exact', value: 'pro' }],+ rollout_percentage: 100,+ }))+ const existing = { id: 9, key: 'plan-rollout', filters: { ...flagLevel, groups: storedGroups } }+ const request = vi.fn().mockResolvedValueOnce(existing).mockResolvedValueOnce(existing)++ const readIds = (withConditionIds(existing).filters.groups as unknown as { condition_id: string }[]).map(+ (group) => group.condition_id+ )++ const params = tool.schema.parse({+ id: 9,+ filters: {+ groups: [...readIds].reverse().map((condition_id) => ({+ condition_id,+ properties: [{ key: 'plan', operator: 'exact', value: 'pro' }],+ rollout_percentage: 100,+ })),+ },+ })+ const result = (await tool.handler(createMockContext(request), params)) as typeof existing++ const patchGroups = (requestArgs(request, 1).body as typeof existing).filters.groups+ expect(patchGroups.map((group) => group.properties[0]?.group_type_index)).toEqual([1, 0])+ expect(patchGroups.some((group) => 'condition_id' in group)).toBe(false)+ expect(result.filters.groups.map((group) => (group as { condition_id?: string }).condition_id)).toEqual(+ readIds+ )+ }+ )+it('surfaces GET failures instead of PATCHing unmerged filters', async () => {const request = vi.fn().mockRejectedValueOnce(new Error('HTTP 429: rate limited'))@@ -133,7 +172,7 @@ describe('update-feature-flag preserving groups', () => {expect(requestArgs(request, 0).body).toMatchObject({ active: false })})- describe('untyped property error', () => {+ describe('rejected property error', () => {const existing = {id: 9,key: 'pricing-banner',@@ -188,13 +227,21 @@ describe('update-feature-flag preserving groups', () => {shape: 'serde guard',detail: 'groups[1].properties[0].type: invalid property type',code: 'invalid',+ fix: "Don't guess `person`",},{shape: 'structural',detail: 'groups[1].properties[0].type: This field is required.',code: 'structural.groups[].properties[].type.required',+ fix: "Don't guess `person`",},- ])('names the rejected property and its fix for the $shape rejection', async ({ detail, code }) => {+ {+ shape: 'group type mismatch',+ detail: "groups[1].properties[0]: Group properties must match the condition set's group type.",+ code: 'cross_field.group_property_type_index_mismatch',+ fix: 'Ask the user which group type the condition should target',+ },+ ])('names the rejected property and its fix for the $shape rejection', async ({ detail, code, fix }) => {const { request } = rejectPatchWith(detail, code)const rejection: unknown = await tool.handler(createMockContext(request), params).catch((e: unknown) => e)@@ -205,7 +252,7 @@ describe('update-feature-flag preserving groups', () => {expect(message).toContain(detail)expect(message).toContain('filters.groups[1].properties[0]')expect(message).toContain('"plan"')- expect(message).toContain("Don't guess `person`")+ expect(message).toContain(fix)expect(message).not.toContain('"email"')})@@ -220,6 +267,11 @@ describe('update-feature-flag preserving groups', () => {detail: 'groups[5].properties[0].type: invalid property type',code: 'invalid',},+ {+ scenario: 'another rule on a property path',+ detail: 'groups[1].properties[0]: Group-aggregated conditions can only use group properties.',+ code: 'cross_field.group_aggregation_property_type',+ },])('rethrows the API error unchanged for $scenario', async ({ detail, code }) => {const { request, error } = rejectPatchWith(detail, code)