:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): add a gated tool that replaces v2 feature flag rules (#123448)
Andersb2762c43c245
diff --git a/products/feature_flags/evals/scorers.py b/products/feature_flags/evals/scorers.pyindex 76ae5d2442e6..2553387d7777 100644--- a/products/feature_flags/evals/scorers.py+++ b/products/feature_flags/evals/scorers.py@@ -673,6 +673,7 @@ FLAG_MUTATION_TOOLS = frozenset("feature-flag-unarchive","feature-flag-disable","feature-flag-enable",+ "feature-flag-rules-update","feature-flag-roll-out-to-everyone","feature-flag-set-release-condition-rollout","delete-feature-flag",diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yamlindex 261f001017cc..8b0886aa4b8f 100644--- a/products/feature_flags/mcp/tools.yaml+++ b/products/feature_flags/mcp/tools.yaml@@ -419,6 +419,55 @@ tools:- status- version- filters+ feature-flag-rules-update:+ operation: feature_flags_partial_update+ enabled: true+ scopes:+ - feature_flag:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: false+ input_schema: FlagRulesV2UpdateInputSchema+ enrich_url: '{id}'+ title: Replace feature flag rules+ description: >+ Replace the rules of a feature flag whose `filters.version` is 2. Requires the flag's numeric ID; use+ `feature-flag-get-definition-by-key` to get it from a key. For a flag without `filters.version` 2, use+ `update-feature-flag` instead; this tool cannot convert a flag between the two formats.+++ Read the flag first with `feature-flag-get-definition` or `feature-flag-get-definition-by-key`. Build the+ new `filters` from what you read and send the whole document: `version` 2, the same `return_type`,+ `default_value` and the complete ordered `rules` list. The server replaces the stored `filters` with what+ you send, so a rule you leave out is deleted. Rules are evaluated in order and the first rule that returns a+ value wins.+++ Each rule you read has an `id`, and randomized rules (`percentage_rollout`, `experiment`) have a `seed`.+ Send both unchanged on every rule you keep, edit or move, so the rule keeps its identity and nobody is+ reassigned. Leave `id` and `seed` off a new rule; the server assigns them. Never invent an `id` or change a+ `seed`: the write is refused.+++ Send the flag's top-level `version` from your read (not `filters.version`). Returns 409 when the flag+ changed after that version, and writes nothing. Read the flag again, rebuild the change on the current rules+ and send it with the new `version`. Do not retry with the same `version`.+++ Returns 400 naming the first invalid field when the document is invalid. Fix it and send the document again;+ the next attempt can name another field. Returns 400 with code `reserved_config_version` ("filters.version+ is reserved") when this project or this flag does not accept version 2 rule changes. Do not remove+ `filters.version`. Report that to the user; do not work around it with `update-feature-flag`. This tool+ changes only `filters`. Use `feature-flag-enable` and `feature-flag-disable` to turn the flag on or off.+ feature_flag: feature-flag-rules-v2-mcp+ response:+ include:+ - id+ - key+ - active+ - version+ - filtersfeature-flag-set-release-condition-rollout:operation: feature_flags_set_release_condition_rollout_createenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex dd99e5aa8b51..6eff866f89d6 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -6766,6 +6766,22 @@"readOnlyHint": false}},+ "feature-flag-rules-update": {+ "description": "Replace the rules of a feature flag whose `filters.version` is 2. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key. For a flag without `filters.version` 2, use `update-feature-flag` instead; this tool cannot convert a flag between the two formats.\n\nRead the flag first with `feature-flag-get-definition` or `feature-flag-get-definition-by-key`. Build the new `filters` from what you read and send the whole document: `version` 2, the same `return_type`, `default_value` and the complete ordered `rules` list. The server replaces the stored `filters` with what you send, so a rule you leave out is deleted. Rules are evaluated in order and the first rule that returns a value wins.\n\nEach rule you read has an `id`, and randomized rules (`percentage_rollout`, `experiment`) have a `seed`. Send both unchanged on every rule you keep, edit or move, so the rule keeps its identity and nobody is reassigned. Leave `id` and `seed` off a new rule; the server assigns them. Never invent an `id` or change a `seed`: the write is refused.\n\nSend the flag's top-level `version` from your read (not `filters.version`). Returns 409 when the flag changed after that version, and writes nothing. Read the flag again, rebuild the change on the current rules and send it with the new `version`. Do not retry with the same `version`.\n\nReturns 400 naming the first invalid field when the document is invalid. Fix it and send the document again; the next attempt can name another field. Returns 400 with code `reserved_config_version` (\"filters.version is reserved\") when this project or this flag does not accept version 2 rule changes. Do not remove `filters.version`. Report that to the user; do not work around it with `update-feature-flag`. This tool changes only `filters`. Use `feature-flag-enable` and `feature-flag-disable` to turn the flag on or off.",+ "category": "Feature flags",+ "feature": "flags",+ "summary": "Replace feature flag rules",+ "title": "Replace feature flag rules",+ "required_scopes": ["feature_flag:write"],+ "api_operations": ["PATCH /api/projects/{project_id}/feature_flags/{id}/"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "feature-flag-rules-v2-mcp"+ },"feature-flag-set-release-condition-rollout": {"description": "Set what percentage of one release condition's audience a feature flag is served to. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nChanges `rollout_percentage` on the release condition at `condition_index` and nothing else. This tool never accepts or replaces the `filters` object, so the condition's property filters, the other conditions, the variants and the payloads cannot change.\n\nCheck `aggregation_group_type_index` on the condition, and on `filters` when the condition sets none. When it is set, the flag buckets groups of that type instead of people, so 25 serves 25% of those groups rather than 25% of users. Say groups when you report the change.\n\nRead the flag first. `condition_index` counts the conditions in `filters.groups` from 0, and only the definition you read says which condition is which, so never guess an index on a flag with more than one condition. Send the `version` that same read returned. Returns 409 when anyone changed the flag after that version, and writes nothing. Read the flag again, check the conditions still mean what you thought, and call again with the new version. Do not retry with the same version: after a call writes a change that version is no longer current, so a blind retry is the same 409. A call that sets the percentage the condition already has writes nothing and returns the version unchanged.\n\nOn a multivariate flag this sets how many of the matching users or groups get a variant at all. It does not change how the variants are split between them. When the user asks for a bare percentage on a multivariate flag, ask which of the two they mean. Use `update-feature-flag` to change the split between variants.\n\nReturns 400 when the flag has no release condition at that index, or when the percentage is outside 0 through 100. Returns 409 when an approval policy gates rollout changes.","category": "Feature flags",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex b39f29febc68..56690fc3abbd 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -6938,6 +6938,22 @@"readOnlyHint": false}},+ "feature-flag-rules-update": {+ "description": "Replace the rules of a feature flag whose `filters.version` is 2. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key. For a flag without `filters.version` 2, use `update-feature-flag` instead; this tool cannot convert a flag between the two formats.\n\nRead the flag first with `feature-flag-get-definition` or `feature-flag-get-definition-by-key`. Build the new `filters` from what you read and send the whole document: `version` 2, the same `return_type`, `default_value` and the complete ordered `rules` list. The server replaces the stored `filters` with what you send, so a rule you leave out is deleted. Rules are evaluated in order and the first rule that returns a value wins.\n\nEach rule you read has an `id`, and randomized rules (`percentage_rollout`, `experiment`) have a `seed`. Send both unchanged on every rule you keep, edit or move, so the rule keeps its identity and nobody is reassigned. Leave `id` and `seed` off a new rule; the server assigns them. Never invent an `id` or change a `seed`: the write is refused.\n\nSend the flag's top-level `version` from your read (not `filters.version`). Returns 409 when the flag changed after that version, and writes nothing. Read the flag again, rebuild the change on the current rules and send it with the new `version`. Do not retry with the same `version`.\n\nReturns 400 naming the first invalid field when the document is invalid. Fix it and send the document again; the next attempt can name another field. Returns 400 with code `reserved_config_version` (\"filters.version is reserved\") when this project or this flag does not accept version 2 rule changes. Do not remove `filters.version`. Report that to the user; do not work around it with `update-feature-flag`. This tool changes only `filters`. Use `feature-flag-enable` and `feature-flag-disable` to turn the flag on or off.",+ "category": "Feature flags",+ "feature": "flags",+ "summary": "Replace feature flag rules",+ "title": "Replace feature flag rules",+ "required_scopes": ["feature_flag:write"],+ "api_operations": ["PATCH /api/projects/{project_id}/feature_flags/{id}/"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "feature-flag-rules-v2-mcp"+ },"feature-flag-set-release-condition-rollout": {"description": "Set what percentage of one release condition's audience a feature flag is served to. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nChanges `rollout_percentage` on the release condition at `condition_index` and nothing else. This tool never accepts or replaces the `filters` object, so the condition's property filters, the other conditions, the variants and the payloads cannot change.\n\nCheck `aggregation_group_type_index` on the condition, and on `filters` when the condition sets none. When it is set, the flag buckets groups of that type instead of people, so 25 serves 25% of those groups rather than 25% of users. Say groups when you report the change.\n\nRead the flag first. `condition_index` counts the conditions in `filters.groups` from 0, and only the definition you read says which condition is which, so never guess an index on a flag with more than one condition. Send the `version` that same read returned. Returns 409 when anyone changed the flag after that version, and writes nothing. Read the flag again, check the conditions still mean what you thought, and call again with the new version. Do not retry with the same version: after a call writes a change that version is no longer current, so a blind retry is the same 409. A call that sets the percentage the condition already has writes nothing and returns the version unchanged.\n\nOn a multivariate flag this sets how many of the matching users or groups get a variant at all. It does not change how the variants are split between them. When the user asks for a bare percentage on a multivariate flag, ask which of the two they mean. Use `update-feature-flag` to change the split between variants.\n\nReturns 400 when the flag has no release condition at that index, or when the percentage is outside 0 through 100. Returns 409 when an approval policy gates rollout changes.","category": "Feature flags",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 9859632ee402..41cece7ad136 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -746,6 +746,74 @@},"required": ["summary", "feedback_type", "sentiment"]},+ "FlagRulesV2UpdateInputSchema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "number",+ "description": "A unique integer value identifying this feature flag."+ },+ "version": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991,+ "description": "The flag's top-level `version` from your latest read. The write is refused with 409 when the flag changed after it."+ },+ "filters": {+ "type": "object",+ "properties": {+ "version": {+ "type": "number",+ "const": 2,+ "description": "Config format. Always 2 here; unrelated to the top-level `version`."+ },+ "return_type": {+ "type": "string",+ "description": "Copy it from the flag you read. It cannot change."+ },+ "default_value": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {}+ },+ {+ "type": "null"+ }+ ],+ "description": "Value served when no rule returns one. Must match `return_type`, or null."+ },+ "rules": {+ "type": "array",+ "items": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {}+ },+ "description": "The complete ordered rule list, in the shape the flag read returns. Keep `id` and `seed` on every rule you keep; omit both on a new rule."+ }+ },+ "required": ["version", "return_type", "default_value", "rules"],+ "additionalProperties": {},+ "description": "The complete new configuration. It replaces the stored `filters`."+ }+ },+ "required": ["id", "version", "filters"]+ },"InsightQueryInputSchema": {"type": "object","properties": {diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex 80bbcdac3bc1..568628cbb61b 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -6,7 +6,7 @@ import {aiObservabilityOfflineExperimentsUploadCreateBodyResultsMax,} from '../generated/ai_observability/api'import { BillingUsageRetrieveQueryParams } from '../generated/billing/api'-import { FeatureFlagsPartialUpdateBody } from '../generated/feature_flags/api'+import { FeatureFlagsPartialUpdateBody, FeatureFlagsPartialUpdateParams } from '../generated/feature_flags/api'// Relative (not `@/`) imports: this module is loaded by the tsx schema-generation// script, and both modules are pure constants/functions — no `.md` imports to choke on.import { castStringToInt, normalizeParamAliases } from '../tools/cast-helpers'@@ -1350,3 +1350,35 @@ export const UpdateFeatureFlagFiltersSchema = FeatureFlagUpdateFilters.extend({'Full release-condition object. It replaces the stored filters, so read the flag first and send every ' +'condition you want to keep. The tool description covers condition_id and group targeting.')++// Rules stay opaque: the server's v2 validator is the only schema, and its field errors name the path to fix.+// A loose object keeps every key the agent sends, so nothing it echoed from the read is dropped here.+export const FlagRulesV2UpdateInputSchema = z.preprocess(+ normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),+ z.object({+ id: z.preprocess(castStringToInt, FeatureFlagsPartialUpdateParams().shape.id),+ version: z+ .number()+ .int()+ .min(0)+ .describe(+ "The flag's top-level `version` from your latest read. The write is refused with 409 when the flag " ++ 'changed after it.'+ ),+ filters: z+ .looseObject({+ version: z.literal(2).describe('Config format. Always 2 here; unrelated to the top-level `version`.'),+ return_type: z.string().describe('Copy it from the flag you read. It cannot change.'),+ default_value: z+ .union([z.boolean(), z.string(), z.number(), z.record(z.string(), z.unknown()), z.null()])+ .describe('Value served when no rule returns one. Must match `return_type`, or null.'),+ rules: z+ .array(z.record(z.string(), z.unknown()))+ .describe(+ 'The complete ordered rule list, in the shape the flag read returns. Keep `id` and `seed` on ' ++ 'every rule you keep; omit both on a new rule.'+ ),+ })+ .describe('The complete new configuration. It replaces the stored `filters`.'),+ })+)diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.tsindex bf9e63895851..c5997f7db144 100644--- a/services/mcp/src/tools/generated/feature_flags.ts+++ b/services/mcp/src/tools/generated/feature_flags.ts@@ -4,7 +4,11 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import * as orvalSchemas from '@/generated/feature_flags/api'import { withUiApp } from '@/resources/ui-apps'-import { UpdateFeatureFlagFiltersSchema, validateDistinctIdPersonIdExclusive } from '@/schema/tool-inputs'+import {+ FlagRulesV2UpdateInputSchema,+ UpdateFeatureFlagFiltersSchema,+ validateDistinctIdPersonIdExclusive,+} from '@/schema/tool-inputs'import { castStringToInt, normalizeParamAliases } from '@/tools/cast-helpers'import hooks_createFeatureFlag from '@/tools/featureFlags/conditionIdHooks'import hooks_deleteFeatureFlag from '@/tools/featureFlags/conditionIdHooks'@@ -374,6 +378,25 @@ const featureFlagRollOutToEveryone = (): ToolBase<),})+const FeatureFlagRulesUpdateSchema = () => FlagRulesV2UpdateInputSchema++const featureFlagRulesUpdate = (): ToolBase<ReturnType<typeof FeatureFlagRulesUpdateSchema>, Schemas.FeatureFlag> => ({+ name: 'feature-flag-rules-update',+ schema: FeatureFlagRulesUpdateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof FeatureFlagRulesUpdateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const parsedParams = FeatureFlagRulesUpdateSchema().parse(params)+ const { id, ...body } = parsedParams+ const result = await context.api.request<Schemas.FeatureFlag>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(id))}/`,+ body,+ })+ const filtered = pickResponseFields(result, ['id', 'key', 'active', 'version', 'filters']) as typeof result+ return await withPostHogUrl(context, filtered, `/feature-flags/${filtered.id}`)+ },+})+const FeatureFlagSetReleaseConditionRolloutSchema = () => {const FeatureFlagsSetReleaseConditionRolloutCreateBody =orvalSchemas.FeatureFlagsSetReleaseConditionRolloutCreateBody()@@ -1097,6 +1120,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'feature-flag-get-all': featureFlagGetAll,'feature-flag-get-definition': featureFlagGetDefinition,'feature-flag-roll-out-to-everyone': featureFlagRollOutToEveryone,+ 'feature-flag-rules-update': featureFlagRulesUpdate,'feature-flag-set-release-condition-rollout': featureFlagSetReleaseConditionRollout,'feature-flag-unarchive': featureFlagUnarchive,'feature-flags-activity-retrieve': featureFlagsActivityRetrieve,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-rules-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-rules-update.jsonnew file mode 100644index 000000000000..b1201c801db5--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-rules-update.json@@ -0,0 +1,69 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "filters": {+ "additionalProperties": {},+ "description": "The complete new configuration. It replaces the stored `filters`.",+ "properties": {+ "default_value": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Value served when no rule returns one. Must match `return_type`, or null."+ },+ "return_type": {+ "description": "Copy it from the flag you read. It cannot change.",+ "type": "string"+ },+ "rules": {+ "description": "The complete ordered rule list, in the shape the flag read returns. Keep `id` and `seed` on every rule you keep; omit both on a new rule.",+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "version": {+ "const": 2,+ "description": "Config format. Always 2 here; unrelated to the top-level `version`.",+ "type": "number"+ }+ },+ "required": ["version", "return_type", "default_value", "rules"],+ "type": "object"+ },+ "id": {+ "description": "A unique integer value identifying this feature flag.",+ "type": "number"+ },+ "version": {+ "description": "The flag's top-level `version` from your latest read. The write is refused with 409 when the flag changed after it.",+ "maximum": 9007199254740991,+ "minimum": 0,+ "type": "integer"+ }+ },+ "required": ["id", "version", "filters"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/experiment-id-aliases.test.ts b/services/mcp/tests/unit/experiment-id-aliases.test.tsindex f919f476dc63..e47d0facc94c 100644--- a/services/mcp/tests/unit/experiment-id-aliases.test.ts+++ b/services/mcp/tests/unit/experiment-id-aliases.test.ts@@ -134,6 +134,7 @@ describe('feature flag id aliases', () => {'feature-flag-enable','feature-flag-get-definition','feature-flag-roll-out-to-everyone',+ 'feature-flag-rules-update','feature-flag-set-release-condition-rollout','feature-flag-unarchive','feature-flags-activity-retrieve',@@ -148,6 +149,10 @@ describe('feature flag id aliases', () => {const REQUIRED_EXTRAS: Record<string, Record<string, unknown>> = {'feature-flags-test-evaluation-create': { distinct_id: 'user-1' },'feature-flag-roll-out-to-everyone': { version: 3 },+ 'feature-flag-rules-update': {+ version: 3,+ filters: { version: 2, return_type: 'boolean', default_value: false, rules: [] },+ },'feature-flag-set-release-condition-rollout': { condition_index: 0, rollout_percentage: 25, version: 3 },}diff --git a/services/mcp/tests/unit/feature-flag-rules-update.test.ts b/services/mcp/tests/unit/feature-flag-rules-update.test.tsnew file mode 100644index 000000000000..4ff8a8f60189--- /dev/null+++ b/services/mcp/tests/unit/feature-flag-rules-update.test.ts@@ -0,0 +1,105 @@+import { describe, expect, it, vi } from 'vitest'+import { z } from 'zod'++import { GENERATED_TOOL_MAP } from '@/tools/generated'+import { getRequiredFeatureFlags, getToolDefinition, getToolsForFeatures } from '@/tools/toolDefinitions'+import type { Context } from '@/tools/types'++const TOOL = 'feature-flag-rules-update'+const FLAG = 'feature-flag-rules-v2-mcp'++const FILTERS = {+ version: 2,+ return_type: 'string',+ default_value: 'off',+ rules: [+ {+ id: '0b7f3c52-5a0e-4d1e-9a4c-3f1b2e6d8c90',+ rule_type: 'percentage_rollout',+ targeting: { properties: [] },+ value: 'on',+ rollout_percentage: 40,+ on_rollout_miss: 'continue',+ assignment_algorithm: 'sha1_60_v1',+ seed: 'b8e1d0a4-7c2f-4e9b-8d3a-6f5c4b3a2e10',+ },+ {+ rule_type: 'targeted_release',+ targeting: { properties: [{ key: 'plan', type: 'person', operator: 'exact', value: ['team'] }] },+ value: 'on',+ },+ ],+}++function mockContext(request: ReturnType<typeof vi.fn>): Context {+ return {+ api: { request, getProjectBaseUrl: () => 'https://app.posthog.com/project/17' },+ stateManager: { getProjectId: vi.fn().mockResolvedValue('17') },+ } as unknown as Context+}++describe('feature-flag-rules-update', () => {+ it('is hidden unless its flag is on', () => {+ expect(getRequiredFeatureFlags()).toContain(FLAG)+ expect(getToolsForFeatures({ featureFlags: {} })).not.toContain(TOOL)+ expect(getToolsForFeatures({ featureFlags: { [FLAG]: false } })).not.toContain(TOOL)+ expect(getToolsForFeatures({ featureFlags: { [FLAG]: true } })).toContain(TOOL)+ })++ it('leaves update-feature-flag visible either way', () => {+ expect(getToolsForFeatures({ featureFlags: {} })).toContain('update-feature-flag')+ expect(getToolsForFeatures({ featureFlags: { [FLAG]: true } })).toContain('update-feature-flag')+ expect(getToolDefinition('update-feature-flag').feature_flag).toBeUndefined()+ })++ it('is destructive and requires write scope', () => {+ const definition = getToolDefinition(TOOL)+ expect(definition.required_scopes).toEqual(['feature_flag:write'])+ expect(definition.annotations).toMatchObject({+ readOnlyHint: false,+ destructiveHint: true,+ idempotentHint: false,+ })+ })++ it('requires the flag id, the row version and a version 2 document', () => {+ const schema = z.toJSONSchema(GENERATED_TOOL_MAP[TOOL]!().schema, { io: 'input', reused: 'inline' }) as {+ required?: string[]+ }+ expect(schema.required?.sort()).toEqual(['filters', 'id', 'version'])++ const tool = GENERATED_TOOL_MAP[TOOL]!()+ expect(tool.schema.safeParse({ id: 42, version: 3, filters: FILTERS }).success).toBe(true)+ expect(tool.schema.safeParse({ id: 42, filters: FILTERS }).success).toBe(false)+ expect(tool.schema.safeParse({ id: 42, version: 3, filters: { ...FILTERS, version: 1 } }).success).toBe(false)+ })++ it('sends the whole document and the row version in one PATCH', async () => {+ const request = vi.fn().mockResolvedValue({ id: 42, key: 'checkout', version: 4, filters: FILTERS })+ const filters = { ...FILTERS, aggregation_group_type_index: 0 }++ const result = await GENERATED_TOOL_MAP[TOOL]!().handler(mockContext(request), { id: 42, version: 3, filters })++ expect(result).toMatchObject({+ id: 42,+ key: 'checkout',+ version: 4,+ filters: FILTERS,+ _posthogUrl: 'https://app.posthog.com/project/17/feature-flags/42',+ })+ expect(request).toHaveBeenCalledExactlyOnceWith({+ method: 'PATCH',+ path: '/api/projects/17/feature_flags/42/',+ body: { version: 3, filters },+ })+ })++ it('surfaces a refused write instead of swallowing it', async () => {+ const refused = new Error('Conflict: the flag changed after version 3')+ const request = vi.fn().mockRejectedValue(refused)++ await expect(+ GENERATED_TOOL_MAP[TOOL]!().handler(mockContext(request), { id: 42, version: 3, filters: FILTERS })+ ).rejects.toBe(refused)+ })+})diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex e70fa77271a3..039a128d1526 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -1115,6 +1115,7 @@ describe('Tool Filtering - Feature Flags', () => {'activity-summary','anomalies-search','workflows-email-domain-agent-setup',+ 'feature-flag-rules-v2-mcp',]expect(allFlags).toEqual(expect.arrayContaining(branchFlags))// The flags branches add are asserted on the line above and held out of the list anddiff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.tsindex e34fe437c221..a72d646986ea 100644--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts@@ -112,6 +112,7 @@ async function loadSnapshotTools(): Promise<Tool<ZodObjectAny>[]> {'activity-summary': true,'aeo-citation-tracking': true,'anomalies-search': true,+ 'feature-flag-rules-v2-mcp': true,}return [...(await getToolsFromContext(createMockContext(), { featureFlags }))].sort((a, b) =>a.name.localeCompare(b.name)