: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
fix(mcp): preserve group targeting on update-feature-flag (#78678)
Alex Idowu2fc0884ccc4e
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex 79ebd8707e23..9c563201fc4f 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -330,6 +330,36 @@ Product teams own their definitions and control which operations are exposed asThe generated code uses `.extend()` to replace just that field.See [supported annotations](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations) for the full list.+ #### Hand-written override of a generated tool++ The two overrides above reshape a generated tool's schema.+ Neither can change what happens before the request goes out.+ `validators` runs as a synchronous `superRefine`, so it cannot await anything;+ `inject_body` supplies static values; `rename_params` only renames.++ When a tool has to read current state before writing, export a hand-written tool under the generated tool's own name.+ `mergeToolFactories` gives hand-written entries precedence on a name collision, so the hand-written tool replaces the generated one everywhere:+ the Hono catalog, the CLI, `getToolsFromContext`, and `posthog-connection-call`.++ `src/tools/featureFlags/updateFeatureFlag.ts` is the reference.+ It spreads the generated tool so the name, schema and any field codegen adds later carry over, replaces only the handler, and delegates back to the generated handler to make the request:++ ```ts+ const generated = GENERATED_TOOLS['update-feature-flag']!()++ return {+ ...generated,+ handler: async (context, params) => {+ const existing = await context.api.request({ method: 'GET', path: `...` })+ return generated.handler(context, { ...params, filters: merge(existing, params.filters) })+ },+ }+ ```++ Reach for this only when a read-modify-write is genuinely needed.+ Every override is a name collision that has to stay deliberate, which `tests/unit/tool-name-validation.test.ts` enforces by pinning the set of shadowed names.+ If a second tool needs the same treatment, add support for a `before_request:` hook to the YAML config instead of a second shadow.+#### Typed-confirm paradigm for destructive toolsFor destructive or security-sensitive tools (account changes, key revocation, bulk deletes),diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yamlindex 67dc2510b368..f6d2964b862a 100644--- a/products/feature_flags/mcp/tools.yaml+++ b/products/feature_flags/mcp/tools.yaml@@ -694,10 +694,12 @@ tools:Rollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters`- replaces the whole object, so read the flag first and merge your change. Use- `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full- definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at- a future time instead, use `scheduled-changes-create`.+ replaces the whole object, so read the flag first and merge your change. When the flag targets groups, keep+ `type: "group"`, `group_type_index`, and `filters.aggregation_group_type_index` in what you send; if you+ omit them this tool restores them from the existing flag so group targeting is not silently converted to+ person targeting. Use `feature-flag-get-definition-by-key` when you have the string key: it returns the+ numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you already have the+ ID. To apply a change at a future time instead, use `scheduled-changes-create`.include_params:- key- name@@ -713,6 +715,12 @@ tools:param_overrides:id:cast: string-int+ filters:+ description: >+ Full release-condition object (replaces filters at the API). For group flags set+ aggregation_group_type_index and property type "group" + group_type_index. Omitted type /+ group_type_index / aggregation_group_type_index are filled from the existing flag to prevent silent+ person demotion (see #46501).is_remote_configuration:description:Whether this flag delivers a payload instead of gating a feature (Remote Config mode). When true, set thediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 394b7286dbb8..58ab94fe1c3b 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -11349,7 +11349,7 @@"feature_flag": "tasks"},"update-feature-flag": {- "description": "Update a feature flag by numeric ID (partial update: only the fields you include are changed). Use this for edits that have no dedicated tool, such as release conditions, rollout percentages, variants, payloads, tags and the description.\n\nPrefer a dedicated tool whenever the request matches one. `feature-flag-enable`, `feature-flag-disable`, `feature-flag-archive` and `feature-flag-unarchive` each change one state field and send no `filters`. A targeting change someone else made between your read and your write is therefore not overwritten. Send `active` or `archived` here only when the same request also changes targeting or another field, so the whole edit lands in one write.\n\nRollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters` replaces the whole object, so read the flag first and merge your change. Use `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at a future time instead, use `scheduled-changes-create`.",+ "description": "Update a feature flag by numeric ID (partial update: only the fields you include are changed). Use this for edits that have no dedicated tool, such as release conditions, rollout percentages, variants, payloads, tags and the description.\n\nPrefer a dedicated tool whenever the request matches one. `feature-flag-enable`, `feature-flag-disable`, `feature-flag-archive` and `feature-flag-unarchive` each change one state field and send no `filters`. A targeting change someone else made between your read and your write is therefore not overwritten. Send `active` or `archived` here only when the same request also changes targeting or another field, so the whole edit lands in one write.\n\nRollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters` replaces the whole object, so read the flag first and merge your change. When the flag targets groups, keep `type: \"group\"`, `group_type_index`, and `filters.aggregation_group_type_index` in what you send; if you omit them this tool restores them from the existing flag so group targeting is not silently converted to person targeting. Use `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at a future time instead, use `scheduled-changes-create`.","category": "Feature flags","feature": "flags","summary": "Update feature flag",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 6eb922a5ac85..c4c726e35c96 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -11994,7 +11994,7 @@"feature_flag": "tasks"},"update-feature-flag": {- "description": "Update a feature flag by numeric ID (partial update: only the fields you include are changed). Use this for edits that have no dedicated tool, such as release conditions, rollout percentages, variants, payloads, tags and the description.\n\nPrefer a dedicated tool whenever the request matches one. `feature-flag-enable`, `feature-flag-disable`, `feature-flag-archive` and `feature-flag-unarchive` each change one state field and send no `filters`. A targeting change someone else made between your read and your write is therefore not overwritten. Send `active` or `archived` here only when the same request also changes targeting or another field, so the whole edit lands in one write.\n\nRollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters` replaces the whole object, so read the flag first and merge your change. Use `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at a future time instead, use `scheduled-changes-create`.",+ "description": "Update a feature flag by numeric ID (partial update: only the fields you include are changed). Use this for edits that have no dedicated tool, such as release conditions, rollout percentages, variants, payloads, tags and the description.\n\nPrefer a dedicated tool whenever the request matches one. `feature-flag-enable`, `feature-flag-disable`, `feature-flag-archive` and `feature-flag-unarchive` each change one state field and send no `filters`. A targeting change someone else made between your read and your write is therefore not overwritten. Send `active` or `archived` here only when the same request also changes targeting or another field, so the whole edit lands in one write.\n\nRollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters` replaces the whole object, so read the flag first and merge your change. When the flag targets groups, keep `type: \"group\"`, `group_type_index`, and `filters.aggregation_group_type_index` in what you send; if you omit them this tool restores them from the existing flag so group targeting is not silently converted to person targeting. Use `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at a future time instead, use `scheduled-changes-create`.","category": "Feature flags","feature": "flags","summary": "Update feature flag",diff --git a/services/mcp/src/cli/tools.ts b/services/mcp/src/cli/tools.tsindex 03b48a080e55..5b943d5ab2cf 100644--- a/services/mcp/src/cli/tools.ts+++ b/services/mcp/src/cli/tools.ts@@ -1,5 +1,6 @@import { TOOL_MAP } from '@/tools'import { GENERATED_TOOL_MAP } from '@/tools/generated'+import { mergeToolFactories } from '@/tools/mergeToolFactories'import { type ToolDefinition, getToolDefinition, getToolsForFeatures } from '@/tools/toolDefinitions'import type { Tool, ToolBase, ZodObjectAny } from '@/tools/types'@@ -22,7 +23,11 @@ function materializeTool(}export function getCliTools(options: CliToolOptions = {}): Tool<ZodObjectAny>[] {- const factories: Record<string, () => ToolBase<ZodObjectAny>> = { ...TOOL_MAP, ...GENERATED_TOOL_MAP }+ // Hand-written TOOL_MAP wins on collision (same as tool-catalog / getToolsFromContext).+ const factories: Record<string, () => ToolBase<ZodObjectAny>> = mergeToolFactories({+ generated: GENERATED_TOOL_MAP,+ handwritten: TOOL_MAP,+ })const names = getToolsForFeatures({aiConsentGiven: options.aiConsentGiven,})diff --git a/services/mcp/src/hono/tool-catalog.ts b/services/mcp/src/hono/tool-catalog.tsindex c2a252d5cc5f..4015578f6d4b 100644--- a/services/mcp/src/hono/tool-catalog.ts+++ b/services/mcp/src/hono/tool-catalog.ts@@ -3,6 +3,7 @@ import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-scimport type { Tool as McpTool } from '@modelcontextprotocol/sdk/types.js'import { hasScopes } from '@/lib/api'+import { mergeToolFactories } from '@/tools/mergeToolFactories'import {type ToolDefinition,type ToolFilterOptions,@@ -113,7 +114,11 @@ export class ToolCatalog {import('@/tools/generated'),])- const allFactories: Record<string, () => ToolBase<ZodObjectAny>> = { ...TOOL_MAP, ...GENERATED_TOOL_MAP }+ // Hand-written TOOL_MAP wins on collision (e.g. update-feature-flag group merge).+ const allFactories: Record<string, () => ToolBase<ZodObjectAny>> = mergeToolFactories({+ generated: GENERATED_TOOL_MAP,+ handwritten: TOOL_MAP,+ })const defs = getToolDefinitions()diff --git a/services/mcp/src/tools/featureFlags/preserveGroupTargeting.ts b/services/mcp/src/tools/featureFlags/preserveGroupTargeting.tsnew file mode 100644index 000000000000..e36862165e27--- /dev/null+++ b/services/mcp/src/tools/featureFlags/preserveGroupTargeting.ts@@ -0,0 +1,284 @@+/**+ * Preserve group-based feature-flag targeting when MCP agents send partial `filters`.+ * Agents rebuild release conditions with only `key` / `operator` / `value`, and the API+ * reads an omitted property `type` as person, which silently converts a group flag to a+ * person flag (PostHog/posthog#46501).+ *+ * `aggregation_group_type_index: null` means person aggregation. Only a missing key is+ * filled from the existing flag.+ *+ * A condition set pinned to person aggregation never gains group targeting. A set is+ * pinned when the payload clears aggregation with an explicit null, or when it carries an+ * explicit person, cohort, or flag property without setting a group index itself. This+ * mirrors check_property_types_match_aggregation in+ * products/feature_flags/backend/filters_validation.py, which rejects a group-aggregated+ * set holding a non-group property.+ *+ * `super_groups` is ignored: the flags API drops it from writes+ * (LEGACY_UNKNOWN_FILTER_KEYS in products/feature_flags/backend/api/filters_schema.py).+ */++export type FlagProperty = {+ key?: string+ type?: string | null+ group_type_index?: number | null+ operator?: string+ value?: unknown+ [key: string]: unknown+}++export type FlagConditionGroup = {+ properties?: FlagProperty[] | null+ rollout_percentage?: number | null+ variant?: string | null+ aggregation_group_type_index?: number | null+ [key: string]: unknown+}++export type FlagFilters = {+ groups?: FlagConditionGroup[] | null+ super_groups?: FlagConditionGroup[] | null+ aggregation_group_type_index?: number | null+ multivariate?: unknown+ payloads?: unknown+ [key: string]: unknown+}++function isPresentType(type: unknown): type is string {+ return typeof type === 'string' && type.length > 0+}++function isPresentGroupIndex(index: unknown): index is number {+ return typeof index === 'number' && Number.isFinite(index)+}++function explicitlyClearsAggregation(obj: Record<string, unknown> | null | undefined): boolean {+ return (+ !!obj &&+ Object.prototype.hasOwnProperty.call(obj, 'aggregation_group_type_index') &&+ !isPresentGroupIndex(obj.aggregation_group_type_index)+ )+}++/** Indexed across all groups so a reordered or collapsed group can still be matched. */+function indexExistingProperties(existing: FlagFilters | null | undefined): Map<string, FlagProperty[]> {+ const map = new Map<string, FlagProperty[]>()+ const groups = existing?.groups+ if (!Array.isArray(groups)) {+ return map+ }+ for (const group of groups) {+ const props = group?.properties+ if (!Array.isArray(props)) {+ continue+ }+ for (const prop of props) {+ if (!prop || typeof prop.key !== 'string' || prop.key.length === 0) {+ continue+ }+ const list = map.get(prop.key) ?? []+ list.push(prop)+ map.set(prop.key, list)+ }+ }+ return map+}++function pickMatchingExisting(+ candidates: FlagProperty[] | undefined,+ incoming: FlagProperty+): FlagProperty | undefined {+ if (!candidates || candidates.length === 0) {+ return undefined+ }+ if (incoming.operator) {+ const byOp = candidates.find((c) => c.operator === incoming.operator)+ if (byOp) {+ return byOp+ }+ }+ return candidates.find((c) => c.type === 'group') ?? candidates[0]+}++function resolveGroupIndex(+ pinnedToPerson: boolean,+ explicitIndex: unknown,+ fallbackIndex: number | undefined+): number | undefined {+ if (pinnedToPerson) {+ return undefined+ }+ return isPresentGroupIndex(explicitIndex) ? explicitIndex : fallbackIndex+}++function mergeProperty(+ incoming: FlagProperty,+ existingProp: FlagProperty | undefined,+ fallbackGroupTypeIndex: number | undefined,+ canCarryGroupTargeting: boolean+): FlagProperty {+ const out: FlagProperty = { ...incoming }++ if (!isPresentType(out.type) && existingProp && isPresentType(existingProp.type)) {+ // Leaving the type unset makes the API report the property the agent actually+ // sent. Restoring `group` here would name fields the agent never sent.+ if (canCarryGroupTargeting || existingProp.type !== 'group') {+ out.type = existingProp.type+ }+ }++ if (canCarryGroupTargeting && !isPresentType(out.type) && isPresentGroupIndex(fallbackGroupTypeIndex)) {+ out.type = 'group'+ }++ if (out.type === 'group' && !isPresentGroupIndex(out.group_type_index)) {+ if (existingProp && isPresentGroupIndex(existingProp.group_type_index)) {+ out.group_type_index = existingProp.group_type_index+ } else if (isPresentGroupIndex(fallbackGroupTypeIndex)) {+ out.group_type_index = fallbackGroupTypeIndex+ }+ }++ return out+}++type MergeConditionOptions = {+ /** Restore set-level aggregation only from a same-index existing group (not a fallback group). */+ allowAggregationRestore: boolean+ /** The payload cleared aggregation with an explicit null, so no group index is restored. */+ incomingClearsAggregation: boolean+}++function mergeConditionGroup(+ incoming: FlagConditionGroup,+ propertySourceGroup: FlagConditionGroup | undefined,+ flagLevelGroupIndex: number | undefined,+ crossGroupPropsByKey: Map<string, FlagProperty[]>,+ options: MergeConditionOptions+): FlagConditionGroup {+ const out: FlagConditionGroup = { ...incoming }++ // One explicit person, cohort, or flag property stops this set from keeping or+ // gaining group targeting. An explicit incoming group index still wins, and the API+ // then reports the contradiction in the agent's own payload.+ const hasExplicitNonGroupProperty =+ Array.isArray(incoming.properties) &&+ incoming.properties.some((p) => isPresentType(p?.type) && p.type !== 'group')+ const propertiesPinSetToPerson =+ hasExplicitNonGroupProperty && !isPresentGroupIndex(out.aggregation_group_type_index)+ if (propertiesPinSetToPerson) {+ out.aggregation_group_type_index = null+ }++ const pinnedToPerson = options.incomingClearsAggregation || propertiesPinSetToPerson++ // Fill only when the key is absent. An explicit null means person aggregation.+ if (+ options.allowAggregationRestore &&+ !pinnedToPerson &&+ !Object.prototype.hasOwnProperty.call(out, 'aggregation_group_type_index') &&+ propertySourceGroup &&+ isPresentGroupIndex(propertySourceGroup.aggregation_group_type_index)+ ) {+ out.aggregation_group_type_index = propertySourceGroup.aggregation_group_type_index+ }++ const effectiveGroupIndex = resolveGroupIndex(pinnedToPerson, out.aggregation_group_type_index, flagLevelGroupIndex)++ if (Array.isArray(out.properties)) {+ const sameGroupByKey = new Map<string, FlagProperty[]>()+ if (Array.isArray(propertySourceGroup?.properties)) {+ for (const p of propertySourceGroup.properties) {+ if (p && typeof p.key === 'string') {+ const list = sameGroupByKey.get(p.key) ?? []+ list.push(p)+ sameGroupByKey.set(p.key, list)+ }+ }+ }++ out.properties = out.properties.map((prop) => {+ if (!prop || typeof prop !== 'object') {+ return prop+ }+ if (typeof prop.key !== 'string') {+ return prop+ }+ // Cross-group matching covers groups the payload reordered or collapsed.+ const existingProp =+ pickMatchingExisting(sameGroupByKey.get(prop.key), prop) ??+ pickMatchingExisting(crossGroupPropsByKey.get(prop.key), prop)+ return mergeProperty(prop, existingProp, effectiveGroupIndex, !pinnedToPerson)+ })+ }++ return out+}++/**+ * Merge incoming MCP filters with the flag's current filters. Explicitly set incoming+ * values always win, `null` included. Only missing `type`, `group_type_index`, and+ * `aggregation_group_type_index` keys are filled from the existing flag.+ */+export function preserveGroupTargetingFilters(+ existing: FlagFilters | null | undefined,+ incoming: FlagFilters | null | undefined+): FlagFilters | null | undefined {+ if (!incoming || typeof incoming !== 'object') {+ return incoming+ }++ const result: FlagFilters = { ...incoming }++ const existingFlagGroupIndex = isPresentGroupIndex(existing?.aggregation_group_type_index)+ ? existing!.aggregation_group_type_index!+ : undefined++ const incomingClearsAggregation = explicitlyClearsAggregation(incoming as Record<string, unknown>)++ // The flag-level index is the UI's "Target by" group type.+ if (+ !incomingClearsAggregation &&+ !Object.prototype.hasOwnProperty.call(result, 'aggregation_group_type_index') &&+ isPresentGroupIndex(existingFlagGroupIndex)+ ) {+ result.aggregation_group_type_index = existingFlagGroupIndex+ }++ const effectiveFlagGroupIndex = resolveGroupIndex(+ incomingClearsAggregation,+ result.aggregation_group_type_index,+ existingFlagGroupIndex+ )++ if (Array.isArray(result.groups)) {+ const crossGroupPropsByKey = indexExistingProperties(existing)+ const existingGroups = Array.isArray(existing?.groups) ? existing!.groups! : []+ result.groups = result.groups.map((group, index) => {+ if (!group || typeof group !== 'object') {+ return group+ }++ const sameIndexGroup = existingGroups[index]+ // Aggregation restores only from the same index, so appending a person set+ // cannot inherit another set's group index. Property restore is looser.+ const propertySourceGroup =+ sameIndexGroup ??+ existingGroups.find((g) => isPresentGroupIndex(g?.aggregation_group_type_index)) ??+ existingGroups[0]++ const groupClearsAggregation = explicitlyClearsAggregation(group as Record<string, unknown>)++ return mergeConditionGroup(group, propertySourceGroup, effectiveFlagGroupIndex, crossGroupPropsByKey, {+ allowAggregationRestore: sameIndexGroup !== undefined,+ // A flag-level clear only pins sets that omit the key. A set that carries its own+ // index keeps it, which matches the backend's per-set fallback in filters_validation.py.+ incomingClearsAggregation:+ groupClearsAggregation ||+ (incomingClearsAggregation && !isPresentGroupIndex(group.aggregation_group_type_index)),+ })+ })+ }++ return result+}diff --git a/services/mcp/src/tools/featureFlags/updateFeatureFlag.ts b/services/mcp/src/tools/featureFlags/updateFeatureFlag.tsnew file mode 100644index 000000000000..60e64542fde8--- /dev/null+++ b/services/mcp/src/tools/featureFlags/updateFeatureFlag.ts@@ -0,0 +1,46 @@+/**+ * Hand-written override of generated `update-feature-flag`. It intercepts only+ * `filters`, to preserve group targeting (PostHog/posthog#46501), and delegates+ * everything else to the codegen factory. Re-sync is needed only if the generated+ * tool name or the `filters` param shape changes.+ *+ * Title, description, and scopes still resolve from the generated+ * `update-feature-flag` entry, not from this file.+ */+import type { Schemas } from '@/api/generated'+import { GENERATED_TOOLS } from '@/tools/generated/feature_flags'+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'++import { preserveGroupTargetingFilters, type FlagFilters } from './preserveGroupTargeting'++type UpdateParams = {+ id: number | string+ filters?: FlagFilters+ [key: string]: unknown+}++export default function updateFeatureFlagPreservingGroups(): ToolBase<ZodObjectAny> {+ const generated = GENERATED_TOOLS['update-feature-flag']!()++ return {+ // Spreading the generated tool carries over any field codegen adds later.+ ...generated,+ handler: async (context: Context, params: UpdateParams) => {+ if (params.filters === undefined) {+ return generated.handler(context, params)+ }++ // No try/catch: a failed GET must abort before the PATCH. PATCHing raw+ // filters without the merge is what silently demotes group flags.+ const projectId = await context.stateManager.getProjectId()+ const existing = await context.api.request<Schemas.FeatureFlag>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/`,+ })+ const existingFilters = (existing?.filters ?? undefined) as FlagFilters | undefined+ const mergedFilters = preserveGroupTargetingFilters(existingFilters, params.filters)++ return generated.handler(context, { ...params, filters: mergedFilters })+ },+ }+}diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.tsindex 93af7e5847f9..5be432a27d35 100644--- a/services/mcp/src/tools/generated/feature_flags.ts+++ b/services/mcp/src/tools/generated/feature_flags.ts@@ -837,6 +837,9 @@ const UpdateFeatureFlagSchema = () => {.extend(FeatureFlagsPartialUpdateBody.shape).extend({id: z.preprocess(castStringToInt, FeatureFlagsPartialUpdateParams.shape['id']),+ filters: FeatureFlagsPartialUpdateBody.shape['filters'].describe(+ 'Full release-condition object (replaces filters at the API). For group flags set aggregation_group_type_index and property type "group" + group_type_index. Omitted type / group_type_index / aggregation_group_type_index are filled from the existing flag to prevent silent person demotion (see #46501).'+ ),is_remote_configuration: FeatureFlagsPartialUpdateBody.shape['is_remote_configuration'].describe('Whether this flag delivers a payload instead of gating a feature (Remote Config mode). When true, set the delivered payload through the `filters` param under `filters.payloads.true` as a JSON-encoded string. There is no dedicated payload parameter.'),diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.tsindex bd98d7bc3e8f..dc782ef1e4c2 100644--- a/services/mcp/src/tools/index.ts+++ b/services/mcp/src/tools/index.ts@@ -10,8 +10,9 @@ import debugMcpUiApps from './debug/debugMcpUiApps'// Experiments (hand-written — CRUD + lifecycle are codegen in generated/experiments.ts)import getExperimentResults from './experiments/getResults'import experimentListDeprecated from './experiments/listDeprecated'-// Feature flags (get-definition-by-key is hand-written; get-definition-by-id is codegen)+// Feature flagsimport featureFlagGetDefinitionByKey from './featureFlags/getDefinitionByKey'+import updateFeatureFlagPreservingGroups from './featureFlags/updateFeatureFlag'// Feedbackimport submitFeedback from './feedback/submit'// Generated tools (from definitions/*.yaml)@@ -21,6 +22,7 @@ import queryInsight from './insights/query'// Links (utility — builds canonical app URLs from the frontend's route table)import generateAppUrl from './links/generate-app-url'import loopsReview from './loops/loopsReview'+import { mergeToolFactories } from './mergeToolFactories'// Notebooks (edit + cell tools are hand-written — generated CRUD lives in generated/notebooks.ts)import notebookAddCell from './notebooks/addCell'import notebookCreateMarkdown from './notebooks/createMarkdown'@@ -87,6 +89,7 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {// Feature flags (get-definition-by-key is hand-written; get-definition by numeric id is codegen)'feature-flag-get-definition-by-key': featureFlagGetDefinitionByKey,+ 'update-feature-flag': updateFeatureFlagPreservingGroups,'path-cleaning-rules-update': updatePathCleaning,@@ -159,7 +162,7 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {/** Build one tool by name, from the hand-written and generated registries alike. */function resolveToolBase(name: string): ToolBase<ZodObjectAny> | undefined {- return { ...TOOL_MAP, ...GENERATED_TOOL_MAP }[name]?.()+ return mergeToolFactories({ generated: GENERATED_TOOL_MAP, handwritten: TOOL_MAP })[name]?.()}export const getToolsFromContext = async (@@ -169,7 +172,7 @@ export const getToolsFromContext = async (// Check org AI consent to gate tools that use LLMs internally (cached in StateManager)const aiConsentGiven = await context.stateManager.getAiConsentGiven()const effectiveOptions = aiConsentGiven !== undefined ? { ...options, aiConsentGiven } : options- const effectiveMap = { ...TOOL_MAP, ...GENERATED_TOOL_MAP }+ const effectiveMap = mergeToolFactories({ generated: GENERATED_TOOL_MAP, handwritten: TOOL_MAP })const excludeTools = options?.excludeTools ?? []const allowedToolNames = getFilteredToolNames(effectiveOptions).filter((name) => !excludeTools.includes(name))const toolBases: ToolBase<ZodObjectAny>[] = []diff --git a/services/mcp/src/tools/mergeToolFactories.ts b/services/mcp/src/tools/mergeToolFactories.tsnew file mode 100644index 000000000000..dfb3d6e1b977--- /dev/null+++ b/services/mcp/src/tools/mergeToolFactories.ts@@ -0,0 +1,27 @@+import type { ToolBase, ZodObjectAny } from '@/tools/types'++/**+ * Merge codegen and hand-written tool factories. Hand-written entries win on key+ * collision. Use this helper at every merge site rather than inlining a spread, so+ * the sites cannot drift apart.+ *+ * The arguments are named rather than positional because both maps have the same+ * type. A swapped positional call would invert precedence with no type error, and+ * only the one colliding tool would behave differently.+ */+export function mergeToolFactories({+ generated,+ handwritten,+}: {+ generated: Record<string, () => ToolBase<ZodObjectAny>>+ handwritten: Record<string, () => ToolBase<ZodObjectAny>>+}): Record<string, () => ToolBase<ZodObjectAny>> {+ // Key order is observable: it sets the listing order and which tools the compact+ // domain index is built from. Laying hand-written keys down first keeps the order+ // the catalog had before any override existed.+ const merged: Record<string, () => ToolBase<ZodObjectAny>> = { ...handwritten, ...generated }+ for (const [name, factory] of Object.entries(handwritten)) {+ merged[name] = factory+ }+ return merged+}diff --git a/services/mcp/tests/shared/test-utils.ts b/services/mcp/tests/shared/test-utils.tsindex aba325ed37e2..9800d643abd5 100644--- a/services/mcp/tests/shared/test-utils.ts+++ b/services/mcp/tests/shared/test-utils.ts@@ -8,6 +8,7 @@ import { StateManager } from '@/lib/StateManager'import type { InsightQuery } from '@/schema/query'import { GENERATED_TOOL_MAP } from '@/tools/generated'import { TOOL_MAP } from '@/tools/index'+import { mergeToolFactories } from '@/tools/mergeToolFactories'import type { Context, Tool, ToolBase, ZodObjectAny } from '@/tools/types'export const API_BASE_URL = process.env.TEST_POSTHOG_API_BASE_URL || 'http://localhost:8010'@@ -171,7 +172,8 @@ export function getToolByName(let name: stringif (typeof nameOrMap === 'string') {- toolMap = { ...TOOL_MAP, ...GENERATED_TOOL_MAP }+ // Hand-written overrides win (same as production catalogs / CLI).+ toolMap = mergeToolFactories({ generated: GENERATED_TOOL_MAP, handwritten: TOOL_MAP })name = nameOrMap} else {toolMap = nameOrMapdiff --git a/services/mcp/tests/tools/featureFlags.integration.test.ts b/services/mcp/tests/tools/featureFlags.integration.test.tsindex ceef62e58e3b..4a2dfa5c350c 100644--- a/services/mcp/tests/tools/featureFlags.integration.test.ts+++ b/services/mcp/tests/tools/featureFlags.integration.test.ts@@ -8,6 +8,7 @@ import {createTestClient,createTestContext,generateUniqueKey,+ getToolByName,parseToolResponse,setActiveProjectAndOrg,validateEnvironmentVariables,@@ -274,6 +275,60 @@ describe('Feature flags', { concurrent: false }, () => {expect(updatedFlag._posthogUrl).toContain('/feature_flags/')})+ it('keeps group targeting when partial filters omit the group fields', async () => {+ // Resolved the way production does, so the hand-written override wins. Without+ // the merge the untyped property below reaches the API as a person property.+ const overrideUpdateTool = getToolByName('update-feature-flag')++ const createResult = await createTool.handler(context, {+ name: 'Group targeted flag',+ key: generateUniqueKey('group-targeting'),+ filters: {+ aggregation_group_type_index: 0,+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [+ {+ key: 'plan',+ type: 'group',+ group_type_index: 0,+ operator: 'exact',+ value: 'enterprise',+ },+ ],+ rollout_percentage: 100,+ },+ ],+ },+ active: true,+ })+ const createdFlag = parseToolResponse(createResult)+ createdResources.featureFlags.push(createdFlag.id)++ // The shape agents actually send: key, operator and value only.+ const updateResult = await overrideUpdateTool.handler(context, {+ id: createdFlag.id,+ filters: {+ groups: [+ {+ properties: [{ key: 'plan', operator: 'exact', value: 'pro' }],+ rollout_percentage: 100,+ },+ ],+ },+ })+ const updatedFlag = parseToolResponse(updateResult)++ // Flag-level aggregation survives the backend's shallow merge on its own, so the+ // property assertions below are what actually cover the fix.+ expect(updatedFlag.filters.aggregation_group_type_index).toBe(0)+ const updatedProperty = updatedFlag.filters.groups[0].properties[0]+ expect(updatedProperty.value).toBe('pro')+ expect(updatedProperty.type).toBe('group')+ expect(updatedProperty.group_type_index).toBe(0)+ })+it('should update feature flag filters', async () => {const createResult = await createTool.handler(context, {name: 'Filter update flag',diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.jsonindex c5cdbf250c6a..c64396aef173 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json@@ -54,7 +54,7 @@"description": "Where this flag is allowed to evaluate — `server` (server-side SDKs only), `client` (client-side SDKs only), or `all` (both). Defaults to `all`."},"filters": {- "description": "Feature flag targeting configuration.",+ "description": "Full release-condition object (replaces filters at the API). For group flags set aggregation_group_type_index and property type \"group\" + group_type_index. Omitted type / group_type_index / aggregation_group_type_index are filled from the existing flag to prevent silent person demotion (see #46501).","properties": {"aggregation_group_type_index": {"anyOf": [diff --git a/services/mcp/tests/unit/merge-tool-factories.test.ts b/services/mcp/tests/unit/merge-tool-factories.test.tsnew file mode 100644index 000000000000..70188841e306--- /dev/null+++ b/services/mcp/tests/unit/merge-tool-factories.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest'+import { z } from 'zod'++import { mergeToolFactories } from '@/tools/mergeToolFactories'+import type { ToolBase, ZodObjectAny } from '@/tools/types'++const factory = (name: string, tag: string): (() => ToolBase<ZodObjectAny>) => {+ return () =>+ ({+ name,+ schema: z.object({}),+ handler: async () => tag,+ _tag: tag,+ }) as ToolBase<ZodObjectAny> & { _tag: string }+}++describe('mergeToolFactories', () => {+ it('lets hand-written factories win on key collision', async () => {+ const generated = {+ 'update-feature-flag': factory('update-feature-flag', 'generated'),+ 'other-tool': factory('other-tool', 'generated'),+ }+ const handwritten = {+ 'update-feature-flag': factory('update-feature-flag', 'handwritten'),+ }++ const merged = mergeToolFactories({ generated, handwritten })+ expect(await merged['update-feature-flag']!().handler({} as never, {} as never)).toBe('handwritten')+ expect(await merged['other-tool']!().handler({} as never, {} as never)).toBe('generated')+ })++ it('keeps hand-written keys ahead of generated-only keys', () => {+ // Key order decides the order tools are listed in and which ones the compact+ // domain index is built from, so overriding a tool must not reorder the catalog.+ const generated = {+ 'action-create': factory('action-create', 'generated'),+ 'update-feature-flag': factory('update-feature-flag', 'generated'),+ }+ const handwritten = {+ 'update-feature-flag': factory('update-feature-flag', 'handwritten'),+ 'feature-flag-get-definition-by-key': factory('feature-flag-get-definition-by-key', 'handwritten'),+ }++ expect(Object.keys(mergeToolFactories({ generated, handwritten }))).toEqual([+ 'update-feature-flag',+ 'feature-flag-get-definition-by-key',+ 'action-create',+ ])+ })+})diff --git a/services/mcp/tests/unit/nested-query-input-example.test.ts b/services/mcp/tests/unit/nested-query-input-example.test.tsindex fd5ab369fe9b..9ae044f5239a 100644--- a/services/mcp/tests/unit/nested-query-input-example.test.ts+++ b/services/mcp/tests/unit/nested-query-input-example.test.ts@@ -3,6 +3,7 @@ import { z } from 'zod'import { TOOL_MAP } from '@/tools'import { GENERATED_TOOL_MAP } from '@/tools/generated'+import { mergeToolFactories } from '@/tools/mergeToolFactories'import { getToolDefinitions } from '@/tools/toolDefinitions'import type { ToolBase, ZodObjectAny } from '@/tools/types'@@ -70,7 +71,10 @@ function jsonExamples(description: string): unknown[] {return examples}-const allFactories: Record<string, () => ToolBase<ZodObjectAny>> = { ...TOOL_MAP, ...GENERATED_TOOL_MAP }+const allFactories: Record<string, () => ToolBase<ZodObjectAny>> = mergeToolFactories({+ generated: GENERATED_TOOL_MAP,+ handwritten: TOOL_MAP,+})const definitions = getToolDefinitions()const wrapperTools = Object.entries(allFactories).flatMap(([name, factory]) => {diff --git a/services/mcp/tests/unit/preserve-group-targeting.test.ts b/services/mcp/tests/unit/preserve-group-targeting.test.tsnew file mode 100644index 000000000000..8482bffb45fa--- /dev/null+++ b/services/mcp/tests/unit/preserve-group-targeting.test.ts@@ -0,0 +1,495 @@+import { describe, expect, it } from 'vitest'++import { preserveGroupTargetingFilters } from '@/tools/featureFlags/preserveGroupTargeting'++describe('preserveGroupTargetingFilters', () => {+ const existingGroupFlag = {+ aggregation_group_type_index: 0,+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [+ {+ key: 'plan',+ type: 'group',+ group_type_index: 0,+ operator: 'exact',+ value: 'enterprise',+ },+ ],+ rollout_percentage: 100,+ },+ ],+ }++ it('preserves aggregation_group_type_index when omitted on update', () => {+ const incoming = {+ groups: [+ {+ properties: [{ key: 'plan', operator: 'exact', value: 'pro' }],+ rollout_percentage: 50,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existingGroupFlag, incoming)++ expect(merged?.aggregation_group_type_index).toBe(0)+ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('group')+ expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBe(0)+ expect(merged?.groups?.[0]?.properties?.[0]?.value).toBe('pro')+ expect(merged?.groups?.[0]?.rollout_percentage).toBe(50)+ expect(merged?.groups?.[0]?.aggregation_group_type_index).toBe(0)+ })++ it('does not override explicit person type and pins set to person aggregation', () => {+ const incoming = {+ groups: [+ {+ properties: [{ key: 'email', type: 'person', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existingGroupFlag, incoming)++ // The set must not carry group aggregation around a person property.+ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('person')+ expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBeUndefined()+ expect(merged?.groups?.[0]?.aggregation_group_type_index).toBeNull()+ })++ // A person-aggregated set cannot hold a group property. A key that matches an existing+ // group property must not resurrect one, or the API error names a field the agent never sent.+ it.each([+ { name: 'a key with no existing match', key: 'email', operator: 'icontains', value: '@acme.com' },+ { name: 'a key matching an existing group property', key: 'plan', operator: 'exact', value: 'pro' },+ ])('honors explicit null aggregation_group_type_index for $name', ({ key, operator, value }) => {+ const incoming = {+ aggregation_group_type_index: null,+ groups: [+ {+ aggregation_group_type_index: null,+ properties: [{ key, operator, value }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existingGroupFlag, incoming)++ expect(merged?.aggregation_group_type_index).toBeNull()+ expect(merged?.groups?.[0]?.aggregation_group_type_index).toBeNull()+ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBeUndefined()+ expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBeUndefined()+ })++ // A mixed-aggregation flag is stored with a null flag level and per-set indices, and+ // the tool tells agents to echo that back. The null must not pin a set sending its own index.+ it('keeps group targeting on a set carrying its own index when the flag level is null', () => {+ const existingMixedFlag = {+ aggregation_group_type_index: null,+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [+ { key: 'plan', type: 'group', group_type_index: 0, operator: 'exact', value: 'enterprise' },+ ],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: null,+ properties: [{ key: 'email', type: 'person', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existingMixedFlag, {+ aggregation_group_type_index: null,+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [{ key: 'plan', operator: 'exact', value: 'pro' }],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: null,+ properties: [{ key: 'email', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ ],+ })++ expect(merged?.groups?.[0]?.aggregation_group_type_index).toBe(0)+ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('group')+ expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBe(0)+ expect(merged?.groups?.[1]?.properties?.[0]?.type).toBe('person')+ })++ it('pins a set that omits the aggregation key when only the flag level is nulled', () => {+ const merged = preserveGroupTargetingFilters(existingGroupFlag, {+ aggregation_group_type_index: null,+ groups: [{ properties: [{ key: 'plan', operator: 'exact', value: 'pro' }], rollout_percentage: 100 }],+ })++ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBeUndefined()+ expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBeUndefined()+ })++ it('restores each condition set aggregation from the existing set at the same index', () => {+ const existingTwoGroupFlag = {+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [+ { key: 'plan', type: 'group', group_type_index: 0, operator: 'exact', value: 'enterprise' },+ ],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: 1,+ properties: [{ key: 'name', type: 'group', group_type_index: 1, operator: 'exact', value: 'acme' }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existingTwoGroupFlag, {+ groups: [+ { properties: [{ key: 'plan', operator: 'exact', value: 'pro' }], rollout_percentage: 100 },+ { properties: [{ key: 'name', operator: 'exact', value: 'globex' }], rollout_percentage: 100 },+ ],+ })++ expect(merged?.groups?.[1]?.aggregation_group_type_index).toBe(1)+ expect(merged?.groups?.[1]?.properties?.[0]?.group_type_index).toBe(1)+ })++ it('fills group_type_index when the agent sets type "group" but omits the index', () => {+ const merged = preserveGroupTargetingFilters(existingGroupFlag, {+ groups: [+ {+ properties: [{ key: 'plan', type: 'group', operator: 'exact', value: 'pro' }],+ rollout_percentage: 100,+ },+ ],+ })++ expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBe(0)+ })++ it('does not group-infer an untyped property in a set that also holds an explicit person property', () => {+ const incoming = {+ groups: [+ {+ properties: [+ { key: 'email', type: 'person', operator: 'icontains', value: '@acme.com' },+ { key: 'plan', operator: 'exact', value: 'pro' },+ ],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existingGroupFlag, incoming)++ expect(merged?.groups?.[0]?.aggregation_group_type_index).toBeNull()+ expect(merged?.groups?.[0]?.properties?.[1]?.type).toBeUndefined()+ expect(merged?.groups?.[0]?.properties?.[1]?.group_type_index).toBeUndefined()+ })++ it('still restores a non-group property type in a set pinned to person aggregation', () => {+ const existingPersonSetFlag = {+ aggregation_group_type_index: 0,+ groups: [+ {+ aggregation_group_type_index: null,+ properties: [{ key: 'email', type: 'person', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ ],+ }+ const incoming = {+ aggregation_group_type_index: null,+ groups: [+ {+ aggregation_group_type_index: null,+ properties: [{ key: 'email', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existingPersonSetFlag, incoming)++ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('person')+ })++ it('keeps explicit group type and index from the agent', () => {+ const incoming = {+ aggregation_group_type_index: 1,+ groups: [+ {+ properties: [+ {+ key: 'region',+ type: 'group',+ group_type_index: 1,+ operator: 'exact',+ value: 'eu',+ },+ ],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existingGroupFlag, incoming)++ expect(merged?.aggregation_group_type_index).toBe(1)+ expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBe(1)+ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('group')+ })++ it('infers type group from flag-level aggregation when property type omitted', () => {+ const existing = { aggregation_group_type_index: 2, groups: [{ properties: [], rollout_percentage: 100 }] }+ const incoming = {+ groups: [+ {+ properties: [{ key: 'tier', operator: 'exact', value: 'gold' }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existing, incoming)++ expect(merged?.aggregation_group_type_index).toBe(2)+ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('group')+ expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBe(2)+ })++ it('passes through when there is no existing flag', () => {+ const incoming = {+ groups: [+ {+ properties: [{ key: 'email', operator: 'exact', value: '[email protected]' }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(undefined, incoming)++ expect(merged?.aggregation_group_type_index).toBeUndefined()+ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBeUndefined()+ })++ it('restores group type via cross-group key match when condition groups collapse', () => {+ // Collapsing two sets into one forces the cross-group fallback.+ const existing = {+ aggregation_group_type_index: 0,+ groups: [+ {+ properties: [{ key: 'email', type: 'person', operator: 'icontains', value: '@corp.com' }],+ rollout_percentage: 100,+ },+ {+ properties: [+ {+ key: 'plan',+ type: 'group',+ group_type_index: 0,+ operator: 'exact',+ value: 'enterprise',+ },+ ],+ rollout_percentage: 50,+ },+ ],+ }+ const incoming = {+ groups: [+ {+ properties: [{ key: 'plan', operator: 'exact', value: 'pro' }],+ rollout_percentage: 75,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existing, incoming)++ expect(merged?.aggregation_group_type_index).toBe(0)+ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('group')+ expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBe(0)+ expect(merged?.groups?.[0]?.properties?.[0]?.value).toBe('pro')+ })++ it.each([+ { name: 'the operator matches the group-typed candidate', operator: 'exact', value: 'New Name' },+ { name: 'the operator matches neither candidate', operator: 'regex', value: '.*' },+ ])('restores group type and index for a duplicate key when $name', ({ operator, value }) => {+ const existing = {+ aggregation_group_type_index: 0,+ groups: [+ {+ properties: [+ { key: 'name', type: 'person', operator: 'icontains', value: 'acme' },+ {+ key: 'name',+ type: 'group',+ group_type_index: 0,+ operator: 'exact',+ value: 'Acme Corp',+ },+ ],+ rollout_percentage: 100,+ },+ ],+ }+ const incoming = {+ groups: [+ {+ properties: [{ key: 'name', operator, value }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existing, incoming)++ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('group')+ expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBe(0)+ expect(merged?.groups?.[0]?.properties?.[0]?.value).toBe(value)+ })++ it('does not copy set-level aggregation onto a newly appended condition set', () => {+ const existing = {+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [+ {+ key: 'plan',+ type: 'group',+ group_type_index: 0,+ operator: 'exact',+ value: 'enterprise',+ },+ ],+ rollout_percentage: 100,+ },+ ],+ }+ const incoming = {+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [+ {+ key: 'plan',+ type: 'group',+ group_type_index: 0,+ operator: 'exact',+ value: 'enterprise',+ },+ ],+ rollout_percentage: 100,+ },+ {+ properties: [{ key: 'email', type: 'person', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existing, incoming)++ expect(merged?.groups?.[0]?.aggregation_group_type_index).toBe(0)+ expect(merged?.groups?.[1]?.aggregation_group_type_index).toBeNull()+ expect(merged?.groups?.[1]?.properties?.[0]?.type).toBe('person')+ })++ it('restores property group_type_index from matched existing property over flag aggregation', () => {+ const existing = {+ groups: [+ {+ properties: [+ {+ key: 'region',+ type: 'group',+ group_type_index: 1,+ operator: 'exact',+ value: 'us',+ },+ ],+ rollout_percentage: 100,+ },+ ],+ }+ const incoming = {+ groups: [+ {+ properties: [{ key: 'region', operator: 'exact', value: 'eu' }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existing, incoming)++ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('group')+ expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBe(1)+ })++ it('passes through multivariate and payloads without restoring from existing', () => {+ const existing = {+ aggregation_group_type_index: 0,+ multivariate: { variants: [{ key: 'control', rollout_percentage: 100 }] },+ payloads: { control: '{"a":1}' },+ groups: existingGroupFlag.groups,+ }+ const incoming = {+ groups: [+ {+ properties: [{ key: 'plan', operator: 'exact', value: 'pro' }],+ rollout_percentage: 50,+ variant: 'treatment',+ },+ ],+ payloads: { treatment: '{"b":2}' },+ }++ const merged = preserveGroupTargetingFilters(existing, incoming)++ expect(merged?.payloads).toEqual({ treatment: '{"b":2}' })+ expect(merged?.multivariate).toBeUndefined()+ expect(merged?.groups?.[0]?.variant).toBe('treatment')+ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('group')+ })++ it('accepts group properties when both type and index are present (no strip)', () => {+ const incoming = {+ aggregation_group_type_index: 0,+ groups: [+ {+ properties: [+ {+ key: 'workspace_id',+ type: 'group',+ group_type_index: 0,+ operator: 'exact',+ value: 'ws-1',+ },+ ],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(null, incoming)+ expect(merged).toEqual(incoming)+ })+})diff --git a/services/mcp/tests/unit/schema.feature-flag-filters.test.ts b/services/mcp/tests/unit/schema.feature-flag-filters.test.tsindex b6b9f63af26f..222a9a1d2fa9 100644--- a/services/mcp/tests/unit/schema.feature-flag-filters.test.ts+++ b/services/mcp/tests/unit/schema.feature-flag-filters.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from 'vitest'-import { FeatureFlagsCreateBody, FeatureFlagsListQueryParams } from '@/generated/feature_flags/api'+import {+ FeatureFlagsCreateBody,+ FeatureFlagsListQueryParams,+ FeatureFlagsPartialUpdateBody,+} from '@/generated/feature_flags/api'import { SurveysCreateBody } from '@/generated/surveys/api'describe('Feature flag filter schemas', () => {@@ -256,4 +260,41 @@ describe('Filter groups schema', () => {expect(result.success).toBe(true)})++ it('should accept group property filters with type and group_type_index (#46501)', () => {+ const payload = {+ aggregation_group_type_index: 0,+ groups: [+ {+ properties: [+ {+ key: 'plan',+ type: 'group',+ group_type_index: 0,+ value: 'enterprise',+ operator: 'exact',+ },+ ],+ rollout_percentage: 100,+ },+ ],+ }++ const result = filtersSchema.safeParse(payload)++ expect(result.success).toBe(true)+ if (result.success) {+ const prop = result.data?.groups?.[0]?.properties?.[0] as {+ type?: string+ group_type_index?: number+ }+ expect(prop?.type).toBe('group')+ expect(prop?.group_type_index).toBe(0)+ expect(result.data?.aggregation_group_type_index).toBe(0)+ }++ // update-feature-flag advertises FeatureFlagsPartialUpdateBody.filters (separate copy).+ const updateResult = FeatureFlagsPartialUpdateBody().shape.filters.safeParse(payload)+ expect(updateResult.success).toBe(true)+ })})diff --git a/services/mcp/tests/unit/tool-catalog.test.ts b/services/mcp/tests/unit/tool-catalog.test.tsindex 633f6b2fa30e..8d9b2929c7ff 100644--- a/services/mcp/tests/unit/tool-catalog.test.ts+++ b/services/mcp/tests/unit/tool-catalog.test.ts@@ -47,12 +47,20 @@ vi.mock('@/tools', () => ({TOOL_MAP: {'tool-a': () => makeToolBase('tool-a'),'tool-b': () => makeToolBase('tool-b'),+ 'update-feature-flag': () =>+ makeToolBase('update-feature-flag', {+ schema: z.object({ source: z.literal('handwritten') }),+ }),},}))vi.mock('@/tools/generated', () => ({GENERATED_TOOL_MAP: {'gen-tool-c': () => makeToolBase('gen-tool-c'),+ 'update-feature-flag': () =>+ makeToolBase('update-feature-flag', {+ schema: z.object({ source: z.literal('generated') }),+ }),},}))@@ -60,6 +68,7 @@ const DEFINITIONS: Record<string, FakeDefinition> = {'tool-a': fakeDef({ required_scopes: ['project:read'] }),'tool-b': fakeDef({ feature: 'insights', annotations: { ...fakeDef().annotations, readOnlyHint: true } }),'gen-tool-c': fakeDef({ required_scopes: ['action:write'] }),+ 'update-feature-flag': fakeDef({ required_scopes: ['feature_flag:write'] }),}vi.mock('@/tools/toolDefinitions', () => ({@@ -176,9 +185,20 @@ describe('ToolCatalog', () => {})it('should return all tools when no filters applied', () => {- const tools = catalog.getFilteredTools({ scopes: ['project:read', 'action:write'] })+ const tools = catalog.getFilteredTools({+ scopes: ['project:read', 'action:write', 'feature_flag:write'],+ })const names = tools.map((t) => t.name).sort()- expect(names).toEqual(['gen-tool-c', 'tool-a', 'tool-b'])+ expect(names).toEqual(['gen-tool-c', 'tool-a', 'tool-b', 'update-feature-flag'])+ })++ it('should prefer hand-written factory when name collides with generated', () => {+ const tools = catalog.getFilteredTools({ scopes: ['feature_flag:write'] })+ const update = tools.find((t) => t.name === 'update-feature-flag')+ expect(update).toBeTruthy()+ // Schema is from the TOOL_MAP mock (handwritten), not GENERATED_TOOL_MAP.+ expect(update!.schema.safeParse({ source: 'handwritten' }).success).toBe(true)+ expect(update!.schema.safeParse({ source: 'generated' }).success).toBe(false)})it('should exclude tools by name', () => {diff --git a/services/mcp/tests/unit/tool-name-validation.test.ts b/services/mcp/tests/unit/tool-name-validation.test.tsindex baac6597331c..5168240bd6a9 100644--- a/services/mcp/tests/unit/tool-name-validation.test.ts+++ b/services/mcp/tests/unit/tool-name-validation.test.ts@@ -2,11 +2,20 @@ import { describe, expect, it } from 'vitest'import { TOOL_MAP } from '@/tools'import { GENERATED_TOOL_MAP } from '@/tools/generated'+import { mergeToolFactories } from '@/tools/mergeToolFactories'import { MAX_TOOL_NAME_LENGTH, TOOL_NAME_PATTERN } from '../../scripts/yaml-config-schema'describe('Tool name validation', () => {- const allTools = { ...TOOL_MAP, ...GENERATED_TOOL_MAP }+ const allTools = mergeToolFactories({ generated: GENERATED_TOOL_MAP, handwritten: TOOL_MAP })++ // A hand-written tool that shares a generated tool's name shadows it everywhere, so a+ // newly generated tool colliding with one would silently replace it.+ it('shadows only the generated tools it means to', () => {+ const shadowed = Object.keys(TOOL_MAP).filter((name) => name in GENERATED_TOOL_MAP)++ expect(shadowed.sort()).toEqual(['update-feature-flag'])+ })it.each(Object.keys(allTools))('%s — name matches map key, length, and pattern', (mapKey) => {const factory = allTools[mapKey]!diff --git a/services/mcp/tests/unit/update-feature-flag-preserving-groups.test.ts b/services/mcp/tests/unit/update-feature-flag-preserving-groups.test.tsnew file mode 100644index 000000000000..99e902760095--- /dev/null+++ b/services/mcp/tests/unit/update-feature-flag-preserving-groups.test.ts@@ -0,0 +1,134 @@+import { describe, expect, it, vi } from 'vitest'++import updateFeatureFlagPreservingGroups from '@/tools/featureFlags/updateFeatureFlag'+import type { Context } from '@/tools/types'++type ApiRequestArgs = { method: string; path: string; body?: unknown }++function requestArgs(requestMock: ReturnType<typeof vi.fn>, callIndex: number): ApiRequestArgs {+ const call = requestMock.mock.calls[callIndex]+ if (!call) {+ throw new Error(`Expected an api.request call at index ${callIndex}`)+ }+ return call[0] as ApiRequestArgs+}++function createMockContext(requestMock: ReturnType<typeof vi.fn>): Context {+ return {+ api: {+ request: requestMock,+ getProjectBaseUrl: (projectId: string) => `https://us.posthog.com/project/${projectId}`,+ } as any,+ stateManager: { getProjectId: vi.fn().mockResolvedValue('42') } as any,+ env: {} as any,+ sessionManager: {} as any,+ cache: {} as any,+ getDistinctId: async () => 'test-distinct-id',+ trackEvent: async () => {},+ }+}++describe('update-feature-flag preserving groups', () => {+ const tool = updateFeatureFlagPreservingGroups()++ it('GETs existing flag, merges group fields into filters, then PATCHes', async () => {+ const existing = {+ id: 9,+ key: 'workspace-rollout',+ filters: {+ aggregation_group_type_index: 0,+ groups: [+ {+ properties: [+ {+ key: 'plan',+ type: 'group',+ group_type_index: 0,+ operator: 'exact',+ value: 'enterprise',+ },+ ],+ rollout_percentage: 100,+ },+ ],+ },+ }+ const patched = { ...existing, filters: { ...existing.filters, groups: [] } }++ const request = vi+ .fn()+ .mockResolvedValueOnce(existing) // GET+ .mockResolvedValueOnce(patched) // PATCH via generated handler++ // The merge reads key presence, so a codegen default on an aggregation key would turn it+ // into a no-op. Params built by hand never catch that, so parse through the tool's own schema.+ const params = tool.schema.parse({+ id: 9,+ name: 'Renamed',+ filters: {+ groups: [+ {+ properties: [{ key: 'plan', operator: 'exact', value: 'pro' }],+ rollout_percentage: 50,+ },+ ],+ },+ })++ const result = await tool.handler(createMockContext(request), params)++ expect(request).toHaveBeenCalledTimes(2)+ expect(requestArgs(request, 0)).toMatchObject({+ method: 'GET',+ path: '/api/projects/42/feature_flags/9/',+ })+ expect(requestArgs(request, 1)).toMatchObject({+ method: 'PATCH',+ path: '/api/projects/42/feature_flags/9/',+ })+ const patchBody = requestArgs(request, 1).body as {+ name?: string+ filters: {+ aggregation_group_type_index?: number+ groups: Array<{ properties: Array<{ type?: string; group_type_index?: number; value?: unknown }> }>+ }+ }+ expect(patchBody).toMatchObject({ name: 'Renamed' })+ expect(patchBody.filters.aggregation_group_type_index).toBe(0)+ expect(patchBody.filters.groups[0]?.properties[0]?.type).toBe('group')+ expect(patchBody.filters.groups[0]?.properties[0]?.group_type_index).toBe(0)+ expect(patchBody.filters.groups[0]?.properties[0]?.value).toBe('pro')+ expect(result).toMatchObject({ id: 9 })+ })++ it('surfaces GET failures instead of PATCHing unmerged filters', async () => {+ const request = vi.fn().mockRejectedValueOnce(new Error('HTTP 429: rate limited'))++ await expect(+ tool.handler(createMockContext(request), {+ id: 9,+ filters: {+ groups: [+ {+ properties: [{ key: 'plan', operator: 'exact', value: 'pro' }],+ rollout_percentage: 50,+ },+ ],+ },+ })+ ).rejects.toThrow(/429|rate limited/i)++ expect(request).toHaveBeenCalledTimes(1)+ expect(requestArgs(request, 0).method).toBe('GET')+ })++ it('forwards updates without filters without an extra GET', async () => {+ const request = vi.fn().mockResolvedValue({ id: 9, key: 'x', active: false })++ await tool.handler(createMockContext(request), { id: 9, active: false })++ expect(request).toHaveBeenCalledTimes(1)+ expect(requestArgs(request, 0).method).toBe('PATCH')+ expect(requestArgs(request, 0).body).toMatchObject({ active: false })+ })+})