Skip to content

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

feat(flags): expose bulk-ops feature flag endpoints as MCP tools (#57885)

Dylan Martina8fae3f10aa4
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 4902afa09d51..0eb8ea85632d 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -1587,6 +1587,14 @@ export const getPropertyDefinitionsBulkUpdateTagsCreateUrl = (projectId: string)
/**
* Bulk update tags on multiple objects.
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index 4995bee45cf1..0af1fcaaae05 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -2494,6 +2494,14 @@ export const PropertyDefinitionsPartialUpdateBody = /* @__PURE__ */ zod
/**
* Bulk update tags on multiple objects.
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/posthog/api/feature_flag.py b/posthog/api/feature_flag.py
index 6a3819949ea6..2ffc3c5f3784 100644
--- a/posthog/api/feature_flag.py
+++ b/posthog/api/feature_flag.py
@@ -2361,6 +2361,124 @@ class LocalEvaluationResponseSerializer(serializers.Serializer):
)
+class BulkKeysRequestSerializer(serializers.Serializer):
+ ids = serializers.ListField(
+ child=serializers.JSONField(),
+ required=False,
+ allow_empty=True,
+ help_text=(
+ "Feature flag IDs to look up keys for. Strings of digits are also accepted; any other value "
+ "is reported in the response `warning` field and otherwise ignored."
+ ),
+ )
+
+
+class BulkKeysResponseSerializer(serializers.Serializer):
+ keys = serializers.DictField(
+ child=serializers.CharField(),
+ help_text="Mapping of feature flag ID (as a string) to flag key, for IDs that exist in this project.",
+ )
+ warning = serializers.CharField(
+ required=False,
+ help_text="Present when some submitted IDs were not numeric and were ignored.",
+ )
+
+
+class BulkDeleteFiltersSerializer(serializers.Serializer):
+ """Allowed filter keys for bulk_delete — same shape as the list endpoint's query params."""
+
+ active = serializers.ChoiceField(
+ choices=["true", "false", "STALE"],
+ required=False,
+ help_text="Filter by active state.",
+ )
+ created_by_id = serializers.IntegerField(
+ required=False,
+ help_text="Filter to flags created by a specific user ID.",
+ )
+ search = serializers.CharField(
+ required=False,
+ help_text="Search by feature flag key or name (case-insensitive).",
+ )
+ type = serializers.ChoiceField(
+ choices=["boolean", "multivariant", "experiment", "remote_config"],
+ required=False,
+ help_text="Filter by flag type.",
+ )
+ evaluation_runtime = serializers.ChoiceField(
+ choices=FeatureFlag.EVALUATION_RUNTIME_CHOICES,
+ required=False,
+ help_text="Filter by evaluation runtime.",
+ )
+ excluded_properties = serializers.CharField(
+ required=False,
+ help_text="JSON-encoded property filter to exclude. Same shape as the list endpoint.",
+ )
+ tags = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ help_text="Tag names to filter by. Flags carrying at least one of these tags match.",
+ )
+ has_evaluation_contexts = serializers.BooleanField(
+ required=False,
+ help_text="When true, only matches flags with at least one evaluation context.",
+ )
+
+
+class BulkDeleteRequestSerializer(serializers.Serializer):
+ filters = BulkDeleteFiltersSerializer(
+ required=False,
+ help_text=(
+ "Filter criteria — same shape as the list endpoint's query params. Mutually exclusive with `ids`. "
+ "Use this to bulk-delete by search/active/tags/etc. instead of supplying explicit IDs."
+ ),
+ )
+ ids = serializers.ListField(
+ child=serializers.IntegerField(min_value=1),
+ required=False,
+ help_text="Explicit feature flag IDs to soft-delete. Mutually exclusive with `filters`.",
+ )
+
+
+class BulkDeleteDeletedItemSerializer(serializers.Serializer):
+ id = serializers.IntegerField(help_text="ID of the soft-deleted flag.")
+ key = serializers.CharField(help_text="The flag key at the time of deletion.")
+ rollout_state = serializers.ChoiceField(
+ choices=["fully_rolled_out", "not_rolled_out", "partial"],
+ help_text="Rollout state captured before deletion.",
+ )
+ active_variant = serializers.CharField(
+ allow_null=True,
+ help_text="Variant key when a multivariate flag was fully rolled out to a single variant; otherwise null.",
+ )
+
+
+class BulkDeleteErrorItemSerializer(serializers.Serializer):
+ id = serializers.JSONField(
+ help_text="Feature flag ID — integer for valid inputs; the original raw value for invalid inputs."
+ )
+ key = serializers.CharField(required=False, help_text="The flag key, when known.")
+ reason = serializers.CharField(help_text="Human-readable reason the flag could not be deleted.")
+
+
+class BulkDeleteResponseSerializer(serializers.Serializer):
+ """
+ Schema-only — referenced from ``@extend_schema(responses=...)`` to describe the wire format.
+ Never instantiate this for validation or call ``.is_valid()`` / ``.errors`` on it: the
+ declared ``errors`` field shadows DRF's inherited ``Serializer.errors`` ReturnDict property,
+ so accessing ``serializer.errors`` would return this field descriptor instead of validation
+ errors. The handler builds the response dict directly; this class exists only so drf-spectacular
+ can render the response in the OpenAPI spec and downstream generated clients.
+ """
+
+ deleted = BulkDeleteDeletedItemSerializer(many=True, help_text="Flags successfully soft-deleted.")
+ # Explicit ListSerializer avoids the many=True descriptor magic that confuses type checkers.
+ errors: serializers.ListSerializer = serializers.ListSerializer( # type: ignore[assignment]
+ child=BulkDeleteErrorItemSerializer(),
+ help_text="Flags that could not be deleted, with reasons.",
+ )
+
+
# ClickHouse cost attribution: this viewset currently has no direct ClickHouse calls —
# all ClickHouse work is delegated to helpers (user_blast_radius.py, flag_analytics.py)
# that already tag their queries. If you add a new ClickHouse query reachable from an
@@ -2383,6 +2501,10 @@ class FeatureFlagViewSet(
"""
scope_object = "feature_flag"
+ # Opt the shared TaggedItemViewSetMixin action into feature_flag:write.
+ # Other inheritors of the mixin don't extend write actions and so still
+ # reject PAT calls — keeps the scope local to this viewset.
+ scope_object_write_actions = ["create", "update", "partial_update", "patch", "destroy", "bulk_update_tags"]
# Use the unfiltered manager so non-list actions (retrieve, update, etc.)
# can access soft-deleted flags. The list action applies its own
# deleted=False filter in safely_get_queryset.
@@ -2788,7 +2910,14 @@ class FeatureFlagViewSet(
for feature_flag in all_serialized_flags
)
- @action(methods=["POST"], detail=False)
+ @extend_schema(
+ request=BulkKeysRequestSerializer,
+ responses={
+ 200: OpenApiResponse(response=BulkKeysResponseSerializer),
+ 400: OpenApiResponse(response=ErrorResponseSerializer, description="Invalid flag IDs provided."),
+ },
+ )
+ @action(methods=["POST"], detail=False, required_scopes=["feature_flag:read"])
def bulk_keys(self, request: request.Request, **kwargs):
"""
Get feature flag keys by IDs.
@@ -2829,8 +2958,13 @@ class FeatureFlagViewSet(
if invalid_ids:
response_data["warning"] = f"Invalid flag IDs ignored: {invalid_ids}"
- # Fetch flags by IDs
- flags = FeatureFlag.objects.filter(id__in=flag_ids, team__project_id=self.project_id).values_list("id", "key")
+ # Filter through per-object ACLs so a caller can't probe IDs to learn keys of flags they've been denied.
+ # The queryset is project-scoped (team__project_id) while the AC filter is team-scoped — equivalent today
+ # since team_id == project_id, asymmetric only under the deprecated multi-team-per-project ("environments")
+ # path being removed. Mirrors the list endpoint's ACL filtering.
+ queryset = FeatureFlag.objects.filter(id__in=flag_ids, team__project_id=self.project_id)
+ queryset = self.user_access_control.filter_queryset_by_access_level(queryset, include_all_if_admin=True)
+ flags = queryset.values_list("id", "key")
# Create mapping of ID to key
keys_mapping = {str(flag_id): key for flag_id, key in flags}
@@ -2886,6 +3020,16 @@ class FeatureFlagViewSet(
}
)
+ @extend_schema(
+ request=BulkDeleteRequestSerializer,
+ responses={
+ 200: OpenApiResponse(response=BulkDeleteResponseSerializer),
+ 400: OpenApiResponse(
+ response=ErrorResponseSerializer,
+ description="Invalid input — e.g., both filters and ids supplied, neither supplied, or unknown filter keys.",
+ ),
+ },
+ )
@action(methods=["POST"], detail=False, required_scopes=["feature_flag:write"])
def bulk_delete(self, request: request.Request, **kwargs):
"""
@@ -2925,16 +3069,7 @@ class FeatureFlagViewSet(
# Validate filter keys against allowlist to prevent accidental mass deletion
if filters:
- valid_filter_keys = {
- "active",
- "created_by_id",
- "search",
- "type",
- "evaluation_runtime",
- "excluded_properties",
- "tags",
- "has_evaluation_contexts",
- }
+ valid_filter_keys = set(BulkDeleteFiltersSerializer().fields.keys())
unknown_keys = set(filters.keys()) - valid_filter_keys
if unknown_keys:
return Response(
diff --git a/posthog/api/tagged_item.py b/posthog/api/tagged_item.py
index bb22ab30383a..935a48dbdbd4 100644
--- a/posthog/api/tagged_item.py
+++ b/posthog/api/tagged_item.py
@@ -184,6 +184,14 @@ class TaggedItemViewSetMixin(viewsets.GenericViewSet):
"""
Bulk update tags on multiple objects.
+ PAT access: this action has no ``required_scopes=`` on the decorator —
+ inheriting viewsets must add ``"bulk_update_tags"`` to their
+ ``scope_object_write_actions`` list to accept personal API keys.
+ Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+ "This action does not support personal API key access". Done per-viewset
+ so granting ``<scope>:write`` for one resource doesn't leak access to
+ sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/posthog/api/test/test_feature_flag.py b/posthog/api/test/test_feature_flag.py
index bb69c4752dad..4afc992c6a06 100644
--- a/posthog/api/test/test_feature_flag.py
+++ b/posthog/api/test/test_feature_flag.py
@@ -28,7 +28,7 @@ from posthog.api.cohort import get_cohort_actors_for_feature_flag
from posthog.api.feature_flag import FeatureFlagSerializer, extract_etag_from_header
from posthog.constants import AvailableFeature
from posthog.helpers.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE, get_decrypted_flag_payload
-from posthog.models import FeatureFlag, GroupTypeMapping, TaggedItem, User
+from posthog.models import FeatureFlag, GroupTypeMapping, Insight, TaggedItem, User
from posthog.models.cohort import Cohort
from posthog.models.cohort.cohort import CohortType
from posthog.models.feature_flag import FeatureFlagDashboards, get_feature_flags_for_team_in_cache
@@ -7519,6 +7519,84 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
assert "keys" in data
assert data["keys"] == {str(flag1.id): "test-flag-1"}
+ def test_bulk_keys_works_with_personal_api_key(self):
+ """Once enabled as MCP tool with feature_flag:read scope, PAT requests must succeed."""
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="pat-scope-test",
+ filters={"groups": [{"rollout_percentage": 100, "properties": []}]},
+ )
+ personal_api_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="X",
+ user=self.user,
+ scopes=["feature_flag:read"],
+ secure_value=hash_key_value(personal_api_key),
+ )
+ self.client.logout()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/bulk_keys/",
+ {"ids": [flag.id]},
+ format="json",
+ headers={"authorization": f"Bearer {personal_api_key}"},
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {"keys": {str(flag.id): "pat-scope-test"}}
+
+ def test_bulk_update_tags_works_with_personal_api_key(self):
+ """Same scope-config bug on bulk_update_tags; same fix in tagged_item.py."""
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="pat-tag-test",
+ filters={"groups": [{"rollout_percentage": 100, "properties": []}]},
+ )
+ personal_api_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="X",
+ user=self.user,
+ scopes=["feature_flag:write"],
+ secure_value=hash_key_value(personal_api_key),
+ )
+ self.client.logout()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/bulk_update_tags/",
+ {"ids": [flag.id], "action": "add", "tags": ["foo"]},
+ format="json",
+ headers={"authorization": f"Bearer {personal_api_key}"},
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ # Pin the body so a regression that grants the PAT scope but loses the
+ # mutation (broken preload_object_access_controls, wrong scope_object,
+ # etc.) can't stay green: the endpoint returns 200 with the flag in
+ # `skipped` rather than a non-2xx status when ACLs drop it.
+ body = response.json()
+ assert body["updated"] == [{"id": flag.id, "tags": ["foo"]}]
+ assert body["skipped"] == []
+
+ # Lives in the feature-flag test file (instead of test_insight.py) so the
+ # full bulk-ops PAT regression story — positive feature-flag cases and the
+ # negative cross-resource block — stays adjacent for reviewers of #57885.
+ def test_feature_flag_write_pat_cannot_mutate_insight_tags(self):
+ """A feature_flag:write PAT must not reach Insight.bulk_update_tags via the shared mixin."""
+ insight = Insight.objects.create(team=self.team, name="x", created_by=self.user)
+ personal_api_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="X",
+ user=self.user,
+ scopes=["feature_flag:write"],
+ secure_value=hash_key_value(personal_api_key),
+ )
+ self.client.logout()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/insights/bulk_update_tags/",
+ {"ids": [insight.id], "action": "add", "tags": ["foo"]},
+ format="json",
+ headers={"authorization": f"Bearer {personal_api_key}"},
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+
def test_local_evaluation_caching_basic(self):
"""Test basic caching functionality for local_evaluation endpoint."""
# Clear any existing flags for this team to avoid interference
@@ -8660,6 +8738,182 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
keys = [f["key"] for f in list_response.json()["results"]]
self.assertNotIn("blocked-flag", keys)
+ def test_member_still_blocked_from_bulk_keys_default_none_flag(self) -> None:
+ # bulk_keys must not leak keys for flags the user has been explicitly
+ # denied, even when the caller submits the ID directly.
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+
+ other = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
+
+ visible_flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ name="visible flag",
+ key="visible-flag",
+ )
+ blocked_flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ name="blocked flag",
+ key="blocked-flag",
+ )
+ AccessControl.objects.create(
+ resource="feature_flag", resource_id=blocked_flag.id, team=self.team, access_level="none"
+ )
+
+ self.client.force_login(other)
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/bulk_keys/",
+ {"ids": [visible_flag.id, blocked_flag.id]},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ keys = response.json()["keys"]
+ self.assertEqual(keys.get(str(visible_flag.id)), "visible-flag")
+ self.assertNotIn(str(blocked_flag.id), keys)
+
+ def test_member_with_explicit_viewer_grant_can_bulk_keys_default_none_flag(self) -> None:
+ # Inverse of the test above — exercises the allowed_resource_ids branch
+ # of filter_queryset_by_access_level: a flag with a team-wide "none"
+ # default plus an explicit viewer grant for this member must round-trip.
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+
+ grantee = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
+ grantee_membership = grantee.organization_memberships.get(organization=self.organization)
+
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ name="granted flag",
+ key="granted-flag",
+ )
+ AccessControl.objects.create(resource="feature_flag", resource_id=flag.id, team=self.team, access_level="none")
+ AccessControl.objects.create(
+ resource="feature_flag",
+ resource_id=flag.id,
+ team=self.team,
+ organization_member=grantee_membership,
+ access_level="viewer",
+ )
+
+ self.client.force_login(grantee)
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/bulk_keys/",
+ {"ids": [flag.id]},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["keys"].get(str(flag.id)), "granted-flag")
+
+ def test_org_admin_can_bulk_keys_default_none_flag(self) -> None:
+ # Exercises the include_all_if_admin=True short-circuit: org admins must
+ # be able to resolve keys for flags with a team-wide "none" default,
+ # matching the list endpoint's behavior for feature_flag.
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+
+ creator = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=creator,
+ name="default-none flag",
+ key="default-none-flag",
+ )
+ AccessControl.objects.create(resource="feature_flag", resource_id=flag.id, team=self.team, access_level="none")
+
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/bulk_keys/",
+ {"ids": [flag.id]},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["keys"].get(str(flag.id)), "default-none-flag")
+
+ def test_member_blocked_from_bulk_keys_via_explicit_deny_on_individual_flag(self) -> None:
+ # Exercises the exclude() branch of filter_queryset_by_access_level
+ # (user_access_control.py line 937): the team-wide default is permissive
+ # (no resource-level "none" row), but this flag carries an explicit
+ # "none" ACL for the caller's membership. bulk_keys must still drop it.
+ # The existing IDOR tests all hit the filter() branch (line 931) via a
+ # team-wide deny; without this case, a regression that only handled
+ # team-wide denies would ship clean.
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+
+ other = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
+ other_membership = other.organization_memberships.get(organization=self.organization)
+
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ name="explicit deny flag",
+ key="explicit-deny-flag",
+ )
+ AccessControl.objects.create(
+ resource="feature_flag",
+ resource_id=flag.id,
+ team=self.team,
+ organization_member=other_membership,
+ access_level="none",
+ )
+
+ self.client.force_login(other)
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/bulk_keys/",
+ {"ids": [flag.id]},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertNotIn(str(flag.id), response.json()["keys"])
+
+ def test_creator_still_sees_denied_flag_in_bulk_keys(self) -> None:
+ # filter_queryset_by_access_level deliberately preserves
+ # Q(created_by=self._user) in both branches (user_access_control.py
+ # lines 931 and 937), so creators retain visibility of their own flags
+ # even with a deny ACL. This mirrors the list endpoint's contract.
+ # Pinning it so a future "harden the IDOR fix" patch can't silently
+ # strip the creator clause and diverge bulk_keys from list.
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+
+ creator = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=creator,
+ name="self-created flag",
+ key="self-created-flag",
+ )
+ AccessControl.objects.create(resource="feature_flag", resource_id=flag.id, team=self.team, access_level="none")
+
+ self.client.force_login(creator)
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/bulk_keys/",
+ {"ids": [flag.id]},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["keys"].get(str(flag.id)), "self-created-flag")
+
class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):
def test_creating_static_cohort_with_deleted_flag(self):
diff --git a/products/actions/frontend/generated/api.ts b/products/actions/frontend/generated/api.ts
index 9fdaa475742d..b2b6bfe65b63 100644
--- a/products/actions/frontend/generated/api.ts
+++ b/products/actions/frontend/generated/api.ts
@@ -267,6 +267,14 @@ export const getActionsBulkUpdateTagsCreateUrl = (projectId: string, params?: Ac
/**
* Bulk update tags on multiple objects.
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/products/actions/frontend/generated/api.zod.ts b/products/actions/frontend/generated/api.zod.ts
index b96926a669c8..6dd72341f777 100644
--- a/products/actions/frontend/generated/api.zod.ts
+++ b/products/actions/frontend/generated/api.zod.ts
@@ -1226,6 +1226,14 @@ export const ActionsPartialUpdateBody = /* @__PURE__ */ zod
/**
* Bulk update tags on multiple objects.
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.ts
index 5935ab219ab8..6e1b442f7606 100644
--- a/products/conversations/frontend/generated/api.ts
+++ b/products/conversations/frontend/generated/api.ts
@@ -453,6 +453,14 @@ export const getConversationsTicketsBulkUpdateTagsCreateUrl = (projectId: string
/**
* Bulk update tags on multiple objects.
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.ts
index a6a943e9447a..afb9ff5fb701 100644
--- a/products/conversations/frontend/generated/api.zod.ts
+++ b/products/conversations/frontend/generated/api.zod.ts
@@ -190,6 +190,14 @@ export const ConversationsTicketsPartialUpdateBody = /* @__PURE__ */ zod
/**
* Bulk update tags on multiple objects.
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/products/dashboards/frontend/generated/api.ts b/products/dashboards/frontend/generated/api.ts
index a92ce4f22fa2..4039aea62dfc 100644
--- a/products/dashboards/frontend/generated/api.ts
+++ b/products/dashboards/frontend/generated/api.ts
@@ -720,6 +720,14 @@ export const getDashboardsBulkUpdateTagsCreateUrl = (
/**
* Bulk update tags on multiple objects.
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.ts
index e2aeff250fd1..9cce9d99e980 100644
--- a/products/dashboards/frontend/generated/api.zod.ts
+++ b/products/dashboards/frontend/generated/api.zod.ts
@@ -333,6 +333,14 @@ export const DashboardsSnapshotCreateBody = /* @__PURE__ */ zod
/**
* Bulk update tags on multiple objects.
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/products/event_definitions/frontend/generated/api.ts b/products/event_definitions/frontend/generated/api.ts
index 851f8a425d76..7b8bd346c56b 100644
--- a/products/event_definitions/frontend/generated/api.ts
+++ b/products/event_definitions/frontend/generated/api.ts
@@ -166,6 +166,14 @@ export const getEventDefinitionsBulkUpdateTagsCreateUrl = (projectId: string) =>
/**
* Bulk update tags on multiple objects.
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/products/event_definitions/frontend/generated/api.zod.ts b/products/event_definitions/frontend/generated/api.zod.ts
index 1303ba11cfa7..d0db30d9eecd 100644
--- a/products/event_definitions/frontend/generated/api.zod.ts
+++ b/products/event_definitions/frontend/generated/api.zod.ts
@@ -93,6 +93,14 @@ export const EventDefinitionsPartialUpdateBody = /* @__PURE__ */ zod
/**
* Bulk update tags on multiple objects.
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index 71dd436007cf..11275be1f858 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -913,6 +913,149 @@ export interface FeatureFlagVersionResponseApi {
readonly modified_by: number | null
}
+/**
+ * * `true` - true
+ * `false` - false
+ * `STALE` - STALE
+ */
+export type ActiveEnumApi = (typeof ActiveEnumApi)[keyof typeof ActiveEnumApi]
+
+export const ActiveEnumApi = {
+ True: 'true',
+ False: 'false',
+ Stale: 'STALE',
+} as const
+
+/**
+ * * `boolean` - boolean
+ * `multivariant` - multivariant
+ * `experiment` - experiment
+ * `remote_config` - remote_config
+ */
+export type BulkDeleteFiltersTypeEnumApi =
+ (typeof BulkDeleteFiltersTypeEnumApi)[keyof typeof BulkDeleteFiltersTypeEnumApi]
+
+export const BulkDeleteFiltersTypeEnumApi = {
+ Boolean: 'boolean',
+ Multivariant: 'multivariant',
+ Experiment: 'experiment',
+ RemoteConfig: 'remote_config',
+} as const
+
+/**
+ * Allowed filter keys for bulk_delete — same shape as the list endpoint's query params.
+ */
+export interface BulkDeleteFiltersApi {
+ /** Filter by active state.
+
+ * `true` - true
+ * `false` - false
+ * `STALE` - STALE */
+ active?: ActiveEnumApi
+ /** Filter to flags created by a specific user ID. */
+ created_by_id?: number
+ /** Search by feature flag key or name (case-insensitive). */
+ search?: string
+ /** Filter by flag type.
+
+ * `boolean` - boolean
+ * `multivariant` - multivariant
+ * `experiment` - experiment
+ * `remote_config` - remote_config */
+ type?: BulkDeleteFiltersTypeEnumApi
+ /** Filter by evaluation runtime.
+
+ * `server` - Server
+ * `client` - Client
+ * `all` - All */
+ evaluation_runtime?: EvaluationRuntimeEnumApi
+ /** JSON-encoded property filter to exclude. Same shape as the list endpoint. */
+ excluded_properties?: string
+ /** Tag names to filter by. Flags carrying at least one of these tags match. */
+ tags?: string[]
+ /** When true, only matches flags with at least one evaluation context. */
+ has_evaluation_contexts?: boolean
+}
+
+export interface BulkDeleteRequestApi {
+ /** Filter criteria — same shape as the list endpoint's query params. Mutually exclusive with `ids`. Use this to bulk-delete by search/active/tags/etc. instead of supplying explicit IDs. */
+ filters?: BulkDeleteFiltersApi
+ /** Explicit feature flag IDs to soft-delete. Mutually exclusive with `filters`. */
+ ids?: number[]
+}
+
+/**
+ * * `fully_rolled_out` - fully_rolled_out
+ * `not_rolled_out` - not_rolled_out
+ * `partial` - partial
+ */
+export type RolloutStateEnumApi = (typeof RolloutStateEnumApi)[keyof typeof RolloutStateEnumApi]
+
+export const RolloutStateEnumApi = {
+ FullyRolledOut: 'fully_rolled_out',
+ NotRolledOut: 'not_rolled_out',
+ Partial: 'partial',
+} as const
+
+export interface BulkDeleteDeletedItemApi {
+ /** ID of the soft-deleted flag. */
+ id: number
+ /** The flag key at the time of deletion. */
+ key: string
+ /** Rollout state captured before deletion.
+
+ * `fully_rolled_out` - fully_rolled_out
+ * `not_rolled_out` - not_rolled_out
+ * `partial` - partial */
+ rollout_state: RolloutStateEnumApi
+ /**
+ * Variant key when a multivariate flag was fully rolled out to a single variant; otherwise null.
+ * @nullable
+ */
+ active_variant: string | null
+}
+
+export interface BulkDeleteErrorItemApi {
+ /** Feature flag ID — integer for valid inputs; the original raw value for invalid inputs. */
+ id: unknown
+ /** The flag key, when known. */
+ key?: string
+ /** Human-readable reason the flag could not be deleted. */
+ reason: string
+}
+
+/**
+ * Schema-only — referenced from ``@extend_schema(responses=...)`` to describe the wire format.
+Never instantiate this for validation or call ``.is_valid()`` / ``.errors`` on it: the
+declared ``errors`` field shadows DRF's inherited ``Serializer.errors`` ReturnDict property,
+so accessing ``serializer.errors`` would return this field descriptor instead of validation
+errors. The handler builds the response dict directly; this class exists only so drf-spectacular
+can render the response in the OpenAPI spec and downstream generated clients.
+ */
+export interface BulkDeleteResponseApi {
+ /** Flags successfully soft-deleted. */
+ deleted: BulkDeleteDeletedItemApi[]
+ /** Flags that could not be deleted, with reasons. */
+ errors: BulkDeleteErrorItemApi[]
+}
+
+export interface BulkKeysRequestApi {
+ /** Feature flag IDs to look up keys for. Strings of digits are also accepted; any other value is reported in the response `warning` field and otherwise ignored. */
+ ids?: unknown[]
+}
+
+/**
+ * Mapping of feature flag ID (as a string) to flag key, for IDs that exist in this project.
+ */
+export type BulkKeysResponseApiKeys = { [key: string]: string }
+
+export interface BulkKeysResponseApi {
+ /** Mapping of feature flag ID (as a string) to flag key, for IDs that exist in this project. */
+ keys: BulkKeysResponseApiKeys
+ /** Present when some submitted IDs were not numeric and were ignored. */
+ warning?: string
+}
+
/**
* * `add` - add
* `remove` - remove
diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.ts
index 3eb911c6f031..62f4f552b93e 100644
--- a/products/feature_flags/frontend/generated/api.ts
+++ b/products/feature_flags/frontend/generated/api.ts
@@ -10,6 +10,10 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
ActivityLogPaginatedResponseApi,
+ BulkDeleteRequestApi,
+ BulkDeleteResponseApi,
+ BulkKeysRequestApi,
+ BulkKeysResponseApi,
BulkUpdateTagsRequestApi,
BulkUpdateTagsResponseApi,
CopyFlagsRequestApi,
@@ -485,14 +489,14 @@ invalidation happens once at the end rather than per-flag.
*/
export const featureFlagsBulkDeleteCreate = async (
projectId: string,
- featureFlagApi: NonReadonly<FeatureFlagApi>,
+ bulkDeleteRequestApi?: BulkDeleteRequestApi,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getFeatureFlagsBulkDeleteCreateUrl(projectId), {
+): Promise<BulkDeleteResponseApi> => {
+ return apiMutator<BulkDeleteResponseApi>(getFeatureFlagsBulkDeleteCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(featureFlagApi),
+ body: JSON.stringify(bulkDeleteRequestApi),
})
}
@@ -506,14 +510,14 @@ Accepts a list of feature flag IDs and returns a mapping of ID to key.
*/
export const featureFlagsBulkKeysCreate = async (
projectId: string,
- featureFlagApi: NonReadonly<FeatureFlagApi>,
+ bulkKeysRequestApi?: BulkKeysRequestApi,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getFeatureFlagsBulkKeysCreateUrl(projectId), {
+): Promise<BulkKeysResponseApi> => {
+ return apiMutator<BulkKeysResponseApi>(getFeatureFlagsBulkKeysCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(featureFlagApi),
+ body: JSON.stringify(bulkKeysRequestApi),
})
}
@@ -524,6 +528,14 @@ export const getFeatureFlagsBulkUpdateTagsCreateUrl = (projectId: string) => {
/**
* Bulk update tags on multiple objects.
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.ts
index 01f9ba3fa232..5f4c26552f40 100644
--- a/products/feature_flags/frontend/generated/api.zod.ts
+++ b/products/feature_flags/frontend/generated/api.zod.ts
@@ -990,167 +990,81 @@ Returns same format as bulk_delete for UI compatibility.
Uses bulk operations for efficiency: database updates are batched and cache
invalidation happens once at the end rather than per-flag.
*/
-export const featureFlagsBulkDeleteCreateBodyKeyMax = 400
-export const featureFlagsBulkDeleteCreateBodyVersionDefault = 0
-export const featureFlagsBulkDeleteCreateBodyShouldCreateUsageDashboardDefault = true
-
-export const FeatureFlagsBulkDeleteCreateBody = /* @__PURE__ */ zod
- .object({
- name: zod
- .string()
- .optional()
- .describe('contains the description for the flag (field name `name` is kept for backwards-compatibility)'),
- key: zod.string().max(featureFlagsBulkDeleteCreateBodyKeyMax),
- filters: zod.record(zod.string(), zod.unknown()).optional(),
- deleted: zod.boolean().optional(),
- active: zod.boolean().optional(),
- created_at: zod.iso.datetime({ offset: true }).optional(),
- version: zod.number().default(featureFlagsBulkDeleteCreateBodyVersionDefault),
- ensure_experience_continuity: zod.boolean().nullish(),
- rollback_conditions: zod.unknown().optional(),
- performed_rollback: zod.boolean().nullish(),
- tags: zod.array(zod.unknown()).optional(),
- evaluation_contexts: zod.array(zod.unknown()).optional(),
- analytics_dashboards: zod.array(zod.number()).optional(),
- has_enriched_analytics: zod.boolean().nullish(),
- creation_context: zod
- .enum([
- 'feature_flags',
- 'experiments',
- 'surveys',
- 'early_access_features',
- 'web_experiments',
- 'product_tours',
- ])
- .describe(
- '\* `feature_flags` - feature_flags\n\* `experiments` - experiments\n\* `surveys` - surveys\n\* `early_access_features` - early_access_features\n\* `web_experiments` - web_experiments\n\* `product_tours` - product_tours'
- )
- .optional()
- .describe(
- "Indicates the origin product of the feature flag. Choices: 'feature_flags', 'experiments', 'surveys', 'early_access_features', 'web_experiments', 'product_tours'.\n\n\* `feature_flags` - feature_flags\n\* `experiments` - experiments\n\* `surveys` - surveys\n\* `early_access_features` - early_access_features\n\* `web_experiments` - web_experiments\n\* `product_tours` - product_tours"
- ),
- is_remote_configuration: zod.boolean().nullish(),
- has_encrypted_payloads: zod.boolean().nullish(),
- evaluation_runtime: zod
- .union([
- zod
- .enum(['server', 'client', 'all'])
- .describe('\* `server` - Server\n\* `client` - Client\n\* `all` - All'),
- zod.enum(['']),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Specifies where this feature flag should be evaluated\n\n\* `server` - Server\n\* `client` - Client\n\* `all` - All'
- ),
- bucketing_identifier: zod
- .union([
- zod
- .enum(['distinct_id', 'device_id'])
- .describe('\* `distinct_id` - User ID (default)\n\* `device_id` - Device ID'),
- zod.enum(['']),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Identifier used for bucketing users into rollout and variants\n\n\* `distinct_id` - User ID (default)\n\* `device_id` - Device ID'
- ),
- last_called_at: zod.iso
- .datetime({ offset: true })
- .nullish()
- .describe('Last time this feature flag was called (from $feature_flag_called events)'),
- _create_in_folder: zod.string().optional(),
- _should_create_usage_dashboard: zod
- .boolean()
- .default(featureFlagsBulkDeleteCreateBodyShouldCreateUsageDashboardDefault),
- })
- .describe('Serializer mixin that handles tags for objects.')
+export const FeatureFlagsBulkDeleteCreateBody = /* @__PURE__ */ zod.object({
+ filters: zod
+ .object({
+ active: zod
+ .enum(['true', 'false', 'STALE'])
+ .describe('\* `true` - true\n\* `false` - false\n\* `STALE` - STALE')
+ .optional()
+ .describe('Filter by active state.\n\n\* `true` - true\n\* `false` - false\n\* `STALE` - STALE'),
+ created_by_id: zod.number().optional().describe('Filter to flags created by a specific user ID.'),
+ search: zod.string().optional().describe('Search by feature flag key or name (case-insensitive).'),
+ type: zod
+ .enum(['boolean', 'multivariant', 'experiment', 'remote_config'])
+ .describe(
+ '\* `boolean` - boolean\n\* `multivariant` - multivariant\n\* `experiment` - experiment\n\* `remote_config` - remote_config'
+ )
+ .optional()
+ .describe(
+ 'Filter by flag type.\n\n\* `boolean` - boolean\n\* `multivariant` - multivariant\n\* `experiment` - experiment\n\* `remote_config` - remote_config'
+ ),
+ evaluation_runtime: zod
+ .enum(['server', 'client', 'all'])
+ .describe('\* `server` - Server\n\* `client` - Client\n\* `all` - All')
+ .optional()
+ .describe(
+ 'Filter by evaluation runtime.\n\n\* `server` - Server\n\* `client` - Client\n\* `all` - All'
+ ),
+ excluded_properties: zod
+ .string()
+ .optional()
+ .describe('JSON-encoded property filter to exclude. Same shape as the list endpoint.'),
+ tags: zod
+ .array(zod.string())
+ .optional()
+ .describe('Tag names to filter by. Flags carrying at least one of these tags match.'),
+ has_evaluation_contexts: zod
+ .boolean()
+ .optional()
+ .describe('When true, only matches flags with at least one evaluation context.'),
+ })
+ .describe("Allowed filter keys for bulk_delete — same shape as the list endpoint's query params.")
+ .optional()
+ .describe(
+ "Filter criteria — same shape as the list endpoint's query params. Mutually exclusive with `ids`. Use this to bulk-delete by search\/active\/tags\/etc. instead of supplying explicit IDs."
+ ),
+ ids: zod
+ .array(zod.number().min(1))
+ .optional()
+ .describe('Explicit feature flag IDs to soft-delete. Mutually exclusive with `filters`.'),
+})
/**
* Get feature flag keys by IDs.
Accepts a list of feature flag IDs and returns a mapping of ID to key.
*/
-export const featureFlagsBulkKeysCreateBodyKeyMax = 400
-
-export const featureFlagsBulkKeysCreateBodyVersionDefault = 0
-export const featureFlagsBulkKeysCreateBodyShouldCreateUsageDashboardDefault = true
-
-export const FeatureFlagsBulkKeysCreateBody = /* @__PURE__ */ zod
- .object({
- name: zod
- .string()
- .optional()
- .describe('contains the description for the flag (field name `name` is kept for backwards-compatibility)'),
- key: zod.string().max(featureFlagsBulkKeysCreateBodyKeyMax),
- filters: zod.record(zod.string(), zod.unknown()).optional(),
- deleted: zod.boolean().optional(),
- active: zod.boolean().optional(),
- created_at: zod.iso.datetime({ offset: true }).optional(),
- version: zod.number().default(featureFlagsBulkKeysCreateBodyVersionDefault),
- ensure_experience_continuity: zod.boolean().nullish(),
- rollback_conditions: zod.unknown().optional(),
- performed_rollback: zod.boolean().nullish(),
- tags: zod.array(zod.unknown()).optional(),
- evaluation_contexts: zod.array(zod.unknown()).optional(),
- analytics_dashboards: zod.array(zod.number()).optional(),
- has_enriched_analytics: zod.boolean().nullish(),
- creation_context: zod
- .enum([
- 'feature_flags',
- 'experiments',
- 'surveys',
- 'early_access_features',
- 'web_experiments',
- 'product_tours',
- ])
- .describe(
- '\* `feature_flags` - feature_flags\n\* `experiments` - experiments\n\* `surveys` - surveys\n\* `early_access_features` - early_access_features\n\* `web_experiments` - web_experiments\n\* `product_tours` - product_tours'
- )
- .optional()
- .describe(
- "Indicates the origin product of the feature flag. Choices: 'feature_flags', 'experiments', 'surveys', 'early_access_features', 'web_experiments', 'product_tours'.\n\n\* `feature_flags` - feature_flags\n\* `experiments` - experiments\n\* `surveys` - surveys\n\* `early_access_features` - early_access_features\n\* `web_experiments` - web_experiments\n\* `product_tours` - product_tours"
- ),
- is_remote_configuration: zod.boolean().nullish(),
- has_encrypted_payloads: zod.boolean().nullish(),
- evaluation_runtime: zod
- .union([
- zod
- .enum(['server', 'client', 'all'])
- .describe('\* `server` - Server\n\* `client` - Client\n\* `all` - All'),
- zod.enum(['']),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Specifies where this feature flag should be evaluated\n\n\* `server` - Server\n\* `client` - Client\n\* `all` - All'
- ),
- bucketing_identifier: zod
- .union([
- zod
- .enum(['distinct_id', 'device_id'])
- .describe('\* `distinct_id` - User ID (default)\n\* `device_id` - Device ID'),
- zod.enum(['']),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Identifier used for bucketing users into rollout and variants\n\n\* `distinct_id` - User ID (default)\n\* `device_id` - Device ID'
- ),
- last_called_at: zod.iso
- .datetime({ offset: true })
- .nullish()
- .describe('Last time this feature flag was called (from $feature_flag_called events)'),
- _create_in_folder: zod.string().optional(),
- _should_create_usage_dashboard: zod
- .boolean()
- .default(featureFlagsBulkKeysCreateBodyShouldCreateUsageDashboardDefault),
- })
- .describe('Serializer mixin that handles tags for objects.')
+export const FeatureFlagsBulkKeysCreateBody = /* @__PURE__ */ zod.object({
+ ids: zod
+ .array(zod.unknown())
+ .optional()
+ .describe(
+ 'Feature flag IDs to look up keys for. Strings of digits are also accepted; any other value is reported in the response `warning` field and otherwise ignored.'
+ ),
+})
/**
* Bulk update tags on multiple objects.
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index 0e027a019404..608566e45437 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -126,13 +126,49 @@ tools:
enabled: false
feature-flags-bulk-delete-create:
operation: feature_flags_bulk_delete_create
- enabled: false
+ enabled: true
+ scopes:
+ - feature_flag:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: false
+ title: Bulk delete feature flags
+ description: >
+ Soft-delete multiple feature flags in one call. Provide either `ids` (explicit list of flag IDs) OR
+ `filters` (same shape as the list endpoint, e.g., search, active, type, tags), but not both. WARNING:
+ `filters` can match an unbounded number of flags. Preview matches via the list endpoint before calling this
+ with `filters`, and prefer explicit `ids` whenever the user has named specific flags. Flags linked to active
+ experiments, early access features, or that other flags depend on are skipped and reported in `errors`.
+ Returns `deleted` (with each flag's rollout state at deletion time) and `errors` arrays.
feature-flags-bulk-keys-create:
operation: feature_flags_bulk_keys_create
- enabled: false
+ enabled: true
+ scopes:
+ - feature_flag:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Look up feature flag keys by ID
+ description: >
+ Resolve feature flag IDs to their string keys in one call. Pass `ids` as a list of integer flag IDs. Returns
+ `keys` as a mapping of stringified ID to key for the IDs that exist in this project. Useful when you have
+ IDs from another tool (e.g., dependent flags, scheduled changes) and need the keys for downstream calls.
feature-flags-bulk-update-tags-create:
operation: feature_flags_bulk_update_tags_create
- enabled: false
+ enabled: true
+ scopes:
+ - feature_flag:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Bulk update tags on feature flags
+ description: >
+ Add, remove, or replace tags on multiple feature flags in one call. Provide `ids` (up to 500), an `action`
+ ('add', 'remove', or 'set'), and a list of tag names. Returns `updated` (per-flag final tag list) and
+ `skipped` (flags missing or without edit permission, with reason).
feature-flags-copy-flags-create:
operation: feature_flags_copy_flags_create
enabled: true
diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.ts
index add35c543128..f01683b27bc5 100644
--- a/products/product_analytics/frontend/generated/api.ts
+++ b/products/product_analytics/frontend/generated/api.ts
@@ -730,6 +730,14 @@ export const getInsightsBulkUpdateTagsCreateUrl = (projectId: string, params?: I
/**
* Bulk update tags on multiple objects.
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/products/product_analytics/frontend/generated/api.zod.ts b/products/product_analytics/frontend/generated/api.zod.ts
index b92ab02bc53f..e00ade4c8f20 100644
--- a/products/product_analytics/frontend/generated/api.zod.ts
+++ b/products/product_analytics/frontend/generated/api.zod.ts
@@ -224,6 +224,14 @@ export const InsightsSuggestionsCreateBody = /* @__PURE__ */ zod
/**
* Bulk update tags on multiple objects.
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
Accepts:
- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 2494ddf1a016..8288da54a906 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2215,6 +2215,51 @@
"readOnlyHint": true
}
},
+ "feature-flags-bulk-delete-create": {
+ "description": "Soft-delete multiple feature flags in one call. Provide either `ids` (explicit list of flag IDs) OR `filters` (same shape as the list endpoint, e.g., search, active, type, tags), but not both. WARNING: `filters` can match an unbounded number of flags. Preview matches via the list endpoint before calling this with `filters`, and prefer explicit `ids` whenever the user has named specific flags. Flags linked to active experiments, early access features, or that other flags depend on are skipped and reported in `errors`. Returns `deleted` (with each flag's rollout state at deletion time) and `errors` arrays.",
+ "category": "Feature flags",
+ "feature": "flags",
+ "summary": "Bulk delete feature flags",
+ "title": "Bulk delete feature flags",
+ "required_scopes": ["feature_flag:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "feature-flags-bulk-keys-create": {
+ "description": "Resolve feature flag IDs to their string keys in one call. Pass `ids` as a list of integer flag IDs. Returns `keys` as a mapping of stringified ID to key for the IDs that exist in this project. Useful when you have IDs from another tool (e.g., dependent flags, scheduled changes) and need the keys for downstream calls.",
+ "category": "Feature flags",
+ "feature": "flags",
+ "summary": "Look up feature flag keys by ID",
+ "title": "Look up feature flag keys by ID",
+ "required_scopes": ["feature_flag:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "feature-flags-bulk-update-tags-create": {
+ "description": "Add, remove, or replace tags on multiple feature flags in one call. Provide `ids` (up to 500), an `action` ('add', 'remove', or 'set'), and a list of tag names. Returns `updated` (per-flag final tag list) and `skipped` (flags missing or without edit permission, with reason).",
+ "category": "Feature flags",
+ "feature": "flags",
+ "summary": "Bulk update tags on feature flags",
+ "title": "Bulk update tags on feature flags",
+ "required_scopes": ["feature_flag:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"feature-flags-copy-flags-create": {
"description": "Copy a feature flag from one project to other projects within the same organization. Provide the flag key, source project ID, and a list of target project IDs. Optionally copy scheduled changes with copy_schedule. Returns lists of successful and failed copies.",
"category": "Feature flags",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 2dc904c491d9..048b662343aa 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2483,6 +2483,51 @@
"readOnlyHint": true
}
},
+ "feature-flags-bulk-delete-create": {
+ "description": "Soft-delete multiple feature flags in one call. Provide either `ids` (explicit list of flag IDs) OR `filters` (same shape as the list endpoint, e.g., search, active, type, tags), but not both. WARNING: `filters` can match an unbounded number of flags. Preview matches via the list endpoint before calling this with `filters`, and prefer explicit `ids` whenever the user has named specific flags. Flags linked to active experiments, early access features, or that other flags depend on are skipped and reported in `errors`. Returns `deleted` (with each flag's rollout state at deletion time) and `errors` arrays.",
+ "category": "Feature flags",
+ "feature": "flags",
+ "summary": "Bulk delete feature flags",
+ "title": "Bulk delete feature flags",
+ "required_scopes": ["feature_flag:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "feature-flags-bulk-keys-create": {
+ "description": "Resolve feature flag IDs to their string keys in one call. Pass `ids` as a list of integer flag IDs. Returns `keys` as a mapping of stringified ID to key for the IDs that exist in this project. Useful when you have IDs from another tool (e.g., dependent flags, scheduled changes) and need the keys for downstream calls.",
+ "category": "Feature flags",
+ "feature": "flags",
+ "summary": "Look up feature flag keys by ID",
+ "title": "Look up feature flag keys by ID",
+ "required_scopes": ["feature_flag:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "feature-flags-bulk-update-tags-create": {
+ "description": "Add, remove, or replace tags on multiple feature flags in one call. Provide `ids` (up to 500), an `action` ('add', 'remove', or 'set'), and a list of tag names. Returns `updated` (per-flag final tag list) and `skipped` (flags missing or without edit permission, with reason).",
+ "category": "Feature flags",
+ "feature": "flags",
+ "summary": "Bulk update tags on feature flags",
+ "title": "Bulk update tags on feature flags",
+ "required_scopes": ["feature_flag:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"feature-flags-copy-flags-create": {
"description": "Copy a feature flag from one project to other projects within the same organization. Provide the flag key, source project ID, and a list of target project IDs. Optionally copy scheduled changes with copy_schedule. Returns lists of successful and failed copies.",
"category": "Feature flags",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 260f579df923..e689e1830658 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -1265,6 +1265,20 @@ export namespace Schemas {
breakpoints: ActiveBreakpoint[];
}
+ /**
+ * * `true` - true
+ * `false` - false
+ * `STALE` - STALE
+ */
+ export type ActiveEnum = typeof ActiveEnum[keyof typeof ActiveEnum];
+
+
+ export const ActiveEnum = {
+ True: 'true',
+ False: 'false',
+ Stale: 'STALE',
+ } as const;
+
export interface ActivityLog {
readonly id: string;
user: UserBasic;
@@ -6469,6 +6483,134 @@ export namespace Schemas {
DeviceId: 'device_id',
} as const;
+ /**
+ * * `fully_rolled_out` - fully_rolled_out
+ * `not_rolled_out` - not_rolled_out
+ * `partial` - partial
+ */
+ export type RolloutStateEnum = typeof RolloutStateEnum[keyof typeof RolloutStateEnum];
+
+
+ export const RolloutStateEnum = {
+ FullyRolledOut: 'fully_rolled_out',
+ NotRolledOut: 'not_rolled_out',
+ Partial: 'partial',
+ } as const;
+
+ export interface BulkDeleteDeletedItem {
+ /** ID of the soft-deleted flag. */
+ id: number;
+ /** The flag key at the time of deletion. */
+ key: string;
+ /** Rollout state captured before deletion.
+
+ * `fully_rolled_out` - fully_rolled_out
+ * `not_rolled_out` - not_rolled_out
+ * `partial` - partial */
+ rollout_state: RolloutStateEnum;
+ /**
+ * Variant key when a multivariate flag was fully rolled out to a single variant; otherwise null.
+ * @nullable
+ */
+ active_variant: string | null;
+ }
+
+ export interface BulkDeleteErrorItem {
+ /** Feature flag ID — integer for valid inputs; the original raw value for invalid inputs. */
+ id: unknown;
+ /** The flag key, when known. */
+ key?: string;
+ /** Human-readable reason the flag could not be deleted. */
+ reason: string;
+ }
+
+ /**
+ * * `boolean` - boolean
+ * `multivariant` - multivariant
+ * `experiment` - experiment
+ * `remote_config` - remote_config
+ */
+ export type BulkDeleteFiltersTypeEnum = typeof BulkDeleteFiltersTypeEnum[keyof typeof BulkDeleteFiltersTypeEnum];
+
+
+ export const BulkDeleteFiltersTypeEnum = {
+ Boolean: 'boolean',
+ Multivariant: 'multivariant',
+ Experiment: 'experiment',
+ RemoteConfig: 'remote_config',
+ } as const;
+
+ /**
+ * * `server` - Server
+ * `client` - Client
+ * `all` - All
+ */
+ export type EvaluationRuntimeEnum = typeof EvaluationRuntimeEnum[keyof typeof EvaluationRuntimeEnum];
+
+
+ export const EvaluationRuntimeEnum = {
+ Server: 'server',
+ Client: 'client',
+ All: 'all',
+ } as const;
+
+ /**
+ * Allowed filter keys for bulk_delete — same shape as the list endpoint's query params.
+ */
+ export interface BulkDeleteFilters {
+ /** Filter by active state.
+
+ * `true` - true
+ * `false` - false
+ * `STALE` - STALE */
+ active?: ActiveEnum;
+ /** Filter to flags created by a specific user ID. */
+ created_by_id?: number;
+ /** Search by feature flag key or name (case-insensitive). */
+ search?: string;
+ /** Filter by flag type.
+
+ * `boolean` - boolean
+ * `multivariant` - multivariant
+ * `experiment` - experiment
+ * `remote_config` - remote_config */
+ type?: BulkDeleteFiltersTypeEnum;
+ /** Filter by evaluation runtime.
+
+ * `server` - Server
+ * `client` - Client
+ * `all` - All */
+ evaluation_runtime?: EvaluationRuntimeEnum;
+ /** JSON-encoded property filter to exclude. Same shape as the list endpoint. */
+ excluded_properties?: string;
+ /** Tag names to filter by. Flags carrying at least one of these tags match. */
+ tags?: string[];
+ /** When true, only matches flags with at least one evaluation context. */
+ has_evaluation_contexts?: boolean;
+ }
+
+ export interface BulkDeleteRequest {
+ /** Filter criteria — same shape as the list endpoint's query params. Mutually exclusive with `ids`. Use this to bulk-delete by search/active/tags/etc. instead of supplying explicit IDs. */
+ filters?: BulkDeleteFilters;
+ /** Explicit feature flag IDs to soft-delete. Mutually exclusive with `filters`. */
+ ids?: number[];
+ }
+
+ /**
+ * Schema-only — referenced from ``@extend_schema(responses=...)`` to describe the wire format.
+ Never instantiate this for validation or call ``.is_valid()`` / ``.errors`` on it: the
+ declared ``errors`` field shadows DRF's inherited ``Serializer.errors`` ReturnDict property,
+ so accessing ``serializer.errors`` would return this field descriptor instead of validation
+ errors. The handler builds the response dict directly; this class exists only so drf-spectacular
+ can render the response in the OpenAPI spec and downstream generated clients.
+ */
+ export interface BulkDeleteResponse {
+ /** Flags successfully soft-deleted. */
+ deleted: BulkDeleteDeletedItem[];
+ /** Flags that could not be deleted, with reasons. */
+ errors: BulkDeleteErrorItem[];
+ }
+
export interface BulkIntervieweeContextItem {
/**
* Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids.
@@ -6496,6 +6638,23 @@ export namespace Schemas {
skipped_identifiers: string[];
}
+ export interface BulkKeysRequest {
+ /** Feature flag IDs to look up keys for. Strings of digits are also accepted; any other value is reported in the response `warning` field and otherwise ignored. */
+ ids?: unknown[];
+ }
+
+ /**
+ * Mapping of feature flag ID (as a string) to flag key, for IDs that exist in this project.
+ */
+ export type BulkKeysResponseKeys = {[key: string]: string};
+
+ export interface BulkKeysResponse {
+ /** Mapping of feature flag ID (as a string) to flag key, for IDs that exist in this project. */
+ keys: BulkKeysResponseKeys;
+ /** Present when some submitted IDs were not numeric and were ignored. */
+ warning?: string;
+ }
+
export interface BulkNotificationIdsRequest {
/**
* UUIDs of notification events to mark in bulk (max 500). Events the user is not a recipient of are silently skipped.
@@ -13052,20 +13211,6 @@ export namespace Schemas {
*/
export type EarlyAccessFeaturePayload = { [key: string]: unknown };
- /**
- * * `server` - Server
- * `client` - Client
- * `all` - All
- */
- export type EvaluationRuntimeEnum = typeof EvaluationRuntimeEnum[keyof typeof EvaluationRuntimeEnum];
-
-
- export const EvaluationRuntimeEnum = {
- Server: 'server',
- Client: 'client',
- All: 'all',
- } as const;
-
export type MinimalFeatureFlagFilters = { [key: string]: unknown };
export interface MinimalFeatureFlag {
diff --git a/services/mcp/src/generated/feature_flags/api.ts b/services/mcp/src/generated/feature_flags/api.ts
index abaed6046253..46078e00b3f6 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 18 enabled ops
+ * PostHog API - MCP 21 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -801,6 +801,138 @@ export const FeatureFlagsTestEvaluationCreateBody = /* @__PURE__ */ zod.object({
.describe('Groups for feature flag evaluation (JSON object, defaults to empty dict)'),
})
+/**
+ * Bulk delete feature flags by filter criteria or explicit IDs.
+
+Accepts either:
+- {"filters": {...}} - Same filter params as list endpoint (search, active, type, etc.)
+- {"ids": [...]} - Explicit list of flag IDs (no limit)
+
+Returns same format as bulk_delete for UI compatibility.
+
+Uses bulk operations for efficiency: database updates are batched and cache
+invalidation happens once at the end rather than per-flag.
+ */
+export const FeatureFlagsBulkDeleteCreateParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const FeatureFlagsBulkDeleteCreateBody = /* @__PURE__ */ zod.object({
+ filters: zod
+ .object({
+ active: zod
+ .enum(['true', 'false', 'STALE'])
+ .describe('* `true` - true\n* `false` - false\n* `STALE` - STALE')
+ .optional()
+ .describe('Filter by active state.\n\n* `true` - true\n* `false` - false\n* `STALE` - STALE'),
+ created_by_id: zod.number().optional().describe('Filter to flags created by a specific user ID.'),
+ search: zod.string().optional().describe('Search by feature flag key or name (case-insensitive).'),
+ type: zod
+ .enum(['boolean', 'multivariant', 'experiment', 'remote_config'])
+ .describe(
+ '* `boolean` - boolean\n* `multivariant` - multivariant\n* `experiment` - experiment\n* `remote_config` - remote_config'
+ )
+ .optional()
+ .describe(
+ 'Filter by flag type.\n\n* `boolean` - boolean\n* `multivariant` - multivariant\n* `experiment` - experiment\n* `remote_config` - remote_config'
+ ),
+ evaluation_runtime: zod
+ .enum(['server', 'client', 'all'])
+ .describe('* `server` - Server\n* `client` - Client\n* `all` - All')
+ .optional()
+ .describe('Filter by evaluation runtime.\n\n* `server` - Server\n* `client` - Client\n* `all` - All'),
+ excluded_properties: zod
+ .string()
+ .optional()
+ .describe('JSON-encoded property filter to exclude. Same shape as the list endpoint.'),
+ tags: zod
+ .array(zod.string())
+ .optional()
+ .describe('Tag names to filter by. Flags carrying at least one of these tags match.'),
+ has_evaluation_contexts: zod
+ .boolean()
+ .optional()
+ .describe('When true, only matches flags with at least one evaluation context.'),
+ })
+ .describe("Allowed filter keys for bulk_delete — same shape as the list endpoint's query params.")
+ .optional()
+ .describe(
+ "Filter criteria — same shape as the list endpoint's query params. Mutually exclusive with `ids`. Use this to bulk-delete by search/active/tags/etc. instead of supplying explicit IDs."
+ ),
+ ids: zod
+ .array(zod.number().min(1))
+ .optional()
+ .describe('Explicit feature flag IDs to soft-delete. Mutually exclusive with `filters`.'),
+})
+
+/**
+ * Get feature flag keys by IDs.
+Accepts a list of feature flag IDs and returns a mapping of ID to key.
+ */
+export const FeatureFlagsBulkKeysCreateParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const FeatureFlagsBulkKeysCreateBody = /* @__PURE__ */ zod.object({
+ ids: zod
+ .array(zod.unknown())
+ .optional()
+ .describe(
+ 'Feature flag IDs to look up keys for. Strings of digits are also accepted; any other value is reported in the response `warning` field and otherwise ignored.'
+ ),
+})
+
+/**
+ * Bulk update tags on multiple objects.
+
+PAT access: this action has no ``required_scopes=`` on the decorator —
+inheriting viewsets must add ``"bulk_update_tags"`` to their
+``scope_object_write_actions`` list to accept personal API keys.
+Without that opt-in, ``APIScopePermission`` rejects PAT requests with
+"This action does not support personal API key access". Done per-viewset
+so granting ``<scope>:write`` for one resource doesn't leak access to
+sibling resources that share this mixin.
+
+Accepts:
+- {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
+
+Actions:
+- "add": Add tags to existing tags on each object
+- "remove": Remove specific tags from each object
+- "set": Replace all tags on each object with the provided list
+ */
+export const FeatureFlagsBulkUpdateTagsCreateParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const featureFlagsBulkUpdateTagsCreateBodyIdsMax = 500
+
+export const FeatureFlagsBulkUpdateTagsCreateBody = /* @__PURE__ */ zod.object({
+ ids: zod
+ .array(zod.number())
+ .max(featureFlagsBulkUpdateTagsCreateBodyIdsMax)
+ .describe('List of object IDs to update tags on.'),
+ action: zod
+ .enum(['add', 'remove', 'set'])
+ .describe('* `add` - add\n* `remove` - remove\n* `set` - set')
+ .describe(
+ "'add' merges with existing tags, 'remove' deletes specific tags, 'set' replaces all tags.\n\n* `add` - add\n* `remove` - remove\n* `set` - set"
+ ),
+ tags: zod.array(zod.string()).describe('Tag names to add, remove, or set.'),
+})
+
/**
* Create, read, update and delete feature flags. [See docs](https://posthog.com/docs/feature-flags) for more information on feature flags.
diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.ts
index 925839009cf3..1adafdb91dec 100644
--- a/services/mcp/src/tools/generated/feature_flags.ts
+++ b/services/mcp/src/tools/generated/feature_flags.ts
@@ -5,6 +5,9 @@ import type { Schemas } from '@/api/generated'
import {
FeatureFlagsActivityRetrieveParams,
FeatureFlagsActivityRetrieveQueryParams,
+ FeatureFlagsBulkDeleteCreateBody,
+ FeatureFlagsBulkKeysCreateBody,
+ FeatureFlagsBulkUpdateTagsCreateBody,
FeatureFlagsCopyFlagsCreateBody,
FeatureFlagsCreateBody,
FeatureFlagsDependentFlagsListParams,
@@ -180,6 +183,81 @@ const featureFlagsActivityRetrieve = (): ToolBase<
},
})
+const FeatureFlagsBulkDeleteCreateSchema = FeatureFlagsBulkDeleteCreateBody
+
+const featureFlagsBulkDeleteCreate = (): ToolBase<
+ typeof FeatureFlagsBulkDeleteCreateSchema,
+ Schemas.BulkDeleteResponse
+> => ({
+ name: 'feature-flags-bulk-delete-create',
+ schema: FeatureFlagsBulkDeleteCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof FeatureFlagsBulkDeleteCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.filters !== undefined) {
+ body['filters'] = params.filters
+ }
+ if (params.ids !== undefined) {
+ body['ids'] = params.ids
+ }
+ const result = await context.api.request<Schemas.BulkDeleteResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/bulk_delete/`,
+ body,
+ })
+ return result
+ },
+})
+
+const FeatureFlagsBulkKeysCreateSchema = FeatureFlagsBulkKeysCreateBody
+
+const featureFlagsBulkKeysCreate = (): ToolBase<typeof FeatureFlagsBulkKeysCreateSchema, Schemas.BulkKeysResponse> => ({
+ name: 'feature-flags-bulk-keys-create',
+ schema: FeatureFlagsBulkKeysCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof FeatureFlagsBulkKeysCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.ids !== undefined) {
+ body['ids'] = params.ids
+ }
+ const result = await context.api.request<Schemas.BulkKeysResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/bulk_keys/`,
+ body,
+ })
+ return result
+ },
+})
+
+const FeatureFlagsBulkUpdateTagsCreateSchema = FeatureFlagsBulkUpdateTagsCreateBody
+
+const featureFlagsBulkUpdateTagsCreate = (): ToolBase<
+ typeof FeatureFlagsBulkUpdateTagsCreateSchema,
+ Schemas.BulkUpdateTagsResponse
+> => ({
+ name: 'feature-flags-bulk-update-tags-create',
+ schema: FeatureFlagsBulkUpdateTagsCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof FeatureFlagsBulkUpdateTagsCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.ids !== undefined) {
+ body['ids'] = params.ids
+ }
+ if (params.action !== undefined) {
+ body['action'] = params.action
+ }
+ if (params.tags !== undefined) {
+ body['tags'] = params.tags
+ }
+ const result = await context.api.request<Schemas.BulkUpdateTagsResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/bulk_update_tags/`,
+ body,
+ })
+ return result
+ },
+})
+
const FeatureFlagsCopyFlagsCreateSchema = FeatureFlagsCopyFlagsCreateBody
const featureFlagsCopyFlagsCreate = (): ToolBase<
@@ -548,6 +626,9 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'feature-flag-get-all': featureFlagGetAll,
'feature-flag-get-definition': featureFlagGetDefinition,
'feature-flags-activity-retrieve': featureFlagsActivityRetrieve,
+ 'feature-flags-bulk-delete-create': featureFlagsBulkDeleteCreate,
+ 'feature-flags-bulk-keys-create': featureFlagsBulkKeysCreate,
+ 'feature-flags-bulk-update-tags-create': featureFlagsBulkUpdateTagsCreate,
'feature-flags-copy-flags-create': featureFlagsCopyFlagsCreate,
'feature-flags-dependent-flags-retrieve': featureFlagsDependentFlagsRetrieve,
'feature-flags-evaluation-reasons-retrieve': featureFlagsEvaluationReasonsRetrieve,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/feature-flags-bulk-delete-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/feature-flags-bulk-delete-create.json
new file mode 100644
index 000000000000..e15501ab2c55
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/feature-flags-bulk-delete-create.json
@@ -0,0 +1,58 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "filters": {
+ "description": "Filter criteria — same shape as the list endpoint's query params. Mutually exclusive with `ids`. Use this to bulk-delete by search/active/tags/etc. instead of supplying explicit IDs.",
+ "properties": {
+ "active": {
+ "description": "Filter by active state.\n\n* `true` - true\n* `false` - false\n* `STALE` - STALE",
+ "enum": ["true", "false", "STALE"],
+ "type": "string"
+ },
+ "created_by_id": {
+ "description": "Filter to flags created by a specific user ID.",
+ "type": "number"
+ },
+ "evaluation_runtime": {
+ "description": "Filter by evaluation runtime.\n\n* `server` - Server\n* `client` - Client\n* `all` - All",
+ "enum": ["server", "client", "all"],
+ "type": "string"
+ },
+ "excluded_properties": {
+ "description": "JSON-encoded property filter to exclude. Same shape as the list endpoint.",
+ "type": "string"
+ },
+ "has_evaluation_contexts": {
+ "description": "When true, only matches flags with at least one evaluation context.",
+ "type": "boolean"
+ },
+ "search": {
+ "description": "Search by feature flag key or name (case-insensitive).",
+ "type": "string"
+ },
+ "tags": {
+ "description": "Tag names to filter by. Flags carrying at least one of these tags match.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "type": {
+ "description": "Filter by flag type.\n\n* `boolean` - boolean\n* `multivariant` - multivariant\n* `experiment` - experiment\n* `remote_config` - remote_config",
+ "enum": ["boolean", "multivariant", "experiment", "remote_config"],
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "ids": {
+ "description": "Explicit feature flag IDs to soft-delete. Mutually exclusive with `filters`.",
+ "items": {
+ "minimum": 1,
+ "type": "number"
+ },
+ "type": "array"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/feature-flags-bulk-keys-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/feature-flags-bulk-keys-create.json
new file mode 100644
index 000000000000..cd8e7c4e7546
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/feature-flags-bulk-keys-create.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "ids": {
+ "description": "Feature flag IDs to look up keys for. Strings of digits are also accepted; any other value is reported in the response `warning` field and otherwise ignored.",
+ "items": {},
+ "type": "array"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/feature-flags-bulk-update-tags-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/feature-flags-bulk-update-tags-create.json
new file mode 100644
index 000000000000..8edf81559f24
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/feature-flags-bulk-update-tags-create.json
@@ -0,0 +1,27 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "action": {
+ "description": "'add' merges with existing tags, 'remove' deletes specific tags, 'set' replaces all tags.\n\n* `add` - add\n* `remove` - remove\n* `set` - set",
+ "enum": ["add", "remove", "set"],
+ "type": "string"
+ },
+ "ids": {
+ "description": "List of object IDs to update tags on.",
+ "items": {
+ "type": "number"
+ },
+ "maxItems": 500,
+ "type": "array"
+ },
+ "tags": {
+ "description": "Tag names to add, remove, or set.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["ids", "action", "tags"],
+ "type": "object"
+}