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(feature-flags): scope my_flags to specific flag keys (#87407)

posthog[bot]652f3e4342ec
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 270f79e6bd95..abcbe33a03fb 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -2487,10 +2487,6 @@ class GroupsJSONField(serializers.CharField):
raise serializers.ValidationError("Invalid JSON in groups parameter")
-class MyFlagsQuerySerializer(serializers.Serializer):
- groups = GroupsJSONField()
-
-
class FlagKeysField(serializers.ListField):
"""
ListField that also accepts a single JSON-array string.
@@ -2520,6 +2516,18 @@ class FlagKeysField(serializers.ListField):
return super().to_internal_value(data)
+class MyFlagsQuerySerializer(serializers.Serializer):
+ groups = GroupsJSONField()
+ flag_keys = FlagKeysField(
+ help_text=(
+ "Optional list of flag keys to scope the response to. When omitted, every flag in the project is "
+ "returned with its evaluated value, which can be a very large payload on projects with many flags. "
+ "Pass the specific flag(s) you want to check to keep the response small. Accepts either repeated "
+ 'query params (flag_keys=a&flag_keys=b) or a JSON array string (flag_keys=["a","b"]).'
+ ),
+ )
+
+
class EvaluationReasonsQuerySerializer(serializers.Serializer):
distinct_id = serializers.CharField(required=True, help_text="User distinct ID")
groups = GroupsJSONField()
@@ -3463,18 +3471,24 @@ class FeatureFlagViewSet(
team__project_id=self.project_id, internal_targeting_flag__isnull=False
).values_list("internal_targeting_flag_id", flat=True)
- feature_flags = list(
+ flag_keys = request.validated_query_data.get("flag_keys") or None
+
+ flags_qs = (
FeatureFlag.objects.filter(team__project_id=self.project_id)
.exclude(Q(id__in=survey_flag_ids))
.exclude(Q(id__in=product_tour_internal_targeting_flags))
- .annotate(
+ )
+ if flag_keys:
+ flags_qs = flags_qs.filter(key__in=flag_keys)
+
+ feature_flags = list(
+ flags_qs.annotate(
evaluation_tag_names_agg=ArrayAgg(
"flag_evaluation_contexts__evaluation_context__name",
filter=Q(flag_evaluation_contexts__isnull=False),
distinct=True,
),
- )
- .order_by("-created_at")
+ ).order_by("-created_at")
)
if not feature_flags:
@@ -3496,10 +3510,15 @@ class FeatureFlagViewSet(
# Authenticated Django UI handler (the flags list in the app), not customer SDK
# traffic. Pass the internal token so the call bypasses per-team billing.
+ # Ask for "all" runtimes (as evaluation_reasons does): the internal request has a
+ # python-requests User-Agent, which the flags service reads as a server runtime and
+ # would otherwise use to drop client-only flags, reporting them here as false.
result = get_flags_from_service(
token=self.team.api_token,
distinct_id=distinct_id,
groups=groups,
+ flag_keys=flag_keys,
+ evaluation_runtime="all",
internal_request_token=settings.INTERNAL_REQUEST_TOKEN,
)
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index 5680d32f2d95..f54999fa2ea1 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -14274,6 +14274,37 @@ class TestFeatureFlagEvaluationReasons(APIBaseTest, ClickhouseTestMixin):
self.assertIn("error", response.json())
+class TestFeatureFlagMyFlags(APIBaseTest, ClickhouseTestMixin):
+ @parameterized.expand(
+ [
+ ("repeated_params", {"flag_keys": ["wanted"]}),
+ ("mcp_json_array_string", {"flag_keys": '["wanted"]'}),
+ ]
+ )
+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")
+ def test_my_flags_scopes_to_flag_keys(self, _name, query_flag_keys, mock_get_flags):
+ # flag_keys must scope both the flag definitions returned and the flags service call,
+ # otherwise the response lists every flag in the project. MCP clients JSON-stringify
+ # array query params into a single value, so that encoding must scope the same way.
+ FeatureFlag.objects.create(team=self.team, key="wanted")
+ FeatureFlag.objects.create(team=self.team, key="other")
+ mock_get_flags.return_value = {"flags": {"wanted": {"enabled": True, "variant": None}}}
+
+ response = self.client.get(
+ f"/api/projects/{self.team.pk}/feature_flags/my_flags/",
+ query_flag_keys,
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(mock_get_flags.call_args.kwargs["flag_keys"], ["wanted"])
+ # Must request all runtimes, otherwise the flags service reads the internal
+ # python-requests User-Agent as a server runtime and drops client-only flags,
+ # reporting a client-only flag that is on as false.
+ self.assertEqual(mock_get_flags.call_args.kwargs["evaluation_runtime"], "all")
+ returned_keys = {item["feature_flag"]["key"] for item in response.json()}
+ self.assertEqual(returned_keys, {"wanted"})
+
+
class TestFeatureFlagFiltersMetrics(APIBaseTest):
def _write_count(self, operation: str, outcome: str) -> float:
return FLAG_FILTERS_WRITE_COUNTER.labels(operation=operation, outcome=outcome, source="ui")._value.get()
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index 7cf63b2a3f26..6e4c0c3d6c30 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -1952,6 +1952,10 @@ export type FeatureFlagsEvaluationReasonsRetrieveParams = {
}
export type FeatureFlagsMyFlagsRetrieveParams = {
+ /**
+ * Optional list of flag keys to scope the response to. When omitted, every flag in the project is returned with its evaluated value, which can be a very large payload on projects with many flags. Pass the specific flag(s) you want to check to keep the response small. Accepts either repeated query params (flag_keys=a&flag_keys=b) or a JSON array string (flag_keys=["a","b"]).
+ */
+ flag_keys?: string[]
/**
* Groups for feature flag evaluation (JSON object string)
*/
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index f65f41c578f2..4364baf7d284 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -282,10 +282,12 @@ tools:
list: true
title: Get my evaluated feature flags
description: >
- List all feature flags in the current project along with their evaluated value for the authenticated user
- (the API key owner). Each item includes the flag definition and its current `value` (boolean for simple
- flags, variant key string for multivariate flags, false if disabled). Optionally pass `groups` as a JSON
- object to evaluate group-based flags.
+ List feature flags in the current project along with their evaluated value for the authenticated user (the
+ API key owner). Each item includes the flag definition and its current `value` (boolean for simple flags,
+ variant key string for multivariate flags, false if disabled). Pass `flag_keys` to scope the response to
+ specific flags. This is strongly recommended on projects with many flags, since omitting it returns an entry
+ for every flag and can produce a very large payload. Optionally pass `groups` as a JSON object to evaluate
+ group-based flags.
feature-flags-remote-config-retrieve:
operation: feature_flags_remote_config_retrieve
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 012780a5072e..833ab3b4be6d 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -4741,7 +4741,7 @@
}
},
"feature-flags-my-flags-retrieve": {
- "description": "List all feature flags in the current project along with their evaluated value for the authenticated user (the API key owner). Each item includes the flag definition and its current `value` (boolean for simple flags, variant key string for multivariate flags, false if disabled). Optionally pass `groups` as a JSON object to evaluate group-based flags.",
+ "description": "List feature flags in the current project along with their evaluated value for the authenticated user (the API key owner). Each item includes the flag definition and its current `value` (boolean for simple flags, variant key string for multivariate flags, false if disabled). Pass `flag_keys` to scope the response to specific flags. This is strongly recommended on projects with many flags, since omitting it returns an entry for every flag and can produce a very large payload. Optionally pass `groups` as a JSON object to evaluate group-based flags.",
"category": "Feature flags",
"feature": "flags",
"summary": "Get my evaluated feature flags",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 3501ec3f7266..a14578369bda 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -4896,7 +4896,7 @@
}
},
"feature-flags-my-flags-retrieve": {
- "description": "List all feature flags in the current project along with their evaluated value for the authenticated user (the API key owner). Each item includes the flag definition and its current `value` (boolean for simple flags, variant key string for multivariate flags, false if disabled). Optionally pass `groups` as a JSON object to evaluate group-based flags.",
+ "description": "List feature flags in the current project along with their evaluated value for the authenticated user (the API key owner). Each item includes the flag definition and its current `value` (boolean for simple flags, variant key string for multivariate flags, false if disabled). Pass `flag_keys` to scope the response to specific flags. This is strongly recommended on projects with many flags, since omitting it returns an entry for every flag and can produce a very large payload. Optionally pass `groups` as a JSON object to evaluate group-based flags.",
"category": "Feature flags",
"feature": "flags",
"summary": "Get my evaluated feature flags",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 38d0103e46b6..f8fbadbf3a39 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -89883,6 +89883,10 @@ export namespace Schemas {
};
export type FeatureFlagsMyFlagsRetrieveParams = {
+ /**
+ * Optional list of flag keys to scope the response to. When omitted, every flag in the project is returned with its evaluated value, which can be a very large payload on projects with many flags. Pass the specific flag(s) you want to check to keep the response small. Accepts either repeated query params (flag_keys=a&flag_keys=b) or a JSON array string (flag_keys=["a","b"]).
+ */
+ flag_keys?: string[];
/**
* Groups for feature flag evaluation (JSON object string)
*/
diff --git a/services/mcp/src/generated/feature_flags/api.ts b/services/mcp/src/generated/feature_flags/api.ts
index 77444f8a0264..7483cc032e73 100644
--- a/services/mcp/src/generated/feature_flags/api.ts
+++ b/services/mcp/src/generated/feature_flags/api.ts
@@ -1110,6 +1110,12 @@ export const FeatureFlagsMyFlagsRetrieveParams = /* @__PURE__ */ zod.object({
export const featureFlagsMyFlagsRetrieveQueryGroupsDefault = `{}`
export const FeatureFlagsMyFlagsRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ flag_keys: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Optional list of flag keys to scope the response to. When omitted, every flag in the project is returned with its evaluated value, which can be a very large payload on projects with many flags. Pass the specific flag(s) you want to check to keep the response small. Accepts either repeated query params (flag_keys=a&flag_keys=b) or a JSON array string (flag_keys=[\"a\",\"b\"]).'
+ ),
groups: zod
.string()
.default(featureFlagsMyFlagsRetrieveQueryGroupsDefault)
diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.ts
index 836f4ec1345f..edd306d2b139 100644
--- a/services/mcp/src/tools/generated/feature_flags.ts
+++ b/services/mcp/src/tools/generated/feature_flags.ts
@@ -385,6 +385,7 @@ const featureFlagsMyFlagsRetrieve = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/my_flags/`,
query: {
+ flag_keys: params.flag_keys,
groups: params.groups,
},
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-my-flags-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-my-flags-retrieve.json
index 011dc11cae61..3f80085c917a 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-my-flags-retrieve.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-my-flags-retrieve.json
@@ -1,6 +1,13 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "flag_keys": {
+ "description": "Optional list of flag keys to scope the response to. When omitted, every flag in the project is returned with its evaluated value, which can be a very large payload on projects with many flags. Pass the specific flag(s) you want to check to keep the response small. Accepts either repeated query params (flag_keys=a&flag_keys=b) or a JSON array string (flag_keys=[\"a\",\"b\"]).",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
"groups": {
"default": "{}",
"description": "Groups for feature flag evaluation (JSON object string)",