:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(flags): add flag_keys filter to evaluation reasons (#68454)
posthog[bot]0324c9f2dc5a
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex ae53424aa640..06a3a4172235 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -2241,9 +2241,47 @@ class MyFlagsQuerySerializer(serializers.Serializer):groups = GroupsJSONField()+class FlagKeysField(serializers.ListField):+ """+ ListField that also accepts a single JSON-array string.++ MCP clients JSON-stringify array query params into one value (e.g. `flag_keys=["a","b"]`),+ while browsers/curl send repeated params (`flag_keys=a&flag_keys=b`). Support both.+ """++ def __init__(self, **kwargs):+ kwargs.setdefault("child", serializers.CharField())+ kwargs.setdefault("required", False)+ kwargs.setdefault("allow_empty", True)+ super().__init__(**kwargs)++ def to_internal_value(self, data):+ if isinstance(data, list) and len(data) == 1 and isinstance(data[0], str):+ candidate = data[0].strip()+ if candidate.startswith("["):+ try:+ parsed = json.loads(candidate)+ except json.JSONDecodeError:+ raise serializers.ValidationError("Invalid JSON in flag_keys parameter")+ if not isinstance(parsed, list):+ raise serializers.ValidationError("flag_keys must be a JSON array")+ data = parsed++ return super().to_internal_value(data)++class EvaluationReasonsQuerySerializer(serializers.Serializer):distinct_id = serializers.CharField(required=True, help_text="User distinct ID")groups = GroupsJSONField()+ flag_keys = FlagKeysField(+ help_text=(+ "Optional list of flag keys to scope the response to. When omitted, evaluation reasons are "+ "returned for every flag in the project, which can be a very large payload on projects with "+ "many flags. Pass the specific flag(s) you are debugging 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 ActivityQuerySerializer(serializers.Serializer):@@ -3688,12 +3726,15 @@ class FeatureFlagViewSet(if isinstance(groups, str):groups = json.loads(groups) if groups else {}+ flag_keys = request.validated_query_data.get("flag_keys") or None+# PostHog UI debug endpoint, not customer SDK traffic. Pass the internal# token so the call bypasses per-team billing.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,)@@ -3716,9 +3757,10 @@ class FeatureFlagViewSet(},}- disabled_flags = FeatureFlag.objects.filter(team__project_id=self.project_id, active=False).values_list(- "key", flat=True- )+ disabled_flags_qs = FeatureFlag.objects.filter(team__project_id=self.project_id, active=False)+ if flag_keys:+ disabled_flags_qs = disabled_flags_qs.filter(key__in=flag_keys)+ disabled_flags = disabled_flags_qs.values_list("key", flat=True)for flag_key in disabled_flags:flags_with_evaluation_reasons[flag_key] = {diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 98f47647cced..4102d1837b09 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -13431,3 +13431,39 @@ class TestFeatureFlagEvaluationReasons(APIBaseTest, ClickhouseTestMixin):data = response.json()self.assertIn(flag.key, data)self.assertEqual(data[flag.key]["evaluation"]["reason"], "condition_match")++ @parameterized.expand(+ [+ ("repeated_params", {"flag_keys": ["wanted-active", "wanted-disabled"]}),+ ("mcp_json_array_string", {"flag_keys": '["wanted-active", "wanted-disabled"]'}),+ ]+ )+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")+ def test_evaluation_reasons_scopes_to_flag_keys(self, _name, query_flag_keys, mock_get_flags):+ # flag_keys must be forwarded to the flags service and also scope the disabled-flag+ # rows appended afterwards, otherwise the response still lists every flag in the project.+ # MCP clients JSON-stringify array query params into a single value, so that encoding+ # must scope the response exactly like repeated query params do.+ FeatureFlag.objects.create(team=self.team, key="wanted-disabled", active=False)+ FeatureFlag.objects.create(team=self.team, key="other-disabled", active=False)+ mock_get_flags.return_value = {+ "flags": {+ "wanted-active": {+ "enabled": True,+ "variant": None,+ "reason": {"code": "condition_match", "condition_index": 0},+ },+ }+ }++ response = self.client.get(+ f"/api/projects/{self.team.pk}/feature_flags/evaluation_reasons/",+ {"distinct_id": "user-1", **query_flag_keys},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(mock_get_flags.call_args.kwargs["flag_keys"], ["wanted-active", "wanted-disabled"])+ data = response.json()+ self.assertIn("wanted-active", data)+ self.assertIn("wanted-disabled", data)+ self.assertNotIn("other-disabled", data)diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex 4200d5494aee..35e8777ac847 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -1885,6 +1885,10 @@ export type FeatureFlagsEvaluationReasonsRetrieveParams = {* @minLength 1*/distinct_id: string+ /**+ * Optional list of flag keys to scope the response to. When omitted, evaluation reasons are returned for every flag in the project, which can be a very large payload on projects with many flags. Pass the specific flag(s) you are debugging 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.yamlindex b3d6dc6aeb0c..6ef3323f30a3 100644--- a/products/feature_flags/mcp/tools.yaml+++ b/products/feature_flags/mcp/tools.yaml@@ -256,7 +256,9 @@ tools:description: >Debug why feature flags evaluate a certain way for a given user. Provide a distinct_id and optionally groupsto see each flag's evaluated value and the reason for that evaluation (e.g. condition_match,- no_condition_match, disabled).+ no_condition_match, 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.feature-flags-matching-ids-retrieve:operation: feature_flags_matching_ids_retrieveenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 1f1e857c9e69..3e0c7d41be42 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3904,7 +3904,7 @@}},"feature-flags-evaluation-reasons-retrieve": {- "description": "Debug why feature flags evaluate a certain way for a given user. Provide a distinct_id and optionally groups to see each flag's evaluated value and the reason for that evaluation (e.g. condition_match, no_condition_match, disabled).",+ "description": "Debug why feature flags evaluate a certain way for a given user. Provide a distinct_id and optionally groups to see each flag's evaluated value and the reason for that evaluation (e.g. condition_match, no_condition_match, 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.","category": "Feature flags","feature": "flags","summary": "Get feature flag evaluation reasons",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 3604ce5fe672..21e5c51da6f4 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -4157,7 +4157,7 @@}},"feature-flags-evaluation-reasons-retrieve": {- "description": "Debug why feature flags evaluate a certain way for a given user. Provide a distinct_id and optionally groups to see each flag's evaluated value and the reason for that evaluation (e.g. condition_match, no_condition_match, disabled).",+ "description": "Debug why feature flags evaluate a certain way for a given user. Provide a distinct_id and optionally groups to see each flag's evaluated value and the reason for that evaluation (e.g. condition_match, no_condition_match, 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.","category": "Feature flags","feature": "flags","summary": "Get feature flag evaluation reasons",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a903d41022bc..32003cad3f76 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -72234,6 +72234,10 @@ export namespace Schemas {* @minLength 1*/distinct_id: string;+ /**+ * Optional list of flag keys to scope the response to. When omitted, evaluation reasons are returned for every flag in the project, which can be a very large payload on projects with many flags. Pass the specific flag(s) you are debugging 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.tsindex 92d8d80c005a..c37c726a4dbf 100644--- a/services/mcp/src/generated/feature_flags/api.ts+++ b/services/mcp/src/generated/feature_flags/api.ts@@ -1061,6 +1061,12 @@ export const featureFlagsEvaluationReasonsRetrieveQueryGroupsDefault = `{}`export const FeatureFlagsEvaluationReasonsRetrieveQueryParams = /* @__PURE__ */ zod.object({distinct_id: zod.string().min(1).describe('User distinct ID'),+ flag_keys: zod+ .array(zod.string())+ .optional()+ .describe(+ 'Optional list of flag keys to scope the response to. When omitted, evaluation reasons are returned for every flag in the project, which can be a very large payload on projects with many flags. Pass the specific flag(s) you are debugging 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(featureFlagsEvaluationReasonsRetrieveQueryGroupsDefault)diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.tsindex f5ae40d6c1de..1ec4b9d3fea7 100644--- a/services/mcp/src/tools/generated/feature_flags.ts+++ b/services/mcp/src/tools/generated/feature_flags.ts@@ -361,6 +361,7 @@ const featureFlagsEvaluationReasonsRetrieve = (): ToolBase<path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/evaluation_reasons/`,query: {distinct_id: params.distinct_id,+ flag_keys: params.flag_keys,groups: params.groups,},})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-evaluation-reasons-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-evaluation-reasons-retrieve.jsonindex caa24f836e3d..2cddf38e2d3b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-evaluation-reasons-retrieve.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-evaluation-reasons-retrieve.json@@ -6,6 +6,13 @@"minLength": 1,"type": "string"},+ "flag_keys": {+ "description": "Optional list of flag keys to scope the response to. When omitted, evaluation reasons are returned for every flag in the project, which can be a very large payload on projects with many flags. Pass the specific flag(s) you are debugging 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)",