Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(flags): send the row version from the MCP flag update and delete tools (#124130)

Anders625c074de0db
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index d5d0ceb00b92..629c6c0fdb3a 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -19468,6 +19468,7 @@ export namespace Schemas {
ensure_experience_continuity: boolean | null;
evaluation_runtime: EvaluationRuntimeEnum | NullEnum;
bucketing_identifier: BucketingIdentifierEnum | NullEnum;
+ version: number;
}>;
export type PatchedHogFlowSchedule = Partial<{
id: string;
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 4d6fcc03372e..a3eeac9b1abb 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -1356,6 +1356,15 @@ class FeatureFlagPartialUpdateRequestSchemaSerializer(serializers.Serializer):
help_text="Identifier used to bucket users into rollout percentages and variants: 'distinct_id' "
"(user ID, the default) or 'device_id'. Using 'device_id' is incompatible with ensure_experience_continuity=True.",
)
+ version = serializers.IntegerField(
+ required=False,
+ min_value=0,
+ help_text=(
+ "The `version` from your most recent read of this flag. Required when the flag's `filters.version` is "
+ "2: the update is then refused with 409 if anyone else changed the flag after that version. Other flags "
+ "do not check it."
+ ),
+ )
class FeatureFlagExperimentSetMetadataSerializer(serializers.Serializer):
diff --git a/products/feature_flags/backend/api/test/feature_flag_openapi_test_helpers.py b/products/feature_flags/backend/api/test/feature_flag_openapi_test_helpers.py
index 31b97c63fb6a..495cd652d5ba 100644
--- a/products/feature_flags/backend/api/test/feature_flag_openapi_test_helpers.py
+++ b/products/feature_flags/backend/api/test/feature_flag_openapi_test_helpers.py
@@ -15,11 +15,11 @@ FEATURE_FLAG_REQUEST_SCHEMA_EXCLUDED_RUNTIME_FIELDS: frozenset[str] = frozenset(
"analytics_dashboards", # relational link managed via dashboards, not the flag create/update surface
"created_at", # server-managed timestamp, not agent-facing
"creation_context", # write_only origin-product marker set by internal callers
- "deleted", # soft-delete handled via the DELETE endpoint, not the create/update body
+ "deleted", # soft delete goes through delete-feature-flag, which injects it into the PATCH body
"has_encrypted_payloads", # server-managed, derived from payload encryption
"has_enriched_analytics", # internal analytics flag, not agent-facing
"last_called_at", # server-managed usage timestamp, not agent-facing
- "version", # server-managed optimistic-concurrency counter
+ "version", # the server sets it on create; only the partial-update doc serializer documents it
}
)
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py
index f148e6c6ad82..953658e7bc0d 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py
@@ -177,6 +177,14 @@ class TestV2SafetyWritesNeedNoAdmission(V2UpdateTestCase):
(entry,) = self.activity(flag)
assert entry.activity == "deleted"
+ def test_soft_deleting_without_the_row_version_names_it(self) -> None:
+ flag = self.flag(active=True)
+ response = self.patch_flag(flag, {"deleted": True})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert (response.json()["attr"], response.json()["code"]) == ("version", "required")
+ flag.refresh_from_db()
+ assert (flag.deleted, flag.version) == (False, 3)
+
@parameterized.expand(
[
("missing_token", {"active": False}, status.HTTP_400_BAD_REQUEST),
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index ff9636910323..80506014fab7 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -1214,6 +1214,11 @@ export interface PatchedFeatureFlagPartialUpdateRequestSchemaApi {
* * `distinct_id` - User ID (default)
* * `device_id` - Device ID */
bucketing_identifier?: BucketingIdentifierEnumApi | null
+ /**
+ * The `version` from your most recent read of this flag. Required when the flag's `filters.version` is 2: the update is then refused with 409 if anyone else changed the flag after that version. Other flags do not check it.
+ * @minimum 0
+ */
+ version?: number
}
export interface ChangeApi {
diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.ts
index 1cfaaddc0851..224d6b488d2b 100644
--- a/products/feature_flags/frontend/generated/api.zod.ts
+++ b/products/feature_flags/frontend/generated/api.zod.ts
@@ -673,6 +673,7 @@ export const FeatureFlagsUpdateBody = /* @__PURE__ */ zod
* If you're looking to use feature flags on your application, you can either use our JavaScript Library or our dedicated endpoint to check if feature flags are enabled for a given user.
*/
export const featureFlagsPartialUpdateBodyFiltersOneEarlyExitDefault = false
+export const featureFlagsPartialUpdateBodyVersionMin = 0
export const FeatureFlagsPartialUpdateBody = /* @__PURE__ */ zod.object({
key: zod.string().optional().describe('Feature flag key.'),
@@ -1036,6 +1037,13 @@ export const FeatureFlagsPartialUpdateBody = /* @__PURE__ */ zod.object({
.describe(
"Identifier used to bucket users into rollout percentages and variants: 'distinct_id' (user ID, the default) or 'device_id'. Using 'device_id' is incompatible with ensure_experience_continuity=True.\n\n\* `distinct_id` - User ID (default)\n\* `device_id` - Device ID"
),
+ version: zod
+ .number()
+ .min(featureFlagsPartialUpdateBodyVersionMin)
+ .optional()
+ .describe(
+ "The `version` from your most recent read of this flag. Required when the flag's `filters.version` is 2: the update is then refused with 409 if anyone else changed the flag after that version. Other flags do not check it."
+ ),
})
/**
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index 8b0886aa4b8f..a663f78808f3 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -72,7 +72,7 @@ tools:
default) or `device_id`. Using `device_id` is incompatible with `ensure_experience_continuity=true`.
hooks: featureFlags/conditionIdHooks
delete-feature-flag:
- operation: feature_flags_destroy
+ operation: feature_flags_partial_update
enabled: true
scopes:
- feature_flag:write
@@ -81,8 +81,17 @@ tools:
destructive: true
idempotent: true
title: Delete feature flag
- description: |
+ description: >
Soft-delete a feature flag by ID in the current project.
+
+
+ A flag whose `filters.version` is 2 requires `version`, so read the flag first and send its current
+ `version`; never guess it. On such a flag a stale `version` returns 409: read the flag again and decide
+ against its current state. Other flags do not check `version`.
+ include_params:
+ - version
+ inject_body:
+ deleted: true
param_overrides:
id:
cast: string-int
@@ -92,7 +101,6 @@ tools:
- feature_flag_id
- featureFlagId
hooks: featureFlags/conditionIdHooks
- soft_delete: true
feature-flag-archive:
operation: feature_flags_archive_create
enabled: true
@@ -169,8 +177,9 @@ tools:
Pass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag
- first and send its current `version`; never guess it. With `version`, a change made after that read returns
- 409: read the flag again and decide against its current state.
+ first and send its current `version`; never guess it. When the call would change the flag, a stale `version`
+ returns 409: read the flag again and decide against its current state. A call that changes nothing succeeds
+ without checking `version`, and the response carries the current `version`.
A disabled flag stops evaluating everywhere, so every caller falls back to its own default. Tell the user
@@ -228,8 +237,9 @@ tools:
Pass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag
- first and send its current `version`; never guess it. With `version`, a change made after that read returns
- 409: read the flag again and decide against its current state.
+ first and send its current `version`; never guess it. When the call would change the flag, a stale `version`
+ returns 409: read the flag again and decide against its current state. A call that changes nothing succeeds
+ without checking `version`, and the response carries the current `version`.
Returns 400 when the flag is archived (call `feature-flag-unarchive` first), when a flag it depends on is
@@ -908,10 +918,16 @@ tools:
`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.
+ refuse the write when the flag changed after the version you read, so a concurrent edit cannot be lost. On a
+ flag without `filters.version` 2, this tool does not check `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.
+
+
+ A flag whose `filters.version` is 2 requires `version` for any change, so read the flag first and send its
+ current `version`; never guess it. A stale `version` returns 409: read the flag again and decide against its
+ current state. Don't send `filters` for such a flag: its rules change through `feature-flag-rules-update`.
Rollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters`
@@ -944,6 +960,7 @@ tools:
- ensure_experience_continuity
- evaluation_runtime
- bucketing_identifier
+ - version
param_overrides:
id:
cast: string-int
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 687992ebcb7d..1c24d9f2760c 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -4628,7 +4628,7 @@
}
},
"delete-feature-flag": {
- "description": "Soft-delete a feature flag by ID in the current project.",
+ "description": "Soft-delete a feature flag by ID in the current project.\n\nA flag whose `filters.version` is 2 requires `version`, so read the flag first and send its current `version`; never guess it. On such a flag a stale `version` returns 409: read the flag again and decide against its current state. Other flags do not check `version`.",
"category": "Feature flags",
"feature": "flags",
"summary": "Delete feature flag",
@@ -6772,7 +6772,7 @@
}
},
"feature-flag-disable": {
- "description": "Turn a feature flag off. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to false and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change.\n\nPass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag first and send its current `version`; never guess it. With `version`, a change made after that read returns 409: read the flag again and decide against its current state.\n\nA disabled flag stops evaluating everywhere, so every caller falls back to its own default. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition. `feature-flag-get-definition-by-key` already returns it, and `feature-flag-get-definition` returns it by ID.\n\nReturns 400 when other active flags depend on this one; `feature-flags-dependent-flags-retrieve` lists them. Returns 409 when an approval policy gates disabling. Disabling an already-disabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags, and an archived flag is already disabled. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag off at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
+ "description": "Turn a feature flag off. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to false and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change.\n\nPass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag first and send its current `version`; never guess it. When the call would change the flag, a stale `version` returns 409: read the flag again and decide against its current state. A call that changes nothing succeeds without checking `version`, and the response carries the current `version`.\n\nA disabled flag stops evaluating everywhere, so every caller falls back to its own default. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition. `feature-flag-get-definition-by-key` already returns it, and `feature-flag-get-definition` returns it by ID.\n\nReturns 400 when other active flags depend on this one; `feature-flags-dependent-flags-retrieve` lists them. Returns 409 when an approval policy gates disabling. Disabling an already-disabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags, and an archived flag is already disabled. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag off at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
"category": "Feature flags",
"feature": "flags",
"summary": "Disable feature flag",
@@ -6787,7 +6787,7 @@
}
},
"feature-flag-enable": {
- "description": "Turn a feature flag on. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. To change who the flag is served to, use `update-feature-flag`.\n\nPass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag first and send its current `version`; never guess it. With `version`, a change made after that read returns 409: read the flag again and decide against its current state.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first), when a flag it depends on is disabled, or when a release condition targets a deleted cohort (remove that condition with `update-feature-flag`). Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
+ "description": "Turn a feature flag on. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. To change who the flag is served to, use `update-feature-flag`.\n\nPass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag first and send its current `version`; never guess it. When the call would change the flag, a stale `version` returns 409: read the flag again and decide against its current state. A call that changes nothing succeeds without checking `version`, and the response carries the current `version`.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first), when a flag it depends on is disabled, or when a release condition targets a deleted cohort (remove that condition with `update-feature-flag`). Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
"category": "Feature flags",
"feature": "flags",
"summary": "Enable feature flag",
@@ -14802,7 +14802,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. 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`.",
+ "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. On a flag without `filters.version` 2, this tool does not check `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\nA flag whose `filters.version` is 2 requires `version` for any change, so read the flag first and send its current `version`; never guess it. A stale `version` returns 409: read the flag again and decide against its current state. Don't send `filters` for such a flag: its rules change through `feature-flag-rules-update`.\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.json
index 3f09a9ffd80b..dc5b02913628 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -4657,7 +4657,7 @@
}
},
"delete-feature-flag": {
- "description": "Soft-delete a feature flag by ID in the current project.",
+ "description": "Soft-delete a feature flag by ID in the current project.\n\nA flag whose `filters.version` is 2 requires `version`, so read the flag first and send its current `version`; never guess it. On such a flag a stale `version` returns 409: read the flag again and decide against its current state. Other flags do not check `version`.",
"category": "Feature flags",
"feature": "flags",
"summary": "Delete feature flag",
@@ -6946,7 +6946,7 @@
}
},
"feature-flag-disable": {
- "description": "Turn a feature flag off. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to false and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change.\n\nPass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag first and send its current `version`; never guess it. With `version`, a change made after that read returns 409: read the flag again and decide against its current state.\n\nA disabled flag stops evaluating everywhere, so every caller falls back to its own default. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition. `feature-flag-get-definition-by-key` already returns it, and `feature-flag-get-definition` returns it by ID.\n\nReturns 400 when other active flags depend on this one; `feature-flags-dependent-flags-retrieve` lists them. Returns 409 when an approval policy gates disabling. Disabling an already-disabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags, and an archived flag is already disabled. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag off at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
+ "description": "Turn a feature flag off. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to false and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change.\n\nPass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag first and send its current `version`; never guess it. When the call would change the flag, a stale `version` returns 409: read the flag again and decide against its current state. A call that changes nothing succeeds without checking `version`, and the response carries the current `version`.\n\nA disabled flag stops evaluating everywhere, so every caller falls back to its own default. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition. `feature-flag-get-definition-by-key` already returns it, and `feature-flag-get-definition` returns it by ID.\n\nReturns 400 when other active flags depend on this one; `feature-flags-dependent-flags-retrieve` lists them. Returns 409 when an approval policy gates disabling. Disabling an already-disabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags, and an archived flag is already disabled. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag off at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
"category": "Feature flags",
"feature": "flags",
"summary": "Disable feature flag",
@@ -6961,7 +6961,7 @@
}
},
"feature-flag-enable": {
- "description": "Turn a feature flag on. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. To change who the flag is served to, use `update-feature-flag`.\n\nPass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag first and send its current `version`; never guess it. With `version`, a change made after that read returns 409: read the flag again and decide against its current state.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first), when a flag it depends on is disabled, or when a release condition targets a deleted cohort (remove that condition with `update-feature-flag`). Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
+ "description": "Turn a feature flag on. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. To change who the flag is served to, use `update-feature-flag`.\n\nPass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag first and send its current `version`; never guess it. When the call would change the flag, a stale `version` returns 409: read the flag again and decide against its current state. A call that changes nothing succeeds without checking `version`, and the response carries the current `version`.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first), when a flag it depends on is disabled, or when a release condition targets a deleted cohort (remove that condition with `update-feature-flag`). Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
"category": "Feature flags",
"feature": "flags",
"summary": "Enable feature flag",
@@ -15564,7 +15564,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. 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`.",
+ "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. On a flag without `filters.version` 2, this tool does not check `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\nA flag whose `filters.version` is 2 requires `version` for any change, so read the flag first and send its current `version`; never guess it. A stale `version` returns 409: read the flag again and decide against its current state. Don't send `filters` for such a flag: its rules change through `feature-flag-rules-update`.\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/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5bdb30011a68..28da57a80dfa 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -87547,6 +87547,11 @@ export namespace Schemas {
* * `distinct_id` - User ID (default)
* * `device_id` - Device ID */
bucketing_identifier?: BucketingIdentifierEnum | null;
+ /**
+ * The `version` from your most recent read of this flag. Required when the flag's `filters.version` is 2: the update is then refused with 409 if anyone else changed the flag after that version. Other flags do not check it.
+ * @minimum 0
+ */
+ version?: number;
}
export interface PatchedFeatureRequestProductArea {
diff --git a/services/mcp/src/generated/feature_flags/api.ts b/services/mcp/src/generated/feature_flags/api.ts
index cc26130de34b..de51cee687ae 100644
--- a/services/mcp/src/generated/feature_flags/api.ts
+++ b/services/mcp/src/generated/feature_flags/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 28 enabled ops
+ * PostHog API - MCP 27 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -541,6 +541,7 @@ export const FeatureFlagsPartialUpdateParams = () => zod.object({
})
export const featureFlagsPartialUpdateBodyFiltersOneEarlyExitDefault = false
+export const featureFlagsPartialUpdateBodyVersionMin = 0
export const FeatureFlagsPartialUpdateBody = () => zod.object({
key: zod.string().optional().describe('Feature flag key.'),
@@ -904,17 +905,12 @@ export const FeatureFlagsPartialUpdateBody = () => zod.object({
.describe(
"Identifier used to bucket users into rollout percentages and variants: 'distinct_id' (user ID, the default) or 'device_id'. Using 'device_id' is incompatible with ensure_experience_continuity=True.\n\n\* `distinct_id` - User ID (default)\n\* `device_id` - Device ID"
),
-})
-
-/**
- * Hard delete of this model is not allowed. Use a patch API call to set "deleted" to true
- */
-export const FeatureFlagsDestroyParams = () => zod.object({
- id: zod.number().describe('A unique integer value identifying this feature flag.'),
- project_id: zod
- .string()
+ version: zod
+ .number()
+ .min(featureFlagsPartialUpdateBodyVersionMin)
+ .optional()
.describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ "The `version` from your most recent read of this flag. Required when the flag's `filters.version` is 2: the update is then refused with 409 if anyone else changed the flag after that version. Other flags do not check it."
),
})
diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.ts
index c5997f7db144..10b9e63ef8af 100644
--- a/services/mcp/src/tools/generated/feature_flags.ts
+++ b/services/mcp/src/tools/generated/feature_flags.ts
@@ -91,12 +91,27 @@ const createFeatureFlag = (): ToolBase<
})
const DeleteFeatureFlagSchema = () => {
- const FeatureFlagsDestroyParams = orvalSchemas.FeatureFlagsDestroyParams()
+ const FeatureFlagsPartialUpdateBody = orvalSchemas.FeatureFlagsPartialUpdateBody()
+ const FeatureFlagsPartialUpdateParams = orvalSchemas.FeatureFlagsPartialUpdateParams()
return z.preprocess(
normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),
- FeatureFlagsDestroyParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, FeatureFlagsDestroyParams.shape['id']),
- })
+ FeatureFlagsPartialUpdateParams.omit({ project_id: true })
+ .extend(
+ FeatureFlagsPartialUpdateBody.omit({
+ key: true,
+ name: true,
+ filters: true,
+ active: true,
+ archived: true,
+ tags: true,
+ evaluation_contexts: true,
+ is_remote_configuration: true,
+ ensure_experience_continuity: true,
+ evaluation_runtime: true,
+ bucketing_identifier: true,
+ }).shape
+ )
+ .extend({ id: z.preprocess(castStringToInt, FeatureFlagsPartialUpdateParams.shape['id']) })
)
}
@@ -107,10 +122,15 @@ const deleteFeatureFlag = (): ToolBase<ReturnType<typeof DeleteFeatureFlagSchema
hooks_deleteFeatureFlag,
async (context: Context, params: z.infer<ReturnType<typeof DeleteFeatureFlagSchema>>) => {
const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.version !== undefined) {
+ body['version'] = params.version
+ }
+ body['deleted'] = true
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 },
+ body: await transformRequestBody(hooks_deleteFeatureFlag, context, params, body),
})
return result
}
@@ -1101,6 +1121,9 @@ const updateFeatureFlag = (): ToolBase<
if (params.bucketing_identifier !== undefined) {
body['bucketing_identifier'] = params.bucketing_identifier
}
+ if (params.version !== undefined) {
+ body['version'] = params.version
+ }
const result = await context.api.request<Schemas.FeatureFlag>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/`,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/delete-feature-flag.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/delete-feature-flag.json
index 88cc27e940e9..928594890fa5 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/delete-feature-flag.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/delete-feature-flag.json
@@ -4,6 +4,11 @@
"id": {
"description": "A unique integer value identifying this feature flag.",
"type": "number"
+ },
+ "version": {
+ "description": "The `version` from your most recent read of this flag. Required when the flag's `filters.version` is 2: the update is then refused with 409 if anyone else changed the flag after that version. Other flags do not check it.",
+ "minimum": 0,
+ "type": "number"
}
},
"required": ["id"],
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.json
index f3e646de9664..a3b6515040b5 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
@@ -562,6 +562,11 @@
"type": "string"
},
"type": "array"
+ },
+ "version": {
+ "description": "The `version` from your most recent read of this flag. Required when the flag's `filters.version` is 2: the update is then refused with 409 if anyone else changed the flag after that version. Other flags do not check it.",
+ "minimum": 0,
+ "type": "number"
}
},
"required": ["id"],
diff --git a/services/mcp/tests/unit/feature-flag-lifecycle-tools.test.ts b/services/mcp/tests/unit/feature-flag-lifecycle-tools.test.ts
index ec652bcf2057..6c659d2da5c9 100644
--- a/services/mcp/tests/unit/feature-flag-lifecycle-tools.test.ts
+++ b/services/mcp/tests/unit/feature-flag-lifecycle-tools.test.ts
@@ -45,6 +45,16 @@ const ROLLOUT_TOOLS = [
},
] as const
+function createMockContext(requestMock: ReturnType<typeof vi.fn>): Context {
+ return {
+ api: {
+ request: requestMock,
+ getProjectBaseUrl: () => 'https://app.posthog.com/project/17',
+ },
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('17') },
+ } as unknown as Context
+}
+
describe('feature flag lifecycle tools', () => {
// The snapshot test would also catch a `filters` param appearing here, but it is
// silenced by `vitest -u`. These assertions are not: the whole point of the lifecycle
@@ -80,13 +90,7 @@ describe('feature flag lifecycle tools', () => {
// turn a flag on would turn it off.
it.each(LIFECYCLE_TOOLS)('$name posts to its own endpoint ($case)', async ({ name, input, body }) => {
const requestMock = vi.fn().mockResolvedValue({ id: 42 })
- const context = {
- api: {
- request: requestMock,
- getProjectBaseUrl: () => 'https://app.posthog.com/project/17',
- },
- stateManager: { getProjectId: vi.fn().mockResolvedValue('17') },
- } as unknown as Context
+ const context = createMockContext(requestMock)
await GENERATED_TOOL_MAP[name]!().handler(context, input)
@@ -119,13 +123,7 @@ describe('feature flag lifecycle tools', () => {
'$name posts the version and rollout fields to its endpoint',
async ({ name, input, path, body }) => {
const requestMock = vi.fn().mockResolvedValue({ id: 42 })
- const context = {
- api: {
- request: requestMock,
- getProjectBaseUrl: () => 'https://app.posthog.com/project/17',
- },
- stateManager: { getProjectId: vi.fn().mockResolvedValue('17') },
- } as unknown as Context
+ const context = createMockContext(requestMock)
await GENERATED_TOOL_MAP[name]!().handler(context, input)
@@ -133,3 +131,69 @@ describe('feature flag lifecycle tools', () => {
}
)
})
+
+// A flag on config version 2 refuses any PATCH without the row `version`, a soft delete included.
+const VERSIONED_PATCH_TOOLS = [
+ {
+ name: 'delete-feature-flag',
+ case: 'versioned',
+ input: { id: 42, version: 3 },
+ body: { version: 3, deleted: true },
+ },
+ { name: 'delete-feature-flag', case: 'unversioned', input: { id: 42 }, body: { deleted: true } },
+ {
+ name: 'update-feature-flag',
+ case: 'versioned',
+ input: { id: 42, name: 'Renamed', version: 3 },
+ body: { name: 'Renamed', version: 3 },
+ },
+ { name: 'update-feature-flag', case: 'unversioned', input: { id: 42, name: 'Renamed' }, body: { name: 'Renamed' } },
+] as const
+
+describe('feature flag PATCH tools', () => {
+ it.each(['delete-feature-flag', 'update-feature-flag'])('%s takes an optional version', (name) => {
+ const schema = z.toJSONSchema(GENERATED_TOOL_MAP[name]!().schema, { io: 'input', reused: 'inline' }) as {
+ properties?: Record<string, unknown>
+ required?: string[]
+ }
+
+ expect(schema.properties).toHaveProperty('version')
+ expect(schema.required).toEqual(['id'])
+ })
+
+ it('delete-feature-flag takes only the flag id and version', () => {
+ const schema = z.toJSONSchema(GENERATED_TOOL_MAP['delete-feature-flag']!().schema, {
+ io: 'input',
+ reused: 'inline',
+ }) as { properties?: Record<string, unknown> }
+
+ expect(Object.keys(schema.properties ?? {}).sort()).toEqual(['id', 'version'])
+ })
+
+ it.each(VERSIONED_PATCH_TOOLS)('$name sends version only when given ($case)', async ({ name, input, body }) => {
+ const requestMock = vi.fn().mockResolvedValue({ id: 42 })
+ const context = createMockContext(requestMock)
+
+ await GENERATED_TOOL_MAP[name]!().handler(context, input)
+
+ expect(requestMock).toHaveBeenCalledExactlyOnceWith({
+ method: 'PATCH',
+ path: '/api/projects/17/feature_flags/42/',
+ body,
+ })
+ })
+
+ it('delete-feature-flag always soft-deletes, whatever else the caller sends', async () => {
+ const requestMock = vi.fn().mockResolvedValue({ id: 42 })
+ const context = createMockContext(requestMock)
+ const tool = GENERATED_TOOL_MAP['delete-feature-flag']!()
+
+ await tool.handler(context, tool.schema.parse({ id: 42, version: 3, deleted: false, name: 'Renamed' }))
+
+ expect(requestMock).toHaveBeenCalledExactlyOnceWith({
+ method: 'PATCH',
+ path: '/api/projects/17/feature_flags/42/',
+ body: { version: 3, deleted: true },
+ })
+ })
+})