Skip to content

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

fix(experiments): id aliases and by-flag-key lookup for the MCP tools (#100587)

ruby childs0ec2ba678d07
diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yaml
index c40ab397d7e5..4d84c62006c1 100644
--- a/products/experiments/mcp/tools.yaml
+++ b/products/experiments/mcp/tools.yaml
@@ -39,6 +39,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
experiment-archive:
operation: experiments_archive_create
enabled: true
@@ -67,6 +70,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
ui_app: experiment
experiment-calculate-running-time:
operation: experiments_calculate_running_time_create
@@ -126,6 +132,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
feature_flag: experiment-flag-cleanup-pr
response:
exclude:
@@ -189,6 +198,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
target_team_id:
cast: string-int
response:
@@ -342,6 +354,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
soft_delete: true
response:
include:
@@ -378,6 +393,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
experiment-end:
operation: experiments_end_create
enabled: true
@@ -419,6 +437,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
open_cleanup_pr:
description: >
When true, a background PostHog Code task removes the experiment's feature flag code and opens a
@@ -481,6 +502,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
ui_app: experiment
experiment-get:
operation: experiments_retrieve
@@ -494,8 +518,9 @@ tools:
enrich_url: '{id}'
title: Get experiment details
description: >
- Get a single experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the
- user's reference first.
+ Get a single experiment by ID. If you have the experiment's feature flag key instead of its ID, call
+ experiment-get-by-flag-key. If you have neither, load the finding-experiments skill to resolve the user's
+ reference first.
Returns the full experiment object including: status (draft/running/paused/exposure_frozen/stopped —
@@ -510,6 +535,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
ui_app: experiment
experiment-holdouts-create:
operation: experiment_holdouts_create
@@ -667,6 +695,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
ui_app: experiment
response:
include:
@@ -699,7 +730,8 @@ tools:
title: Get all experiments
description: >
List experiments in the current project. This is the primary tool for resolving experiment references — load
- the finding-experiments skill for guidance on searching by name, status, recency, or description.
+ the finding-experiments skill for guidance on searching by name, status, recency, or description. When the
+ reference is a feature flag key, call experiment-get-by-flag-key instead of listing.
Supports filtering by status ("draft", "running", "paused", "exposure_frozen", "stopped", "complete" which
@@ -771,6 +803,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
experiment-metrics-recalculation-latest-retrieve:
operation: experiments_metrics_recalculation_latest_retrieve
enabled: true
@@ -810,6 +845,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
ui_app: experiment-results
response:
exclude:
@@ -854,6 +892,14 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
+ recalculation_id:
+ aliases:
+ - run_id
+ - runId
+ - recalculationId
response:
exclude:
- results.*.result.hogql
@@ -896,6 +942,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
ui_app: experiment
experiment-prompt-templates:
operation: experiments_prompt_templates_retrieve
@@ -942,6 +991,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
ui_app: experiment
experiment-resume:
operation: experiments_resume_create
@@ -972,6 +1024,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
ui_app: experiment
experiment-saved-metrics-create:
operation: experiment_saved_metrics_create
@@ -1151,6 +1206,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
open_cleanup_pr:
description: >
When true, a background PostHog Code task removes the experiment's feature flag code, keeping the
@@ -1206,6 +1264,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
response:
exclude:
- timeseries.*.hogql
@@ -1244,6 +1305,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
ui_app: experiment
experiment-unfreeze-exposure:
operation: experiments_unfreeze_exposure_create
@@ -1283,6 +1347,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
ui_app: experiment
experiment-update:
operation: experiments_partial_update
@@ -1364,6 +1431,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
feature_flag:
description: >
Variant split, rollout scope, payloads, and experience continuity for the linked feature flag, in
@@ -1464,6 +1534,9 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - experimentId
+ - experiment_id
feature_flag: experiment-behavior-comparison
response:
informational_wrapper:
diff --git a/products/experiments/skills/finding-experiments/SKILL.md b/products/experiments/skills/finding-experiments/SKILL.md
index 1b3e136070b2..57077dd0e995 100644
--- a/products/experiments/skills/finding-experiments/SKILL.md
+++ b/products/experiments/skills/finding-experiments/SKILL.md
@@ -22,7 +22,11 @@ experiment matching the user's reference:
- **By name**: scan the `name` field for matches
- **By recency**: results are ordered newest first by default
- **By status**: match the `status` field (draft, running, paused, exposure_frozen, stopped)
-- **By flag key**: match the `feature_flag_key` field
+- **By flag key**: skip the list and call `experiment-get-by-flag-key` with the key. It returns the
+ full experiment, or `found: false` with a `reason`. `no_flag` and `no_experiment` mean the key is
+ free, so this is also the existence check to run before `experiment-create`. `ambiguous` means
+ several experiments share the flag and none is the single live one: show the `candidates` and
+ pick one with `experiment-get` rather than creating another.
## After finding matches
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index f6d2964b862a..a1221acd61a0 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -87,6 +87,11 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - flagId
+ - flag_id
+ - feature_flag_id
+ - featureFlagId
soft_delete: true
feature-flag-archive:
operation: feature_flags_archive_create
@@ -120,10 +125,9 @@ tools:
safe.
- A key lookup that finds nothing does not mean the flag is absent. Archived flags are hidden from
- `feature-flag-get-definition-by-key` and from `feature-flag-get-all`, so a flag that is already archived
- looks missing on a retry. Pass `{"archived":"true"}` to `feature-flag-get-all` before you report the flag as
- missing.
+ `feature-flag-get-definition-by-key` also finds archived flags, so a flag that is already archived is
+ returned with `archived: true` rather than looking missing on a retry. `feature-flag-get-all` hides archived
+ flags unless you pass `{"archived":"true"}`.
Use `feature-flag-unarchive` to put the flag back in the list, or `delete-feature-flag` when the user wants
@@ -131,6 +135,11 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - flagId
+ - flag_id
+ - feature_flag_id
+ - featureFlagId
response:
include:
- id
@@ -170,9 +179,8 @@ tools:
nothing, so retrying is safe.
- A key lookup that finds nothing does not mean the flag is absent. Archived flags are hidden from
- `feature-flag-get-definition-by-key` and from `feature-flag-get-all`, and an archived flag is already
- disabled. Pass `{"archived":"true"}` to `feature-flag-get-all` before you report the flag as missing.
+ `feature-flag-get-definition-by-key` also finds archived flags, and an archived flag is already disabled.
+ `feature-flag-get-all` hides archived flags unless you pass `{"archived":"true"}`.
To turn the flag off at a future time instead, use `scheduled-changes-create` with the `update_status`
@@ -180,6 +188,11 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - flagId
+ - flag_id
+ - feature_flag_id
+ - featureFlagId
response:
include:
- id
@@ -214,9 +227,8 @@ tools:
changes nothing, so retrying is safe.
- A key lookup that finds nothing does not mean the flag is absent. Archived flags are hidden from
- `feature-flag-get-definition-by-key` and from `feature-flag-get-all`. Pass `{"archived":"true"}` to
- `feature-flag-get-all` before you report the flag as missing.
+ `feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags
+ unless you pass `{"archived":"true"}`.
To turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status`
@@ -224,6 +236,11 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - flagId
+ - flag_id
+ - feature_flag_id
+ - featureFlagId
response:
include:
- id
@@ -282,6 +299,11 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - flagId
+ - flag_id
+ - feature_flag_id
+ - featureFlagId
feature-flag-request-usage-list:
operation: feature_flag_request_usage_list
enabled: false
@@ -310,6 +332,11 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - flagId
+ - flag_id
+ - feature_flag_id
+ - featureFlagId
response:
include:
- id
@@ -334,6 +361,11 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - flagId
+ - flag_id
+ - feature_flag_id
+ - featureFlagId
feature-flags-all-activity-retrieve:
operation: feature_flags_all_activity_retrieve
enabled: false
@@ -445,6 +477,11 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - flagId
+ - flag_id
+ - feature_flag_id
+ - featureFlagId
feature-flags-evaluation-reasons-retrieve:
operation: feature_flags_evaluation_reasons_retrieve
enabled: true
@@ -531,6 +568,11 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - flagId
+ - flag_id
+ - feature_flag_id
+ - featureFlagId
feature-flags-test-evaluation-create:
operation: feature_flags_test_evaluation_create
enabled: true
@@ -551,6 +593,11 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - flagId
+ - flag_id
+ - feature_flag_id
+ - featureFlagId
validators:
- validateDistinctIdPersonIdExclusive
ui_app: feature-flag-testing
@@ -715,6 +762,11 @@ tools:
param_overrides:
id:
cast: string-int
+ aliases:
+ - flagId
+ - flag_id
+ - feature_flag_id
+ - featureFlagId
filters:
description: >
Full release-condition object (replaces filters at the API). For group flags set
diff --git a/services/mcp/evals/benchmark/tasks.yaml b/services/mcp/evals/benchmark/tasks.yaml
index 274d823eb989..f822d33af8d4 100644
--- a/services/mcp/evals/benchmark/tasks.yaml
+++ b/services/mcp/evals/benchmark/tasks.yaml
@@ -356,8 +356,8 @@ tasks:
acceptable_tools: [feature-flag-get-all, feature-flag-get-definition-by-key, feature-flag-get-definition]
success_criteria: >
Calls feature-flag-unarchive with no filters payload and does not enable it, saying the flag is still turned
- off. Finds the archived flag by passing {"archived":"true"} to feature-flag-get-all; a plain key lookup returning
- nothing is not grounds for reporting that the flag does not exist.
+ off. Finds the archived flag with feature-flag-get-definition-by-key, which returns it with archived: true, or
+ by passing {"archived":"true"} to feature-flag-get-all.
- id: flag-targeting-edit-uses-update
category: feature-flags
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 8771ec415ecd..85db52f61381 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -4429,7 +4429,7 @@
}
},
"experiment-get": {
- "description": "Get a single experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first.\n\nReturns the full experiment object including: status (draft/running/paused/exposure_frozen/stopped — \"paused\" is a virtual value returned when the experiment is launched but its feature flag has been deactivated, \"exposure_frozen\" when its flag's release groups are narrowed to the already-exposed cohort so enrollment is closed while metrics keep flowing), start_date and end_date, linked feature_flag (with variants, filters, active state), metrics and metrics_secondary arrays, conclusion and conclusion_comment if ended, parameters (including feature_flag_variants and recommended_running_time), stats_config, type (web/product), and resolved_exposure_event (the event exposures are counted on when no custom exposure event is configured — resolved server-side to $feature_flag_called or $experiment_exposure; use it in SQL instead of hardcoding either name).",
+ "description": "Get a single experiment by ID. If you have the experiment's feature flag key instead of its ID, call experiment-get-by-flag-key. If you have neither, load the finding-experiments skill to resolve the user's reference first.\n\nReturns the full experiment object including: status (draft/running/paused/exposure_frozen/stopped — \"paused\" is a virtual value returned when the experiment is launched but its feature flag has been deactivated, \"exposure_frozen\" when its flag's release groups are narrowed to the already-exposed cohort so enrollment is closed while metrics keep flowing), start_date and end_date, linked feature_flag (with variants, filters, active state), metrics and metrics_secondary arrays, conclusion and conclusion_comment if ended, parameters (including feature_flag_variants and recommended_running_time), stats_config, type (web/product), and resolved_exposure_event (the event exposures are counted on when no custom exposure event is configured — resolved server-side to $feature_flag_called or $experiment_exposure; use it in SQL instead of hardcoding either name).",
"category": "Experiments",
"feature": "experiments",
"summary": "Get experiment details",
@@ -4527,7 +4527,7 @@
}
},
"experiment-list": {
- "description": "List experiments in the current project. This is the primary tool for resolving experiment references — load the finding-experiments skill for guidance on searching by name, status, recency, or description.\n\nSupports filtering by status (\"draft\", \"running\", \"paused\", \"exposure_frozen\", \"stopped\", \"complete\" which maps to stopped, or \"all\"), archived state (defaults to non-archived), feature_flag_id, created_by_id, and free-text search on name. Supports ordering by an allowlisted set of fields (model fields plus computed \"duration\" and \"status\"). Returns paginated results with each experiment's status, dates, feature flag key, and metrics summary. Use the returned ID for get/update/lifecycle tools.",
+ "description": "List experiments in the current project. This is the primary tool for resolving experiment references — load the finding-experiments skill for guidance on searching by name, status, recency, or description. When the reference is a feature flag key, call experiment-get-by-flag-key instead of listing.\n\nSupports filtering by status (\"draft\", \"running\", \"paused\", \"exposure_frozen\", \"stopped\", \"complete\" which maps to stopped, or \"all\"), archived state (defaults to non-archived), feature_flag_id, created_by_id, and free-text search on name. Supports ordering by an allowlisted set of fields (model fields plus computed \"duration\" and \"status\"). Returns paginated results with each experiment's status, dates, feature flag key, and metrics summary. Use the returned ID for get/update/lifecycle tools.",
"category": "Experiments",
"feature": "experiments",
"summary": "Get all experiments",
@@ -5204,7 +5204,7 @@
}
},
"feature-flag-archive": {
- "description": "Archive a feature flag, hiding it from the default flag list. 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\nSets `archived` to true. An archived flag must be disabled, so an enabled flag is turned off in the same call. Nothing else changes: this tool never accepts or replaces the `filters` object, and linked experiment and survey history is preserved. There is no request body.\n\nWhen the flag is enabled, archiving stops it evaluating everywhere. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition.\n\nReturns 400 when the flag is enabled and other active flags depend on it. Returns 409 when an approval policy gates disabling. Archiving an already-archived flag succeeds and changes nothing, so retrying is safe.\n\nA key lookup that finds nothing does not mean the flag is absent. Archived flags are hidden from `feature-flag-get-definition-by-key` and from `feature-flag-get-all`, so a flag that is already archived looks missing on a retry. Pass `{\"archived\":\"true\"}` to `feature-flag-get-all` before you report the flag as missing.\n\nUse `feature-flag-unarchive` to put the flag back in the list, or `delete-feature-flag` when the user wants it gone rather than tidied away.",
+ "description": "Archive a feature flag, hiding it from the default flag list. 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\nSets `archived` to true. An archived flag must be disabled, so an enabled flag is turned off in the same call. Nothing else changes: this tool never accepts or replaces the `filters` object, and linked experiment and survey history is preserved. There is no request body.\n\nWhen the flag is enabled, archiving stops it evaluating everywhere. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition.\n\nReturns 400 when the flag is enabled and other active flags depend on it. Returns 409 when an approval policy gates disabling. Archiving an already-archived flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags, so a flag that is already archived is returned with `archived: true` rather than looking missing on a retry. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nUse `feature-flag-unarchive` to put the flag back in the list, or `delete-feature-flag` when the user wants it gone rather than tidied away.",
"category": "Feature flags",
"feature": "flags",
"summary": "Archive feature flag",
@@ -5218,7 +5218,7 @@
}
},
"feature-flag-disable": {
- "description": "Turn a feature flag off. 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\nSets `active` to false and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body.\n\nA disabled flag stops evaluating everywhere, so every caller falls back to its own default. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition. `feature-flag-get-definition-by-key` already returns it, and `feature-flag-get-definition` returns it by ID.\n\nReturns 400 when other active flags depend on this one; `feature-flags-dependent-flags-retrieve` lists them. Returns 409 when an approval policy gates disabling. Disabling an already-disabled flag succeeds and changes nothing, so retrying is safe.\n\nA key lookup that finds nothing does not mean the flag is absent. Archived flags are hidden from `feature-flag-get-definition-by-key` and from `feature-flag-get-all`, and an archived flag is already disabled. Pass `{\"archived\":\"true\"}` to `feature-flag-get-all` before you report the flag as missing.\n\nTo turn the flag off at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
+ "description": "Turn a feature flag off. 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\nSets `active` to false and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body.\n\nA disabled flag stops evaluating everywhere, so every caller falls back to its own default. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition. `feature-flag-get-definition-by-key` already returns it, and `feature-flag-get-definition` returns it by ID.\n\nReturns 400 when other active flags depend on this one; `feature-flags-dependent-flags-retrieve` lists them. Returns 409 when an approval policy gates disabling. Disabling an already-disabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags, and an archived flag is already disabled. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag off at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
"category": "Feature flags",
"feature": "flags",
"summary": "Disable feature flag",
@@ -5232,7 +5232,7 @@
}
},
"feature-flag-enable": {
- "description": "Turn a feature flag on. 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\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body. To change who the flag is served to, use `update-feature-flag`.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first) or when a flag it depends on is disabled. Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\nA key lookup that finds nothing does not mean the flag is absent. Archived flags are hidden from `feature-flag-get-definition-by-key` and from `feature-flag-get-all`. Pass `{\"archived\":\"true\"}` to `feature-flag-get-all` before you report the flag as missing.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
+ "description": "Turn a feature flag on. 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\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body. To change who the flag is served to, use `update-feature-flag`.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first) or when a flag it depends on is disabled. Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
"category": "Feature flags",
"feature": "flags",
"summary": "Enable feature flag",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index ad52f497fd85..32bc71b513db 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -4500,7 +4500,7 @@
}
},
"experiment-get": {
- "description": "Get a single experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first.\n\nReturns the full experiment object including: status (draft/running/paused/exposure_frozen/stopped — \"paused\" is a virtual value returned when the experiment is launched but its feature flag has been deactivated, \"exposure_frozen\" when its flag's release groups are narrowed to the already-exposed cohort so enrollment is closed while metrics keep flowing), start_date and end_date, linked feature_flag (with variants, filters, active state), metrics and metrics_secondary arrays, conclusion and conclusion_comment if ended, parameters (including feature_flag_variants and recommended_running_time), stats_config, type (web/product), and resolved_exposure_event (the event exposures are counted on when no custom exposure event is configured — resolved server-side to $feature_flag_called or $experiment_exposure; use it in SQL instead of hardcoding either name).",
+ "description": "Get a single experiment by ID. If you have the experiment's feature flag key instead of its ID, call experiment-get-by-flag-key. If you have neither, load the finding-experiments skill to resolve the user's reference first.\n\nReturns the full experiment object including: status (draft/running/paused/exposure_frozen/stopped — \"paused\" is a virtual value returned when the experiment is launched but its feature flag has been deactivated, \"exposure_frozen\" when its flag's release groups are narrowed to the already-exposed cohort so enrollment is closed while metrics keep flowing), start_date and end_date, linked feature_flag (with variants, filters, active state), metrics and metrics_secondary arrays, conclusion and conclusion_comment if ended, parameters (including feature_flag_variants and recommended_running_time), stats_config, type (web/product), and resolved_exposure_event (the event exposures are counted on when no custom exposure event is configured — resolved server-side to $feature_flag_called or $experiment_exposure; use it in SQL instead of hardcoding either name).",
"category": "Experiments",
"feature": "experiments",
"summary": "Get experiment details",
@@ -4513,6 +4513,20 @@
"readOnlyHint": true
}
},
+ "experiment-get-by-flag-key": {
+ "description": "Get an experiment by its feature flag key (e.g. \"new-checkout\") — the identifier used in code and shown in the UI. Use this when you have the flag key but not the experiment's numeric ID; use `experiment-get` when you have the ID. Returns the full experiment with `found: true`, or `found: false` with a message when no flag or no linked experiment exists — a miss is data, not an error, so an existence check before `experiment-create` needs no special handling. Archived flags and experiments are included. A miss carries `reason`: `no_flag` or `no_experiment` mean the key is free to create on; `ambiguous` means several experiments share the flag (experiment-duplicate reuses it) and none is the single live one, so `candidates` (id, name, status, archived, dates) lists them to pick from with `experiment-get`. When exactly one is live it is returned directly.",
+ "category": "Experiments",
+ "feature": "experiments",
+ "summary": "Get an experiment by its feature flag key.",
+ "title": "Get experiment by flag key",
+ "required_scopes": ["experiment:read", "feature_flag:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"experiment-holdouts-create": {
"description": "Create a holdout group — a reserved slice of users excluded from experiment exposure, used as a held-back baseline. Requires name and a non-empty filters array. Link experiments to it afterwards by passing the returned id as holdout_id on experiment-create or experiment-update. Note that you can't change which holdout an experiment points to once that experiment is running; the holdout itself stays editable (see experiment-holdouts-partial-update, whose edits cascade to all linked experiments).",
"category": "Experiments",
@@ -4598,7 +4612,7 @@
}
},
"experiment-list": {
- "description": "List experiments in the current project. This is the primary tool for resolving experiment references — load the finding-experiments skill for guidance on searching by name, status, recency, or description.\n\nSupports filtering by status (\"draft\", \"running\", \"paused\", \"exposure_frozen\", \"stopped\", \"complete\" which maps to stopped, or \"all\"), archived state (defaults to non-archived), feature_flag_id, created_by_id, and free-text search on name. Supports ordering by an allowlisted set of fields (model fields plus computed \"duration\" and \"status\"). Returns paginated results with each experiment's status, dates, feature flag key, and metrics summary. Use the returned ID for get/update/lifecycle tools.",
+ "description": "List experiments in the current project. This is the primary tool for resolving experiment references — load the finding-experiments skill for guidance on searching by name, status, recency, or description. When the reference is a feature flag key, call experiment-get-by-flag-key instead of listing.\n\nSupports filtering by status (\"draft\", \"running\", \"paused\", \"exposure_frozen\", \"stopped\", \"complete\" which maps to stopped, or \"all\"), archived state (defaults to non-archived), feature_flag_id, created_by_id, and free-text search on name. Supports ordering by an allowlisted set of fields (model fields plus computed \"duration\" and \"status\"). Returns paginated results with each experiment's status, dates, feature flag key, and metrics summary. Use the returned ID for get/update/lifecycle tools.",
"category": "Experiments",
"feature": "experiments",
"summary": "Get all experiments",
@@ -5345,7 +5359,7 @@
}
},
"feature-flag-archive": {
- "description": "Archive a feature flag, hiding it from the default flag list. 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\nSets `archived` to true. An archived flag must be disabled, so an enabled flag is turned off in the same call. Nothing else changes: this tool never accepts or replaces the `filters` object, and linked experiment and survey history is preserved. There is no request body.\n\nWhen the flag is enabled, archiving stops it evaluating everywhere. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition.\n\nReturns 400 when the flag is enabled and other active flags depend on it. Returns 409 when an approval policy gates disabling. Archiving an already-archived flag succeeds and changes nothing, so retrying is safe.\n\nA key lookup that finds nothing does not mean the flag is absent. Archived flags are hidden from `feature-flag-get-definition-by-key` and from `feature-flag-get-all`, so a flag that is already archived looks missing on a retry. Pass `{\"archived\":\"true\"}` to `feature-flag-get-all` before you report the flag as missing.\n\nUse `feature-flag-unarchive` to put the flag back in the list, or `delete-feature-flag` when the user wants it gone rather than tidied away.",
+ "description": "Archive a feature flag, hiding it from the default flag list. 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\nSets `archived` to true. An archived flag must be disabled, so an enabled flag is turned off in the same call. Nothing else changes: this tool never accepts or replaces the `filters` object, and linked experiment and survey history is preserved. There is no request body.\n\nWhen the flag is enabled, archiving stops it evaluating everywhere. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition.\n\nReturns 400 when the flag is enabled and other active flags depend on it. Returns 409 when an approval policy gates disabling. Archiving an already-archived flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags, so a flag that is already archived is returned with `archived: true` rather than looking missing on a retry. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nUse `feature-flag-unarchive` to put the flag back in the list, or `delete-feature-flag` when the user wants it gone rather than tidied away.",
"category": "Feature flags",
"feature": "flags",
"summary": "Archive feature flag",
@@ -5359,7 +5373,7 @@
}
},
"feature-flag-disable": {
- "description": "Turn a feature flag off. 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\nSets `active` to false and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body.\n\nA disabled flag stops evaluating everywhere, so every caller falls back to its own default. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition. `feature-flag-get-definition-by-key` already returns it, and `feature-flag-get-definition` returns it by ID.\n\nReturns 400 when other active flags depend on this one; `feature-flags-dependent-flags-retrieve` lists them. Returns 409 when an approval policy gates disabling. Disabling an already-disabled flag succeeds and changes nothing, so retrying is safe.\n\nA key lookup that finds nothing does not mean the flag is absent. Archived flags are hidden from `feature-flag-get-definition-by-key` and from `feature-flag-get-all`, and an archived flag is already disabled. Pass `{\"archived\":\"true\"}` to `feature-flag-get-all` before you report the flag as missing.\n\nTo turn the flag off at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
+ "description": "Turn a feature flag off. 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\nSets `active` to false and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body.\n\nA disabled flag stops evaluating everywhere, so every caller falls back to its own default. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition. `feature-flag-get-definition-by-key` already returns it, and `feature-flag-get-definition` returns it by ID.\n\nReturns 400 when other active flags depend on this one; `feature-flags-dependent-flags-retrieve` lists them. Returns 409 when an approval policy gates disabling. Disabling an already-disabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags, and an archived flag is already disabled. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag off at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
"category": "Feature flags",
"feature": "flags",
"summary": "Disable feature flag",
@@ -5373,7 +5387,7 @@
}
},
"feature-flag-enable": {
- "description": "Turn a feature flag on. 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\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body. To change who the flag is served to, use `update-feature-flag`.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first) or when a flag it depends on is disabled. Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\nA key lookup that finds nothing does not mean the flag is absent. Archived flags are hidden from `feature-flag-get-definition-by-key` and from `feature-flag-get-all`. Pass `{\"archived\":\"true\"}` to `feature-flag-get-all` before you report the flag as missing.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
+ "description": "Turn a feature flag on. 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\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body. To change who the flag is served to, use `update-feature-flag`.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first) or when a flag it depends on is disabled. Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
"category": "Feature flags",
"feature": "flags",
"summary": "Enable feature flag",
@@ -5415,7 +5429,7 @@
}
},
"feature-flag-get-definition-by-key": {
- "description": "Get a feature flag by its string key (e.g. \"new-checkout\") — the identifier used in code and shown in the UI. Use this when you have the key but not the numeric ID; use `feature-flag-get-definition` when you have the numeric ID.",
+ "description": "Get a feature flag by its string key (e.g. \"new-checkout\") — the identifier used in code and shown in the UI. Use this when you have the key but not the numeric ID; use `feature-flag-get-definition` when you have the numeric ID. Archived flags are included and come back with `archived: true`.",
"category": "Feature flags",
"feature": "flags",
"summary": "Get a feature flag by its key.",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index 478206655fab..7a8fa5f013a1 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -88,6 +88,20 @@
"readOnlyHint": true
}
},
+ "experiment-get-by-flag-key": {
+ "description": "Get an experiment by its feature flag key (e.g. \"new-checkout\") — the identifier used in code and shown in the UI. Use this when you have the flag key but not the experiment's numeric ID; use `experiment-get` when you have the ID. Returns the full experiment with `found: true`, or `found: false` with a message when no flag or no linked experiment exists — a miss is data, not an error, so an existence check before `experiment-create` needs no special handling. Archived flags and experiments are included. A miss carries `reason`: `no_flag` or `no_experiment` mean the key is free to create on; `ambiguous` means several experiments share the flag (experiment-duplicate reuses it) and none is the single live one, so `candidates` (id, name, status, archived, dates) lists them to pick from with `experiment-get`. When exactly one is live it is returned directly.",
+ "category": "Experiments",
+ "feature": "experiments",
+ "summary": "Get an experiment by its feature flag key.",
+ "title": "Get experiment by flag key",
+ "required_scopes": ["experiment:read", "feature_flag:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"experiment-results-get": {
"description": "Run an experiment's metric queries and return primary/secondary metric results plus exposure data in one call, with self-describing per-metric metadata: each row in metrics.primary.results / metrics.secondary.results carries a `metric` summary (uuid, name, metric_type, goal, and source - 'inline' for metrics defined on the experiment, 'shared' for saved metrics, with saved_metric_id/saved_metric_name set on shared rows). Rows are ordered to match the experiment UI (primary_metrics_ordered_uuids / secondary_metrics_ordered_uuids); a row whose metric query failed is kept with data: null so positions stay aligned. Results may be served from cache; pass refresh=true to force fresh computation (slower). Only works with new experiments (not legacy ExperimentTrendsQuery / ExperimentFunnelsQuery). Sibling tools: experiment-metrics-recalculation-latest-retrieve reads the most recent completed background recalculation run instead of executing queries in-call (pair it with experiment-metrics-recalculation-create to refresh); experiment-timeseries-results returns one metric's day-by-day history. Note the response strips UI-only bulk fields (clickhouse_sql, hogql, the legacy insight payload, per-funnel-step step_sessions) while preserving statistical fields (sum, sum_squares, step_counts, credible_intervals, per-breakdown stats).",
"category": "Experiments",
@@ -490,7 +504,7 @@
}
},
"feature-flag-get-definition-by-key": {
- "description": "Get a feature flag by its string key (e.g. \"new-checkout\") — the identifier used in code and shown in the UI. Use this when you have the key but not the numeric ID; use `feature-flag-get-definition` when you have the numeric ID.",
+ "description": "Get a feature flag by its string key (e.g. \"new-checkout\") — the identifier used in code and shown in the UI. Use this when you have the key but not the numeric ID; use `feature-flag-get-definition` when you have the numeric ID. Archived flags are included and come back with `archived: true`.",
"category": "Feature flags",
"feature": "flags",
"summary": "Get a feature flag by its key.",
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index 9cb508d1bb9b..617d341a430a 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -844,6 +844,31 @@ function composeToolSchema(
schemaExpr = `(${schemaExpr}).extend({ ${overrideEntries.join(', ')} })`
}
+ // normalizeParamAliases deletes alias keys after copying them onto the canonical
+ // param, so an alias that is also a real parameter of this operation, or an alias
+ // two params both claim, would silently drop a value. Checked after every override
+ // has run, because input_schema overrides add body fields inside the loop above.
+ const declaredParamNames = new Set([...pathParamNames, ...queryParamNames, ...bodyFieldNames])
+ const aliasOwners = new Map<string, string>()
+ for (const [paramName, aliases] of Object.entries(paramAliases)) {
+ for (const alias of aliases) {
+ if (alias === paramName || declaredParamNames.has(alias)) {
+ throw new Error(
+ `${config.operation}: alias "${alias}" for param "${paramName}" is also a declared parameter ` +
+ 'of this operation, so normalizeParamAliases would drop its value. Rename or remove the alias.'
+ )
+ }
+ const owner = aliasOwners.get(alias)
+ if (owner !== undefined) {
+ throw new Error(
+ `${config.operation}: alias "${alias}" is declared by both "${owner}" and "${paramName}", ` +
+ 'so normalizeParamAliases would drop one of them. Keep it on one param.'
+ )
+ }
+ aliasOwners.set(alias, paramName)
+ }
+ }
+
return {
orvalImports,
toolInputsImports,
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index a29a8b3cbde2..44735d59ff0f 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -391,7 +391,56 @@ export class ApiClient {
* The response body is read by the caller (SSE and JSON paths read it at
* different points) and passed in as `errorText`.
*/
+ /**
+ * A 404 for a path that names an experiment, answered with DRF's generic detail, means the
+ * experiment itself is missing: `get_object()` fails the same way on the resource and on
+ * every lifecycle action under it. That gets the message naming the recovery path, typed as
+ * a 4xx so `handleToolError` treats it as agent-recoverable instead of capturing an exception
+ * per guessed id. A sub-resource that wrote its own detail (a missing recalculation run) is
+ * answering about itself and passes through untouched.
+ */
+ private buildExperimentNotFoundError(
+ response: Response,
+ errorText: string,
+ url: string,
+ method: string
+ ): PostHogApiError | undefined {
+ const experimentMatch = /\/experiments\/(\d+)(?:\/|$)/.exec(url.split('?')[0]!)
+ if (!experimentMatch) {
+ return undefined
+ }
+ let detail: unknown
+ try {
+ detail = JSON.parse(errorText)?.detail
+ } catch {
+ detail = undefined
+ }
+ if (detail !== undefined && detail !== 'Not found.') {
+ return undefined
+ }
+ const experimentId = experimentMatch[1]
+ console.error(`[API] Experiment ${experimentId} not found on ${method} ${url}`)
+ return new PostHogApiError({
+ status: response.status,
+ statusText: response.statusText,
+ body: errorText,
+ url,
+ method,
+ message:
+ `Experiment ${experimentId} not found in this project. ` +
+ `If the id is correct, the experiment may belong to a different project — ` +
+ `call experiment-list to see experiments accessible with your current API key and project, or switch-project first.`,
+ })
+ }
+
private buildApiError(response: Response, errorText: string, url: string, method: string): Error {
+ if (response.status === 404) {
+ const experimentNotFound = this.buildExperimentNotFoundError(response, errorText, url, method)
+ if (experimentNotFound) {
+ return experimentNotFound
+ }
+ }
+
if (response.status === 401) {
return new Error(ErrorCode.INVALID_API_KEY)
}
@@ -504,19 +553,6 @@ export class ApiClient {
if (!response.ok) {
const errorText = await response.text()
- if (response.status === 404) {
- const experimentMatch = /\/experiments\/(\d+)/.exec(url)
- if (experimentMatch) {
- const experimentId = experimentMatch[1]
- console.error(`[API] Experiment ${experimentId} not found on ${method} ${url}`)
- throw new Error(
- `Experiment ${experimentId} not found in this project. ` +
- `If the id is correct, the experiment may belong to a different project — ` +
- `call experiment-list to see experiments accessible with your current API key and project, or switch-project first.`
- )
- }
- }
-
throw this.buildApiError(response, errorText, url, method)
}
diff --git a/services/mcp/src/schema/experiments.ts b/services/mcp/src/schema/experiments.ts
index 473e4af09b30..b103ebf53b58 100644
--- a/services/mcp/src/schema/experiments.ts
+++ b/services/mcp/src/schema/experiments.ts
@@ -34,10 +34,19 @@ const FeatureFlagSchema = z.object({
updated_at: z.string().nullish(),
})
+// `kind` and `properties` are optional on write (the backend defaults both), so stored
+// configs can lack them. Parsing here is on the read path of the results tool: a schema
+// stricter than what the API stores blocks every metric read for that experiment.
const ExperimentEventExposureConfigSchema = z.object({
- kind: z.literal('ExperimentEventExposureConfig'),
+ kind: z
+ .literal('ExperimentEventExposureConfig')
+ .nullish()
+ .transform(() => 'ExperimentEventExposureConfig' as const),
event: z.string(),
- properties: z.array(z.any()),
+ properties: z
+ .array(z.any())
+ .nullish()
+ .transform((properties) => properties ?? []),
})
// Action-based exposure: the experiment counts a user as exposed when they match a
@@ -57,10 +66,11 @@ const ExperimentExposureConfigSchema = z.union([
const ExperimentExposureCriteriaSchema = z.object({
filterTestAccounts: z.boolean().optional(),
- exposure_config: ExperimentExposureConfigSchema.optional(),
+ // Explicit null is how API clients clear a config, so stored criteria carry it.
+ exposure_config: ExperimentExposureConfigSchema.nullish(),
// Zod 4 z.object strips unknown keys on parse, and getExposures round-trips the stored
// criteria through this schema, so omitting a field here silently degrades the query.
- activation_config: ExperimentExposureConfigSchema.optional(),
+ activation_config: ExperimentExposureConfigSchema.nullish(),
multiple_variant_handling: z.enum(['exclude', 'first_seen']).optional(),
})
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 17e6474db8fa..96fe68cca7a7 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -384,14 +384,22 @@ export const SavedMetricsAttachSchema = z
"The complete desired set of shared (saved) metrics for the experiment — this REPLACES all existing saved-metric links, it does not append. To add or remove one, first read the experiment's current saved_metrics via experiment-get and resend the full set. Pass an empty array to detach all shared metrics."
)
-export const ExperimentResultsGetSchema = z.object({
- id: z.number().describe('The ID of the experiment to get comprehensive results for'),
- refresh: z
- .boolean()
- .optional()
- .default(false)
- .describe('Force refresh of results instead of using cached values. Defaults to false.'),
-})
+// Agents reach for `experimentId` / `experiment_id` here as often as `id` — the same
+// alias set the generated experiment tools accept via their tools.yaml overrides.
+export const ExperimentResultsGetSchema = z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ z.object({
+ id: z.preprocess(
+ castStringToInt,
+ z.number().describe('The ID of the experiment to get comprehensive results for')
+ ),
+ refresh: z
+ .boolean()
+ .optional()
+ .default(false)
+ .describe('Force refresh of results instead of using cached values. Defaults to false.'),
+ })
+)
// Accept the identifier under the aliases agents reach for (`insight-get` &
// friends return the insight under `id`; UI URLs surface `short_id`), and
diff --git a/services/mcp/src/tools/experiments/getByFlagKey.ts b/services/mcp/src/tools/experiments/getByFlagKey.ts
new file mode 100644
index 000000000000..e67bef17f26f
--- /dev/null
+++ b/services/mcp/src/tools/experiments/getByFlagKey.ts
@@ -0,0 +1,164 @@
+import { z } from 'zod'
+
+import type { Schemas } from '@/api/generated'
+import { ToolInputValidationError } from '@/lib/errors'
+import { normalizeParamAliases } from '@/tools/cast-helpers'
+import { resolveFlagsByKey } from '@/tools/featureFlags/resolveFlagsByKey'
+import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
+import type { Context, ToolBase } from '@/tools/types'
+
+/**
+ * `experiment-get-by-flag-key` fetches an experiment by its feature flag key, the identifier
+ * agents hold when `experiment-get` wants a numeric ID. The experiments list has no key filter,
+ * but the flag row carries `experiment_set`, so resolving the key to its flag is enough.
+ *
+ * A miss is data, not an error: the dominant caller is an existence check before
+ * `experiment-create` (same pattern as `feature-flag-get-definition-by-key`). Several
+ * experiments on one flag is also data, because `experiment-duplicate` reuses the source flag,
+ * so re-runs stack up; the tool picks the single live one when there is one and otherwise
+ * returns the candidates. Only an ambiguous flag key still throws.
+ */
+const schema = z.preprocess(
+ normalizeParamAliases({ feature_flag_key: ['flagKey', 'flag_key', 'featureFlagKey', 'key'] }),
+ z.object({
+ feature_flag_key: z
+ .string()
+ .describe('The experiment\'s feature flag key: the string identifier used in code (e.g. "new-checkout").'),
+ })
+)
+
+type Params = z.infer<typeof schema>
+
+interface ExperimentCandidate {
+ id: number
+ name: string
+ status: string | null
+ archived: boolean
+ start_date: string | null
+ end_date: string | null
+ created_at: string | null
+}
+
+interface ExperimentLookupMiss {
+ found: false
+ /** `no_flag` and `no_experiment` mean the key is free to create on; `ambiguous` means it is not. */
+ reason: 'no_flag' | 'no_experiment' | 'ambiguous'
+ feature_flag_key: string
+ message: string
+ /** Set for `ambiguous`: the experiments sharing the flag, none of which stands out as the live one. */
+ candidates?: ExperimentCandidate[]
+}
+
+type Result = (WithPostHogUrl<Schemas.Experiment> & { found: true }) | ExperimentLookupMiss
+
+type LinkedPick = { experimentId: number } | { candidates: ExperimentCandidate[] }
+
+const toCandidate = (experiment: Schemas.ExperimentBasic, archived: boolean): ExperimentCandidate => ({
+ id: experiment.id,
+ name: experiment.name,
+ status: experiment.status ?? null,
+ archived,
+ start_date: experiment.start_date ?? null,
+ end_date: experiment.end_date ?? null,
+ created_at: experiment.created_at ?? null,
+})
+
+/** Among several experiments on one flag, the single live one wins, then the single archived one. */
+const pickLinkedExperiment = async (context: Context, projectId: string, flagId: number): Promise<LinkedPick> => {
+ const listLinked = async (archivedOnly: boolean): Promise<Schemas.ExperimentBasic[]> => {
+ const page = await context.api.request<Schemas.PaginatedExperimentBasicList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(projectId)}/experiments/`,
+ query: { feature_flag_id: flagId, limit: 50, ...(archivedOnly && { archived: true }) },
+ })
+ return page.results ?? []
+ }
+ const live = await listLinked(false)
+ if (live.length === 1) {
+ return { experimentId: live[0]!.id }
+ }
+ const archived = await listLinked(true)
+ if (live.length === 0 && archived.length === 1) {
+ return { experimentId: archived[0]!.id }
+ }
+ return {
+ candidates: [
+ ...live.map((experiment) => toCandidate(experiment, false)),
+ ...archived.map((experiment) => toCandidate(experiment, true)),
+ ],
+ }
+}
+
+const experimentGetByFlagKey = (): ToolBase<typeof schema, Result> => ({
+ name: 'experiment-get-by-flag-key',
+ schema,
+ handler: async (context: Context, params: Params) => {
+ const key = params.feature_flag_key.trim()
+ if (key === '') {
+ throw new ToolInputValidationError('Provide the feature flag key of the experiment to fetch.')
+ }
+
+ const projectId = await context.stateManager.getProjectId()
+ const flagMatches = await resolveFlagsByKey(context, projectId, key)
+
+ if (flagMatches.length === 0) {
+ return {
+ found: false,
+ reason: 'no_flag',
+ feature_flag_key: key,
+ message:
+ `No feature flag with key "${key}" exists in this project, so no experiment is linked to it. ` +
+ 'Create one with `experiment-create`, or call `experiment-list` to browse existing experiments.',
+ }
+ }
+ if (flagMatches.length > 1) {
+ const ids = flagMatches.map((flag) => flag.id).join(', ')
+ throw new ToolInputValidationError(
+ `Multiple feature flags matched key "${key}" (IDs: ${ids}). Call \`experiment-list\` with the ` +
+ "right `feature_flag_id`, then pass the experiment's numeric `id` to `experiment-get`."
+ )
+ }
+ const flag = flagMatches[0]!
+ const experimentIds = flag.experiment_set ?? []
+
+ if (experimentIds.length === 0) {
+ return {
+ found: false,
+ reason: 'no_experiment',
+ feature_flag_key: key,
+ message:
+ `Feature flag "${key}" (ID ${flag.id}) exists but no experiment is linked to it. ` +
+ 'Create one with `experiment-create` using this key, or call `experiment-list` to browse existing experiments.',
+ }
+ }
+
+ let experimentId = experimentIds[0]!
+ if (experimentIds.length > 1) {
+ const pick = await pickLinkedExperiment(context, projectId, flag.id)
+ if ('candidates' in pick) {
+ return {
+ found: false,
+ reason: 'ambiguous',
+ feature_flag_key: key,
+ candidates: pick.candidates,
+ message:
+ pick.candidates.length > 0
+ ? `${pick.candidates.length} experiments are linked to feature flag "${key}" (ID ${flag.id}) and ` +
+ 'none stands out as the live one. Pick from `candidates` and pass its `id` to `experiment-get`.'
+ : `Feature flag "${key}" (ID ${flag.id}) lists experiments ${experimentIds.join(', ')}, but none ` +
+ 'came back from the experiments list. Try `experiment-get` with one of those ids.',
+ }
+ }
+ experimentId = pick.experimentId
+ }
+
+ const experiment = await context.api.request<Schemas.Experiment>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(projectId)}/experiments/${encodeURIComponent(String(experimentId))}/`,
+ })
+ const experimentWithUrl = await withPostHogUrl(context, experiment, `/experiments/${experiment.id}`)
+ return { ...experimentWithUrl, found: true }
+ },
+})
+
+export default experimentGetByFlagKey
diff --git a/services/mcp/src/tools/experiments/getResults.ts b/services/mcp/src/tools/experiments/getResults.ts
index 4139cf7f4db7..9b41fae01ac7 100644
--- a/services/mcp/src/tools/experiments/getResults.ts
+++ b/services/mcp/src/tools/experiments/getResults.ts
@@ -1,5 +1,6 @@
import type { z } from 'zod'
+import { findRecoverableApiError, PostHogApiError, PostHogValidationError, wrapError } from '@/lib/errors'
import { withUiApp } from '@/resources/ui-apps'
import type { ExperimentResultsSummary } from '@/schema/experiments'
import { transformExperimentResults } from '@/schema/experiments'
@@ -29,7 +30,16 @@ export const getResultsHandler: ToolBase<typeof schema, Result>['handler'] = asy
})
if (!result.success) {
- throw new Error(`Failed to get experiment results: ${result.error.message}`)
+ const message = `Failed to get experiment results: ${result.error.message}`
+ // A 400 from /query/ means the exposure query was built wrong on this side. Dropping
+ // the typed cause keeps it out of handleToolError's 4xx short-circuit so it is still
+ // captured as an exception. Every other failure keeps its cause: a 404, 403 or 429
+ // is the agent's or the caller's to recover from.
+ const apiError = findRecoverableApiError(result.error)
+ const isOwnQueryBug =
+ apiError instanceof PostHogValidationError ||
+ (apiError instanceof PostHogApiError && apiError.status === 400)
+ throw isOwnQueryBug ? new Error(message) : wrapError(message, result.error)
}
const {
diff --git a/services/mcp/src/tools/featureFlags/getDefinitionByKey.ts b/services/mcp/src/tools/featureFlags/getDefinitionByKey.ts
index 06f176811ba7..f25c773fe6a7 100644
--- a/services/mcp/src/tools/featureFlags/getDefinitionByKey.ts
+++ b/services/mcp/src/tools/featureFlags/getDefinitionByKey.ts
@@ -3,6 +3,7 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import { ToolInputValidationError } from '@/lib/errors'
import { normalizeParamAliases } from '@/tools/cast-helpers'
+import { resolveFlagsByKey } from '@/tools/featureFlags/resolveFlagsByKey'
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase } from '@/tools/types'
@@ -61,19 +62,7 @@ const featureFlagGetDefinitionByKey = (): ToolBase<typeof schema, Result> => ({
const projectId = await context.stateManager.getProjectId()
- // The list endpoint's `key` filter is a case-insensitive exact match, so it can return
- // more than one flag only when two keys differ solely by case — prefer an exact-case
- // match among the results before falling back to whatever case-insensitive match came
- // back. The search result already has the full flag, so it's wrapped directly instead of
- // triggering a redundant fetch-by-id round trip.
- const list = await context.api.request<Schemas.PaginatedFeatureFlagList>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(projectId)}/feature_flags/`,
- query: { key, limit: 5 },
- })
- const results = list.results ?? []
- const exact = results.filter((flag) => flag.key === key)
- const matches = exact.length > 0 ? exact : results
+ const matches = await resolveFlagsByKey(context, projectId, key)
if (matches.length === 0) {
return {
@@ -94,6 +83,8 @@ const featureFlagGetDefinitionByKey = (): ToolBase<typeof schema, Result> => ({
)
}
const flag = matches[0]!
+ // The list row is already the full flag, so it's wrapped directly instead of
+ // triggering a redundant fetch-by-id round trip.
const flagWithUrl = await withPostHogUrl(context, flag, `/feature_flags/${flag.id}`)
return { ...flagWithUrl, found: true }
},
diff --git a/services/mcp/src/tools/featureFlags/resolveFlagsByKey.ts b/services/mcp/src/tools/featureFlags/resolveFlagsByKey.ts
new file mode 100644
index 000000000000..0bd96c36d6b0
--- /dev/null
+++ b/services/mcp/src/tools/featureFlags/resolveFlagsByKey.ts
@@ -0,0 +1,32 @@
+import type { Schemas } from '@/api/generated'
+import type { Context } from '@/tools/types'
+
+/**
+ * Resolve a flag key through the list endpoint's `key` filter, which is a case-insensitive
+ * exact match. It can return more than one flag only when two keys differ solely by case, so
+ * the exact-case match is preferred when one exists. Misses and ambiguity are returned, not
+ * thrown: each caller words them differently (a miss is data for the by-key lookups).
+ *
+ * The list hides archived flags unless `archived` is passed, and archiving an experiment
+ * archives its flag, so a first-pass miss is retried against archived flags before it counts.
+ */
+export async function resolveFlagsByKey(
+ context: Context,
+ projectId: string,
+ key: string
+): Promise<Schemas.FeatureFlag[]> {
+ const list = async (archived: boolean): Promise<Schemas.FeatureFlag[]> => {
+ const page = await context.api.request<Schemas.PaginatedFeatureFlagList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(projectId)}/feature_flags/`,
+ query: { key, limit: 20, ...(archived && { archived: true }) },
+ })
+ return page.results ?? []
+ }
+ let results = await list(false)
+ if (results.length === 0) {
+ results = await list(true)
+ }
+ const exact = results.filter((flag) => flag.key === key)
+ return exact.length > 0 ? exact : results
+}
diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.ts
index 89a2cd11e466..818ce66c881c 100644
--- a/services/mcp/src/tools/generated/experiments.ts
+++ b/services/mcp/src/tools/generated/experiments.ts
@@ -5,7 +5,7 @@ import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/experiments/api'
import { withUiApp } from '@/resources/ui-apps'
import { SavedMetricsAttachSchema } from '@/schema/tool-inputs'
-import { castStringToInt } from '@/tools/cast-helpers'
+import { castStringToInt, normalizeParamAliases } from '@/tools/cast-helpers'
import {
withPostHogUrl,
omitResponseFields,
@@ -19,9 +19,12 @@ import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
const ExperimentActivitySchema = () => {
const ExperimentsActivityRetrieveParams = orvalSchemas.ExperimentsActivityRetrieveParams()
const ExperimentsActivityRetrieveQueryParams = orvalSchemas.ExperimentsActivityRetrieveQueryParams()
- return ExperimentsActivityRetrieveParams.omit({ project_id: true })
- .extend(ExperimentsActivityRetrieveQueryParams.shape)
- .extend({ id: z.preprocess(castStringToInt, ExperimentsActivityRetrieveParams.shape['id']) })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsActivityRetrieveParams.omit({ project_id: true })
+ .extend(ExperimentsActivityRetrieveQueryParams.shape)
+ .extend({ id: z.preprocess(castStringToInt, ExperimentsActivityRetrieveParams.shape['id']) })
+ )
}
const experimentActivity = (): ToolBase<
@@ -47,9 +50,12 @@ const experimentActivity = (): ToolBase<
const ExperimentArchiveSchema = () => {
const ExperimentsArchiveCreateBody = orvalSchemas.ExperimentsArchiveCreateBody()
const ExperimentsArchiveCreateParams = orvalSchemas.ExperimentsArchiveCreateParams()
- return ExperimentsArchiveCreateParams.omit({ project_id: true })
- .extend(ExperimentsArchiveCreateBody.shape)
- .extend({ id: z.preprocess(castStringToInt, ExperimentsArchiveCreateParams.shape['id']) })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsArchiveCreateParams.omit({ project_id: true })
+ .extend(ExperimentsArchiveCreateBody.shape)
+ .extend({ id: z.preprocess(castStringToInt, ExperimentsArchiveCreateParams.shape['id']) })
+ )
}
const experimentArchive = (): ToolBase<
@@ -120,9 +126,12 @@ const experimentCalculateRunningTime = (): ToolBase<
const ExperimentCleanupTaskSchema = () => {
const ExperimentsFlagCleanupTaskRetrieveParams = orvalSchemas.ExperimentsFlagCleanupTaskRetrieveParams()
- return ExperimentsFlagCleanupTaskRetrieveParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, ExperimentsFlagCleanupTaskRetrieveParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsFlagCleanupTaskRetrieveParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsFlagCleanupTaskRetrieveParams.shape['id']),
+ })
+ )
}
const experimentCleanupTask = (): ToolBase<
@@ -145,12 +154,18 @@ const experimentCleanupTask = (): ToolBase<
const ExperimentCopyToProjectSchema = () => {
const ExperimentsCopyToProjectCreateBody = orvalSchemas.ExperimentsCopyToProjectCreateBody()
const ExperimentsCopyToProjectCreateParams = orvalSchemas.ExperimentsCopyToProjectCreateParams()
- return ExperimentsCopyToProjectCreateParams.omit({ project_id: true })
- .extend(ExperimentsCopyToProjectCreateBody.shape)
- .extend({
- id: z.preprocess(castStringToInt, ExperimentsCopyToProjectCreateParams.shape['id']),
- target_team_id: z.preprocess(castStringToInt, ExperimentsCopyToProjectCreateBody.shape['target_team_id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsCopyToProjectCreateParams.omit({ project_id: true })
+ .extend(ExperimentsCopyToProjectCreateBody.shape)
+ .extend({
+ id: z.preprocess(castStringToInt, ExperimentsCopyToProjectCreateParams.shape['id']),
+ target_team_id: z.preprocess(
+ castStringToInt,
+ ExperimentsCopyToProjectCreateBody.shape['target_team_id']
+ ),
+ })
+ )
}
const experimentCopyToProject = (): ToolBase<ReturnType<typeof ExperimentCopyToProjectSchema>, Schemas.Experiment> => ({
@@ -348,9 +363,12 @@ const experimentCreateFromPrompt = (): ToolBase<
const ExperimentDeleteSchema = () => {
const ExperimentsDestroyParams = orvalSchemas.ExperimentsDestroyParams()
- return ExperimentsDestroyParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, ExperimentsDestroyParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsDestroyParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsDestroyParams.shape['id']),
+ })
+ )
}
const experimentDelete = (): ToolBase<ReturnType<typeof ExperimentDeleteSchema>, Schemas.Experiment> => ({
@@ -371,41 +389,44 @@ const experimentDelete = (): ToolBase<ReturnType<typeof ExperimentDeleteSchema>,
const ExperimentDuplicateSchema = () => {
const ExperimentsDuplicateCreateBody = orvalSchemas.ExperimentsDuplicateCreateBody()
const ExperimentsDuplicateCreateParams = orvalSchemas.ExperimentsDuplicateCreateParams()
- return ExperimentsDuplicateCreateParams.omit({ project_id: true })
- .extend(
- ExperimentsDuplicateCreateBody.omit({
- description: true,
- start_date: true,
- end_date: true,
- holdout_id: true,
- parameters: true,
- running_time_calculation: true,
- excluded_variants: true,
- secondary_metrics: true,
- saved_metrics_ids: true,
- filters: true,
- archived: true,
- deleted: true,
- type: true,
- exposure_criteria: true,
- metrics: true,
- metrics_secondary: true,
- stats_config: true,
- scheduling_config: true,
- allow_unknown_events: true,
- _create_in_folder: true,
- conclusion: true,
- conclusion_comment: true,
- repository: true,
- primary_metrics_ordered_uuids: true,
- secondary_metrics_ordered_uuids: true,
- only_count_matured_users: true,
- update_feature_flag_params: true,
- version: true,
- original_experiment: true,
- }).shape
- )
- .extend({ id: z.preprocess(castStringToInt, ExperimentsDuplicateCreateParams.shape['id']) })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsDuplicateCreateParams.omit({ project_id: true })
+ .extend(
+ ExperimentsDuplicateCreateBody.omit({
+ description: true,
+ start_date: true,
+ end_date: true,
+ holdout_id: true,
+ parameters: true,
+ running_time_calculation: true,
+ excluded_variants: true,
+ secondary_metrics: true,
+ saved_metrics_ids: true,
+ filters: true,
+ archived: true,
+ deleted: true,
+ type: true,
+ exposure_criteria: true,
+ metrics: true,
+ metrics_secondary: true,
+ stats_config: true,
+ scheduling_config: true,
+ allow_unknown_events: true,
+ _create_in_folder: true,
+ conclusion: true,
+ conclusion_comment: true,
+ repository: true,
+ primary_metrics_ordered_uuids: true,
+ secondary_metrics_ordered_uuids: true,
+ only_count_matured_users: true,
+ update_feature_flag_params: true,
+ version: true,
+ original_experiment: true,
+ }).shape
+ )
+ .extend({ id: z.preprocess(castStringToInt, ExperimentsDuplicateCreateParams.shape['id']) })
+ )
}
const experimentDuplicate = (): ToolBase<ReturnType<typeof ExperimentDuplicateSchema>, unknown> => ({
@@ -432,17 +453,20 @@ const experimentDuplicate = (): ToolBase<ReturnType<typeof ExperimentDuplicateSc
const ExperimentEndSchema = () => {
const ExperimentsEndCreateBody = orvalSchemas.ExperimentsEndCreateBody()
const ExperimentsEndCreateParams = orvalSchemas.ExperimentsEndCreateParams()
- return ExperimentsEndCreateParams.omit({ project_id: true })
- .extend(ExperimentsEndCreateBody.shape)
- .extend({
- id: z.preprocess(castStringToInt, ExperimentsEndCreateParams.shape['id']),
- open_cleanup_pr: ExperimentsEndCreateBody.shape['open_cleanup_pr'].describe(
- "When true, a background PostHog Code task removes the experiment's feature flag code and opens a draft pull request. Only works for teams with the flag cleanup feature enabled; silently skipped otherwise. Additionally requires the task:write scope. Ask the user before setting this."
- ),
- repository: ExperimentsEndCreateBody.shape['repository'].describe(
- "Repository the cleanup pull request targets, as \"organization/repository\". Must be connected to the team's GitHub integration. Omit to fall back to the experiment's saved repository, the team default, or the team's only connected repository. When several repositories are connected and no default is set, the cleanup is skipped unless this is provided."
- ),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsEndCreateParams.omit({ project_id: true })
+ .extend(ExperimentsEndCreateBody.shape)
+ .extend({
+ id: z.preprocess(castStringToInt, ExperimentsEndCreateParams.shape['id']),
+ open_cleanup_pr: ExperimentsEndCreateBody.shape['open_cleanup_pr'].describe(
+ "When true, a background PostHog Code task removes the experiment's feature flag code and opens a draft pull request. Only works for teams with the flag cleanup feature enabled; silently skipped otherwise. Additionally requires the task:write scope. Ask the user before setting this."
+ ),
+ repository: ExperimentsEndCreateBody.shape['repository'].describe(
+ "Repository the cleanup pull request targets, as \"organization/repository\". Must be connected to the team's GitHub integration. Omit to fall back to the experiment's saved repository, the team default, or the team's only connected repository. When several repositories are connected and no default is set, the cleanup is skipped unless this is provided."
+ ),
+ })
+ )
}
const experimentEnd = (): ToolBase<ReturnType<typeof ExperimentEndSchema>, WithPostHogUrl<Schemas.Experiment>> =>
@@ -475,9 +499,12 @@ const experimentEnd = (): ToolBase<ReturnType<typeof ExperimentEndSchema>, WithP
const ExperimentFreezeExposureSchema = () => {
const ExperimentsFreezeExposureCreateParams = orvalSchemas.ExperimentsFreezeExposureCreateParams()
- return ExperimentsFreezeExposureCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, ExperimentsFreezeExposureCreateParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsFreezeExposureCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsFreezeExposureCreateParams.shape['id']),
+ })
+ )
}
const experimentFreezeExposure = (): ToolBase<
@@ -499,9 +526,12 @@ const experimentFreezeExposure = (): ToolBase<
const ExperimentGetSchema = () => {
const ExperimentsRetrieveParams = orvalSchemas.ExperimentsRetrieveParams()
- return ExperimentsRetrieveParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, ExperimentsRetrieveParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsRetrieveParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsRetrieveParams.shape['id']),
+ })
+ )
}
const experimentGet = (): ToolBase<ReturnType<typeof ExperimentGetSchema>, WithPostHogUrl<Schemas.Experiment>> =>
@@ -670,9 +700,12 @@ const experimentHoldoutsRetrieve = (): ToolBase<
const ExperimentLaunchSchema = () => {
const ExperimentsLaunchCreateParams = orvalSchemas.ExperimentsLaunchCreateParams()
- return ExperimentsLaunchCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, ExperimentsLaunchCreateParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsLaunchCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsLaunchCreateParams.shape['id']),
+ })
+ )
}
const experimentLaunch = (): ToolBase<ReturnType<typeof ExperimentLaunchSchema>, WithPostHogUrl<Schemas.Experiment>> =>
@@ -778,9 +811,12 @@ const experimentList = (): ToolBase<
const ExperimentMetricsRecalculationCreateSchema = () => {
const ExperimentsMetricsRecalculationCreateBody = orvalSchemas.ExperimentsMetricsRecalculationCreateBody()
const ExperimentsMetricsRecalculationCreateParams = orvalSchemas.ExperimentsMetricsRecalculationCreateParams()
- return ExperimentsMetricsRecalculationCreateParams.omit({ project_id: true })
- .extend(ExperimentsMetricsRecalculationCreateBody.shape)
- .extend({ id: z.preprocess(castStringToInt, ExperimentsMetricsRecalculationCreateParams.shape['id']) })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsMetricsRecalculationCreateParams.omit({ project_id: true })
+ .extend(ExperimentsMetricsRecalculationCreateBody.shape)
+ .extend({ id: z.preprocess(castStringToInt, ExperimentsMetricsRecalculationCreateParams.shape['id']) })
+ )
}
const experimentMetricsRecalculationCreate = (): ToolBase<
@@ -805,9 +841,12 @@ const experimentMetricsRecalculationCreate = (): ToolBase<
const ExperimentMetricsRecalculationLatestRetrieveSchema = () => {
const ExperimentsMetricsRecalculationLatestRetrieveParams =
orvalSchemas.ExperimentsMetricsRecalculationLatestRetrieveParams()
- return ExperimentsMetricsRecalculationLatestRetrieveParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, ExperimentsMetricsRecalculationLatestRetrieveParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsMetricsRecalculationLatestRetrieveParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsMetricsRecalculationLatestRetrieveParams.shape['id']),
+ })
+ )
}
const experimentMetricsRecalculationLatestRetrieve = (): ToolBase<
@@ -844,9 +883,15 @@ const experimentMetricsRecalculationLatestRetrieve = (): ToolBase<
const ExperimentMetricsRecalculationRetrieveSchema = () => {
const ExperimentsMetricsRecalculationRetrieveParams = orvalSchemas.ExperimentsMetricsRecalculationRetrieveParams()
- return ExperimentsMetricsRecalculationRetrieveParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, ExperimentsMetricsRecalculationRetrieveParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({
+ id: ['experimentId', 'experiment_id'],
+ recalculation_id: ['run_id', 'runId', 'recalculationId'],
+ }),
+ ExperimentsMetricsRecalculationRetrieveParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsMetricsRecalculationRetrieveParams.shape['id']),
+ })
+ )
}
const experimentMetricsRecalculationRetrieve = (): ToolBase<
@@ -882,9 +927,12 @@ const experimentMetricsRecalculationRetrieve = (): ToolBase<
const ExperimentPauseSchema = () => {
const ExperimentsPauseCreateParams = orvalSchemas.ExperimentsPauseCreateParams()
- return ExperimentsPauseCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, ExperimentsPauseCreateParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsPauseCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsPauseCreateParams.shape['id']),
+ })
+ )
}
const experimentPause = (): ToolBase<ReturnType<typeof ExperimentPauseSchema>, WithPostHogUrl<Schemas.Experiment>> =>
@@ -918,9 +966,12 @@ const experimentPromptTemplates = (): ToolBase<ReturnType<typeof ExperimentPromp
const ExperimentResetSchema = () => {
const ExperimentsResetCreateParams = orvalSchemas.ExperimentsResetCreateParams()
- return ExperimentsResetCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, ExperimentsResetCreateParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsResetCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsResetCreateParams.shape['id']),
+ })
+ )
}
const experimentReset = (): ToolBase<ReturnType<typeof ExperimentResetSchema>, WithPostHogUrl<Schemas.Experiment>> =>
@@ -939,9 +990,12 @@ const experimentReset = (): ToolBase<ReturnType<typeof ExperimentResetSchema>, W
const ExperimentResumeSchema = () => {
const ExperimentsResumeCreateParams = orvalSchemas.ExperimentsResumeCreateParams()
- return ExperimentsResumeCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, ExperimentsResumeCreateParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsResumeCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsResumeCreateParams.shape['id']),
+ })
+ )
}
const experimentResume = (): ToolBase<ReturnType<typeof ExperimentResumeSchema>, WithPostHogUrl<Schemas.Experiment>> =>
@@ -1122,17 +1176,20 @@ const experimentSavedMetricsRetrieve = (): ToolBase<
const ExperimentShipVariantSchema = () => {
const ExperimentsShipVariantCreateBody = orvalSchemas.ExperimentsShipVariantCreateBody()
const ExperimentsShipVariantCreateParams = orvalSchemas.ExperimentsShipVariantCreateParams()
- return ExperimentsShipVariantCreateParams.omit({ project_id: true })
- .extend(ExperimentsShipVariantCreateBody.shape)
- .extend({
- id: z.preprocess(castStringToInt, ExperimentsShipVariantCreateParams.shape['id']),
- open_cleanup_pr: ExperimentsShipVariantCreateBody.shape['open_cleanup_pr'].describe(
- "When true, a background PostHog Code task removes the experiment's feature flag code, keeping the shipped variant's code path, and opens a draft pull request. Only works for teams with the flag cleanup feature enabled; silently skipped otherwise. Additionally requires the task:write scope. Ask the user before setting this."
- ),
- repository: ExperimentsShipVariantCreateBody.shape['repository'].describe(
- "Repository the cleanup pull request targets, as \"organization/repository\". Must be connected to the team's GitHub integration. Omit to fall back to the experiment's saved repository, the team default, or the team's only connected repository. When several repositories are connected and no default is set, the cleanup is skipped unless this is provided."
- ),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsShipVariantCreateParams.omit({ project_id: true })
+ .extend(ExperimentsShipVariantCreateBody.shape)
+ .extend({
+ id: z.preprocess(castStringToInt, ExperimentsShipVariantCreateParams.shape['id']),
+ open_cleanup_pr: ExperimentsShipVariantCreateBody.shape['open_cleanup_pr'].describe(
+ "When true, a background PostHog Code task removes the experiment's feature flag code, keeping the shipped variant's code path, and opens a draft pull request. Only works for teams with the flag cleanup feature enabled; silently skipped otherwise. Additionally requires the task:write scope. Ask the user before setting this."
+ ),
+ repository: ExperimentsShipVariantCreateBody.shape['repository'].describe(
+ "Repository the cleanup pull request targets, as \"organization/repository\". Must be connected to the team's GitHub integration. Omit to fall back to the experiment's saved repository, the team default, or the team's only connected repository. When several repositories are connected and no default is set, the cleanup is skipped unless this is provided."
+ ),
+ })
+ )
}
const experimentShipVariant = (): ToolBase<
@@ -1191,9 +1248,12 @@ const ExperimentTimeseriesResultsSchema = () => {
const ExperimentsTimeseriesResultsRetrieveParams = orvalSchemas.ExperimentsTimeseriesResultsRetrieveParams()
const ExperimentsTimeseriesResultsRetrieveQueryParams =
orvalSchemas.ExperimentsTimeseriesResultsRetrieveQueryParams()
- return ExperimentsTimeseriesResultsRetrieveParams.omit({ project_id: true })
- .extend(ExperimentsTimeseriesResultsRetrieveQueryParams.shape)
- .extend({ id: z.preprocess(castStringToInt, ExperimentsTimeseriesResultsRetrieveParams.shape['id']) })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsTimeseriesResultsRetrieveParams.omit({ project_id: true })
+ .extend(ExperimentsTimeseriesResultsRetrieveQueryParams.shape)
+ .extend({ id: z.preprocess(castStringToInt, ExperimentsTimeseriesResultsRetrieveParams.shape['id']) })
+ )
}
const experimentTimeseriesResults = (): ToolBase<ReturnType<typeof ExperimentTimeseriesResultsSchema>, unknown> => ({
@@ -1227,9 +1287,12 @@ const experimentTimeseriesResults = (): ToolBase<ReturnType<typeof ExperimentTim
const ExperimentUnarchiveSchema = () => {
const ExperimentsUnarchiveCreateParams = orvalSchemas.ExperimentsUnarchiveCreateParams()
- return ExperimentsUnarchiveCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, ExperimentsUnarchiveCreateParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsUnarchiveCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsUnarchiveCreateParams.shape['id']),
+ })
+ )
}
const experimentUnarchive = (): ToolBase<
@@ -1251,9 +1314,12 @@ const experimentUnarchive = (): ToolBase<
const ExperimentUnfreezeExposureSchema = () => {
const ExperimentsUnfreezeExposureCreateParams = orvalSchemas.ExperimentsUnfreezeExposureCreateParams()
- return ExperimentsUnfreezeExposureCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, ExperimentsUnfreezeExposureCreateParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsUnfreezeExposureCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsUnfreezeExposureCreateParams.shape['id']),
+ })
+ )
}
const experimentUnfreezeExposure = (): ToolBase<
@@ -1276,36 +1342,39 @@ const experimentUnfreezeExposure = (): ToolBase<
const ExperimentUpdateSchema = () => {
const ExperimentsPartialUpdateBody = orvalSchemas.ExperimentsPartialUpdateBody()
const ExperimentsPartialUpdateParams = orvalSchemas.ExperimentsPartialUpdateParams()
- return ExperimentsPartialUpdateParams.omit({ project_id: true })
- .extend(
- ExperimentsPartialUpdateBody.omit({
- start_date: true,
- end_date: true,
- feature_flag_key: true,
- secondary_metrics: true,
- filters: true,
- deleted: true,
- type: true,
- scheduling_config: true,
- _create_in_folder: true,
- repository: true,
- primary_metrics_ordered_uuids: true,
- secondary_metrics_ordered_uuids: true,
- only_count_matured_users: true,
- version: true,
- original_experiment: true,
- }).shape
- )
- .extend({
- id: z.preprocess(castStringToInt, ExperimentsPartialUpdateParams.shape['id']),
- feature_flag: ExperimentsPartialUpdateBody.shape['feature_flag'].describe(
- "Variant split, rollout scope, payloads, and experience continuity for the linked feature flag, in the flag's own filters shape. This is the canonical input for flag config. Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100; the analysis baseline defaults to the variant keyed 'control' when present, else the first variant — except web experiments, which must keep a variant keyed 'control') to change the variant split. Set filters.groups to a single group [{\"properties\": [], \"rollout_percentage\": N}] (0-100) to change the overall rollout. Config this object omits is preserved from the flag's current state. On a running experiment this requires update_feature_flag_params=true (see rule 1: warn the user first)."
- ),
- running_time_calculation: ExperimentsPartialUpdateBody.shape['running_time_calculation'].describe(
- "Persist a running-time / sample-size plan onto the experiment (the planning target shown in the experiment's running-time panel). Object with optional keys: minimum_detectable_effect (percentage, e.g. 20 for a 20% lift), recommended_sample_size (total across all variants), recommended_running_time (days), and exposure_estimate_config."
- ),
- saved_metrics_ids: SavedMetricsAttachSchema.optional(),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsPartialUpdateParams.omit({ project_id: true })
+ .extend(
+ ExperimentsPartialUpdateBody.omit({
+ start_date: true,
+ end_date: true,
+ feature_flag_key: true,
+ secondary_metrics: true,
+ filters: true,
+ deleted: true,
+ type: true,
+ scheduling_config: true,
+ _create_in_folder: true,
+ repository: true,
+ primary_metrics_ordered_uuids: true,
+ secondary_metrics_ordered_uuids: true,
+ only_count_matured_users: true,
+ version: true,
+ original_experiment: true,
+ }).shape
+ )
+ .extend({
+ id: z.preprocess(castStringToInt, ExperimentsPartialUpdateParams.shape['id']),
+ feature_flag: ExperimentsPartialUpdateBody.shape['feature_flag'].describe(
+ "Variant split, rollout scope, payloads, and experience continuity for the linked feature flag, in the flag's own filters shape. This is the canonical input for flag config. Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100; the analysis baseline defaults to the variant keyed 'control' when present, else the first variant — except web experiments, which must keep a variant keyed 'control') to change the variant split. Set filters.groups to a single group [{\"properties\": [], \"rollout_percentage\": N}] (0-100) to change the overall rollout. Config this object omits is preserved from the flag's current state. On a running experiment this requires update_feature_flag_params=true (see rule 1: warn the user first)."
+ ),
+ running_time_calculation: ExperimentsPartialUpdateBody.shape['running_time_calculation'].describe(
+ "Persist a running-time / sample-size plan onto the experiment (the planning target shown in the experiment's running-time panel). Object with optional keys: minimum_detectable_effect (percentage, e.g. 20 for a 20% lift), recommended_sample_size (total across all variants), recommended_running_time (days), and exposure_estimate_config."
+ ),
+ saved_metrics_ids: SavedMetricsAttachSchema.optional(),
+ })
+ )
}
const experimentUpdate = (): ToolBase<ReturnType<typeof ExperimentUpdateSchema>, WithPostHogUrl<Schemas.Experiment>> =>
@@ -1396,9 +1465,12 @@ const experimentUpdate = (): ToolBase<ReturnType<typeof ExperimentUpdateSchema>,
const ExperimentsSessionEventDeltasCreateSchema = () => {
const ExperimentsSessionEventDeltasCreateParams = orvalSchemas.ExperimentsSessionEventDeltasCreateParams()
- return ExperimentsSessionEventDeltasCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, ExperimentsSessionEventDeltasCreateParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),
+ ExperimentsSessionEventDeltasCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsSessionEventDeltasCreateParams.shape['id']),
+ })
+ )
}
const experimentsSessionEventDeltasCreate = (): ToolBase<
diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.ts
index 5be432a27d35..1996e9ac7d40 100644
--- a/services/mcp/src/tools/generated/feature_flags.ts
+++ b/services/mcp/src/tools/generated/feature_flags.ts
@@ -5,7 +5,7 @@ import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/feature_flags/api'
import { withUiApp } from '@/resources/ui-apps'
import { validateDistinctIdPersonIdExclusive } from '@/schema/tool-inputs'
-import { castStringToInt } from '@/tools/cast-helpers'
+import { castStringToInt, normalizeParamAliases } from '@/tools/cast-helpers'
import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
@@ -77,9 +77,12 @@ const createFeatureFlag = (): ToolBase<
const DeleteFeatureFlagSchema = () => {
const FeatureFlagsDestroyParams = orvalSchemas.FeatureFlagsDestroyParams()
- return FeatureFlagsDestroyParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, FeatureFlagsDestroyParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),
+ FeatureFlagsDestroyParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, FeatureFlagsDestroyParams.shape['id']),
+ })
+ )
}
const deleteFeatureFlag = (): ToolBase<ReturnType<typeof DeleteFeatureFlagSchema>, Schemas.FeatureFlag> => ({
@@ -98,9 +101,12 @@ const deleteFeatureFlag = (): ToolBase<ReturnType<typeof DeleteFeatureFlagSchema
const FeatureFlagArchiveSchema = () => {
const FeatureFlagsArchiveCreateParams = orvalSchemas.FeatureFlagsArchiveCreateParams()
- return FeatureFlagsArchiveCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, FeatureFlagsArchiveCreateParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),
+ FeatureFlagsArchiveCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, FeatureFlagsArchiveCreateParams.shape['id']),
+ })
+ )
}
const featureFlagArchive = (): ToolBase<
@@ -129,9 +135,12 @@ const featureFlagArchive = (): ToolBase<
const FeatureFlagDisableSchema = () => {
const FeatureFlagsDisableCreateParams = orvalSchemas.FeatureFlagsDisableCreateParams()
- return FeatureFlagsDisableCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, FeatureFlagsDisableCreateParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),
+ FeatureFlagsDisableCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, FeatureFlagsDisableCreateParams.shape['id']),
+ })
+ )
}
const featureFlagDisable = (): ToolBase<
@@ -160,9 +169,12 @@ const featureFlagDisable = (): ToolBase<
const FeatureFlagEnableSchema = () => {
const FeatureFlagsEnableCreateParams = orvalSchemas.FeatureFlagsEnableCreateParams()
- return FeatureFlagsEnableCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, FeatureFlagsEnableCreateParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),
+ FeatureFlagsEnableCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, FeatureFlagsEnableCreateParams.shape['id']),
+ })
+ )
}
const featureFlagEnable = (): ToolBase<
@@ -249,9 +261,12 @@ const featureFlagGetAll = (): ToolBase<
const FeatureFlagGetDefinitionSchema = () => {
const FeatureFlagsRetrieveParams = orvalSchemas.FeatureFlagsRetrieveParams()
- return FeatureFlagsRetrieveParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, FeatureFlagsRetrieveParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),
+ FeatureFlagsRetrieveParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, FeatureFlagsRetrieveParams.shape['id']),
+ })
+ )
}
const featureFlagGetDefinition = (): ToolBase<
@@ -272,9 +287,12 @@ const featureFlagGetDefinition = (): ToolBase<
const FeatureFlagUnarchiveSchema = () => {
const FeatureFlagsUnarchiveCreateParams = orvalSchemas.FeatureFlagsUnarchiveCreateParams()
- return FeatureFlagsUnarchiveCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, FeatureFlagsUnarchiveCreateParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),
+ FeatureFlagsUnarchiveCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, FeatureFlagsUnarchiveCreateParams.shape['id']),
+ })
+ )
}
const featureFlagUnarchive = (): ToolBase<
@@ -304,9 +322,12 @@ const featureFlagUnarchive = (): ToolBase<
const FeatureFlagsActivityRetrieveSchema = () => {
const FeatureFlagsActivityRetrieveParams = orvalSchemas.FeatureFlagsActivityRetrieveParams()
const FeatureFlagsActivityRetrieveQueryParams = orvalSchemas.FeatureFlagsActivityRetrieveQueryParams()
- return FeatureFlagsActivityRetrieveParams.omit({ project_id: true })
- .extend(FeatureFlagsActivityRetrieveQueryParams.shape)
- .extend({ id: z.preprocess(castStringToInt, FeatureFlagsActivityRetrieveParams.shape['id']) })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),
+ FeatureFlagsActivityRetrieveParams.omit({ project_id: true })
+ .extend(FeatureFlagsActivityRetrieveQueryParams.shape)
+ .extend({ id: z.preprocess(castStringToInt, FeatureFlagsActivityRetrieveParams.shape['id']) })
+ )
}
const featureFlagsActivityRetrieve = (): ToolBase<
@@ -492,9 +513,12 @@ const featureFlagsCopyFlagsCreate = (): ToolBase<
const FeatureFlagsDependentFlagsRetrieveSchema = () => {
const FeatureFlagsDependentFlagsListParams = orvalSchemas.FeatureFlagsDependentFlagsListParams()
- return FeatureFlagsDependentFlagsListParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, FeatureFlagsDependentFlagsListParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),
+ FeatureFlagsDependentFlagsListParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, FeatureFlagsDependentFlagsListParams.shape['id']),
+ })
+ )
}
const featureFlagsDependentFlagsRetrieve = (): ToolBase<
@@ -570,9 +594,12 @@ const featureFlagsMyFlagsRetrieve = (): ToolBase<
const FeatureFlagsStatusRetrieveSchema = () => {
const FeatureFlagsStatusRetrieveParams = orvalSchemas.FeatureFlagsStatusRetrieveParams()
- return FeatureFlagsStatusRetrieveParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, FeatureFlagsStatusRetrieveParams.shape['id']),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),
+ FeatureFlagsStatusRetrieveParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, FeatureFlagsStatusRetrieveParams.shape['id']),
+ })
+ )
}
const featureFlagsStatusRetrieve = (): ToolBase<
@@ -594,10 +621,13 @@ const featureFlagsStatusRetrieve = (): ToolBase<
const FeatureFlagsTestEvaluationCreateSchema = () => {
const FeatureFlagsTestEvaluationCreateBody = orvalSchemas.FeatureFlagsTestEvaluationCreateBody()
const FeatureFlagsTestEvaluationCreateParams = orvalSchemas.FeatureFlagsTestEvaluationCreateParams()
- return FeatureFlagsTestEvaluationCreateParams.omit({ project_id: true })
- .extend(FeatureFlagsTestEvaluationCreateBody.shape)
- .extend({ id: z.preprocess(castStringToInt, FeatureFlagsTestEvaluationCreateParams.shape['id']) })
- .superRefine(validateDistinctIdPersonIdExclusive)
+ return z.preprocess(
+ normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),
+ FeatureFlagsTestEvaluationCreateParams.omit({ project_id: true })
+ .extend(FeatureFlagsTestEvaluationCreateBody.shape)
+ .extend({ id: z.preprocess(castStringToInt, FeatureFlagsTestEvaluationCreateParams.shape['id']) })
+ .superRefine(validateDistinctIdPersonIdExclusive)
+ )
}
const featureFlagsTestEvaluationCreate = (): ToolBase<
@@ -833,26 +863,31 @@ const scheduledChangesUpdate = (): ToolBase<
const UpdateFeatureFlagSchema = () => {
const FeatureFlagsPartialUpdateBody = orvalSchemas.FeatureFlagsPartialUpdateBody()
const FeatureFlagsPartialUpdateParams = orvalSchemas.FeatureFlagsPartialUpdateParams()
- return FeatureFlagsPartialUpdateParams.omit({ project_id: true })
- .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.'
- ),
- ensure_experience_continuity: FeatureFlagsPartialUpdateBody.shape['ensure_experience_continuity'].describe(
- 'Whether to persist the flag\'s value for a user across the anonymous-to-identified transition (the "persist across authentication steps" option in the UI). Keeps a user\'s evaluated value stable once they log in. Incompatible with `device_id` bucketing.'
- ),
- evaluation_runtime: FeatureFlagsPartialUpdateBody.shape['evaluation_runtime'].describe(
- 'Where this flag is allowed to evaluate — `server` (server-side SDKs only), `client` (client-side SDKs only), or `all` (both). Defaults to `all`.'
- ),
- bucketing_identifier: FeatureFlagsPartialUpdateBody.shape['bucketing_identifier'].describe(
- 'Identifier used to bucket users into rollout percentages and variants — `distinct_id` (user ID, the default) or `device_id`. Using `device_id` is incompatible with `ensure_experience_continuity=true`.'
- ),
- })
+ return z.preprocess(
+ normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),
+ FeatureFlagsPartialUpdateParams.omit({ project_id: true })
+ .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.'
+ ),
+ ensure_experience_continuity: FeatureFlagsPartialUpdateBody.shape[
+ 'ensure_experience_continuity'
+ ].describe(
+ 'Whether to persist the flag\'s value for a user across the anonymous-to-identified transition (the "persist across authentication steps" option in the UI). Keeps a user\'s evaluated value stable once they log in. Incompatible with `device_id` bucketing.'
+ ),
+ evaluation_runtime: FeatureFlagsPartialUpdateBody.shape['evaluation_runtime'].describe(
+ 'Where this flag is allowed to evaluate — `server` (server-side SDKs only), `client` (client-side SDKs only), or `all` (both). Defaults to `all`.'
+ ),
+ bucketing_identifier: FeatureFlagsPartialUpdateBody.shape['bucketing_identifier'].describe(
+ 'Identifier used to bucket users into rollout percentages and variants — `distinct_id` (user ID, the default) or `device_id`. Using `device_id` is incompatible with `ensure_experience_continuity=true`.'
+ ),
+ })
+ )
}
const updateFeatureFlag = (): ToolBase<
diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.ts
index 5a045deb493e..2bb97e30512f 100644
--- a/services/mcp/src/tools/index.ts
+++ b/services/mcp/src/tools/index.ts
@@ -8,6 +8,7 @@ import parserRecipeReference from './aiObservability/parserRecipeReference'
// Debug
import debugMcpUiApps from './debug/debugMcpUiApps'
// Experiments (hand-written — CRUD + lifecycle are codegen in generated/experiments.ts)
+import experimentGetByFlagKey from './experiments/getByFlagKey'
import getExperimentResults from './experiments/getResults'
// Feature flags
import featureFlagGetDefinitionByKey from './featureFlags/getDefinitionByKey'
@@ -92,8 +93,9 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {
'path-cleaning-rules-update': updatePathCleaning,
- // Experiments (results is hand-written; CRUD + lifecycle are codegen)
+ // Experiments (results and get-by-flag-key are hand-written; CRUD + lifecycle are codegen)
'experiment-results-get': getExperimentResults,
+ 'experiment-get-by-flag-key': experimentGetByFlagKey,
// Insights
'insight-query': queryInsight,
diff --git a/services/mcp/tests/fixtures/experiment-id-tools.ts b/services/mcp/tests/fixtures/experiment-id-tools.ts
new file mode 100644
index 000000000000..1aea38a5d4e1
--- /dev/null
+++ b/services/mcp/tests/fixtures/experiment-id-tools.ts
@@ -0,0 +1,33 @@
+import type { GENERATED_TOOLS } from '@/tools/generated/experiments'
+
+/**
+ * One row per experiment tool that has `param_overrides: { id: ... }` in
+ * products/experiments/mcp/tools.yaml, with stand-in values for the tool's other
+ * required inputs so a parameterised assertion can build a minimal valid input for
+ * every shape. The id cast test and the id alias test both parse against this table,
+ * so adding a cast'd or aliased experiment tool means appending one row here.
+ */
+export const EXPERIMENT_ID_TOOLS = [
+ ['experiment-activity', {}],
+ ['experiment-archive', {}],
+ ['experiment-cleanup-task', {}],
+ ['experiment-copy-to-project', { target_team_id: 5 }],
+ ['experiment-delete', {}],
+ ['experiment-duplicate', { name: 'A duplicate', feature_flag_key: 'duplicated-flag' }],
+ ['experiment-end', {}],
+ ['experiment-freeze-exposure', {}],
+ ['experiment-get', {}],
+ ['experiment-launch', {}],
+ ['experiment-metrics-recalculation-create', {}],
+ ['experiment-metrics-recalculation-latest-retrieve', {}],
+ ['experiment-metrics-recalculation-retrieve', { recalculation_id: '0199a1c0-0000-7000-8000-000000000000' }],
+ ['experiment-pause', {}],
+ ['experiment-reset', {}],
+ ['experiment-resume', {}],
+ ['experiment-ship-variant', { variant_key: 'test' }],
+ ['experiment-timeseries-results', { metric_uuid: 'metric-uuid', fingerprint: 'fp' }],
+ ['experiment-unarchive', {}],
+ ['experiment-unfreeze-exposure', {}],
+ ['experiment-update', {}],
+ ['experiments-session-event-deltas-create', {}],
+] as const satisfies ReadonlyArray<readonly [keyof typeof GENERATED_TOOLS, Record<string, unknown>]>
diff --git a/services/mcp/tests/tools/experiments.integration.test.ts b/services/mcp/tests/tools/experiments.integration.test.ts
index 39010bd28219..1a85038f3802 100644
--- a/services/mcp/tests/tools/experiments.integration.test.ts
+++ b/services/mcp/tests/tools/experiments.integration.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeAll, describe, expect, it } from 'vitest'
+import { PostHogApiError } from '@/lib/errors'
import {
type CreatedResources,
TEST_ORG_ID,
@@ -12,6 +13,7 @@ import {
setActiveProjectAndOrg,
validateEnvironmentVariables,
} from '@/shared/test-utils'
+import experimentGetByFlagKey from '@/tools/experiments/getByFlagKey'
import getExperimentResultsTool from '@/tools/experiments/getResults'
import { GENERATED_TOOLS } from '@/tools/generated/experiments'
import type { Context } from '@/tools/types'
@@ -53,6 +55,7 @@ describe('Experiments', { concurrent: false }, () => {
const launchTool = GENERATED_TOOLS['experiment-launch']!()
const endTool = GENERATED_TOOLS['experiment-end']!()
const archiveTool = GENERATED_TOOLS['experiment-archive']!()
+ const duplicateTool = GENERATED_TOOLS['experiment-duplicate']!()
const pauseTool = GENERATED_TOOLS['experiment-pause']!()
const resumeTool = GENERATED_TOOLS['experiment-resume']!()
const resetTool = GENERATED_TOOLS['experiment-reset']!()
@@ -1466,4 +1469,123 @@ describe('Experiments', { concurrent: false }, () => {
expect(found).toBeFalsy()
})
})
+
+ describe('id ergonomics (aliases, by-flag-key, typed not-found)', () => {
+ const getByFlagKeyTool = experimentGetByFlagKey()
+
+ const createDraft = async (prefix: string): Promise<{ id: number; feature_flag_key: string }> => {
+ const flagKey = generateUniqueKey(prefix)
+ const result = await createTool.handler(context, {
+ name: `Id ergonomics ${prefix}`,
+ feature_flag_key: flagKey,
+ allow_unknown_events: true,
+ } as any)
+ const experiment = parseToolResponse(result)
+ trackExperiment(experiment)
+ return { id: experiment.id, feature_flag_key: flagKey }
+ }
+
+ // Only an ended experiment can be archived; archiving with the flag disabled is what
+ // cascades the archive onto the flag and hides it from the default flag list.
+ const launchAndArchive = async (id: number): Promise<void> => {
+ await launchTool.handler(context, { id } as any)
+ await endTool.handler(context, { id } as any)
+ parseToolResponse(await archiveTool.handler(context, { id, disable_feature_flag: true } as any))
+ }
+
+ it('experiment-get accepts experimentId through its schema, against the live API', async () => {
+ const created = await createDraft('exp-alias')
+
+ const params = getTool.schema.parse({ experimentId: String(created.id) })
+ expect(params).toEqual({ id: created.id })
+
+ const experiment = parseToolResponse(await getTool.handler(context, params as any))
+ expect(experiment.id).toBe(created.id)
+ expect(experiment.feature_flag_key).toBe(created.feature_flag_key)
+ })
+
+ it('experiment-get-by-flag-key returns the full experiment for its flag key', async () => {
+ const created = await createDraft('exp-by-key')
+
+ const params = getByFlagKeyTool.schema.parse({ flagKey: created.feature_flag_key })
+ const result = parseToolResponse(await getByFlagKeyTool.handler(context, params))
+
+ expect(result.found).toBe(true)
+ expect(result.id).toBe(created.id)
+ expect(result.feature_flag_key).toBe(created.feature_flag_key)
+ expect(result.metrics).toBeTruthy()
+ expect(result._posthogUrl).toContain(`/experiments/${created.id}`)
+ })
+
+ it('experiment-get-by-flag-key returns found:false as data when no flag has the key', async () => {
+ const missingKey = generateUniqueKey('exp-by-key-missing')
+
+ const result = parseToolResponse(await getByFlagKeyTool.handler(context, { feature_flag_key: missingKey }))
+
+ expect(result.found).toBe(false)
+ expect(result.reason).toBe('no_flag')
+ expect(result.feature_flag_key).toBe(missingKey)
+ expect(result.message).toContain(missingKey)
+ })
+
+ it('experiment-get surfaces a guessed id as a typed 404 that keeps the recovery message', async () => {
+ const thrown = await getTool.handler(context, { id: 999999999 } as any).then(
+ () => undefined,
+ (error: unknown) => error
+ )
+
+ expect(thrown).toBeInstanceOf(PostHogApiError)
+ expect((thrown as PostHogApiError).status).toBe(404)
+ expect((thrown as PostHogApiError).message).toContain('Experiment 999999999 not found in this project')
+ expect((thrown as PostHogApiError).message).toContain('experiment-list')
+ })
+
+ it('experiment-get-by-flag-key finds an archived experiment whose flag the flag list hides', async () => {
+ const created = await createDraft('exp-by-key-archived')
+ await launchAndArchive(created.id)
+
+ const result = parseToolResponse(
+ await getByFlagKeyTool.handler(context, { feature_flag_key: created.feature_flag_key })
+ )
+
+ expect(result.found).toBe(true)
+ expect(result.id).toBe(created.id)
+ expect(result.archived).toBe(true)
+ })
+
+ it('experiment-get-by-flag-key returns candidates for two drafts on one flag, then picks the live one', async () => {
+ const created = await createDraft('exp-by-key-dup')
+ const duplicate = parseToolResponse(
+ await duplicateTool.handler(context, {
+ id: created.id,
+ name: 'Id ergonomics duplicate',
+ feature_flag_key: created.feature_flag_key,
+ } as any)
+ )
+ trackExperiment(duplicate)
+ expect(duplicate.feature_flag_key).toBe(created.feature_flag_key)
+
+ const ambiguous = parseToolResponse(
+ await getByFlagKeyTool.handler(context, { feature_flag_key: created.feature_flag_key })
+ )
+ expect(ambiguous.found).toBe(false)
+ expect(ambiguous.reason).toBe('ambiguous')
+ expect(ambiguous.candidates.map((candidate: { id: number }) => candidate.id).sort()).toEqual(
+ [created.id, duplicate.id].sort()
+ )
+ for (const candidate of ambiguous.candidates) {
+ expect(candidate).toMatchObject({ status: 'draft', archived: false })
+ expect(candidate.name).toBeTruthy()
+ expect(candidate.created_at).toBeTruthy()
+ }
+
+ await launchAndArchive(duplicate.id)
+
+ const picked = parseToolResponse(
+ await getByFlagKeyTool.handler(context, { feature_flag_key: created.feature_flag_key })
+ )
+ expect(picked.found).toBe(true)
+ expect(picked.id).toBe(created.id)
+ })
+ })
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-get-by-flag-key.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-get-by-flag-key.json
new file mode 100644
index 000000000000..e8c895b8b8c7
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-get-by-flag-key.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "feature_flag_key": {
+ "description": "The experiment's feature flag key: the string identifier used in code (e.g. \"new-checkout\").",
+ "type": "string"
+ }
+ },
+ "required": ["feature_flag_key"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/experiment-get-by-flag-key.test.ts b/services/mcp/tests/unit/experiment-get-by-flag-key.test.ts
new file mode 100644
index 000000000000..cd9bcfa1f894
--- /dev/null
+++ b/services/mcp/tests/unit/experiment-get-by-flag-key.test.ts
@@ -0,0 +1,227 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { ToolInputValidationError } from '@/lib/errors'
+import experimentGetByFlagKey from '@/tools/experiments/getByFlagKey'
+import type { Context } from '@/tools/types'
+
+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 () => {},
+ }
+}
+
+const flag = (
+ id: number,
+ key: string,
+ experimentIds: number[] = []
+): { id: number; key: string; name: string; experiment_set: number[] } => ({
+ id,
+ key,
+ name: key,
+ experiment_set: experimentIds,
+})
+const experiment = (
+ id: number,
+ key: string,
+ extra: Record<string, unknown> = {}
+): { id: number; name: string; feature_flag_key: string } => ({
+ id,
+ name: `Experiment ${id}`,
+ feature_flag_key: key,
+ ...extra,
+})
+
+const FLAG_LIST = { method: 'GET', path: '/api/projects/42/feature_flags/', query: { key: 'new-checkout', limit: 20 } }
+const FLAG_LIST_ARCHIVED = {
+ method: 'GET',
+ path: '/api/projects/42/feature_flags/',
+ query: { key: 'new-checkout', archived: true, limit: 20 },
+}
+const EXPERIMENTS_LIVE = {
+ method: 'GET',
+ path: '/api/projects/42/experiments/',
+ query: { feature_flag_id: 7, limit: 50 },
+}
+const EXPERIMENTS_ARCHIVED = {
+ method: 'GET',
+ path: '/api/projects/42/experiments/',
+ query: { feature_flag_id: 7, archived: true, limit: 50 },
+}
+const EXPERIMENT_GET = (id: number): { method: string; path: string } => ({
+ method: 'GET',
+ path: `/api/projects/42/experiments/${id}/`,
+})
+
+describe('experiment-get-by-flag-key', () => {
+ const tool = experimentGetByFlagKey()
+
+ it('resolves the flag key to its single linked experiment and returns the full experiment', async () => {
+ const request = vi
+ .fn()
+ .mockResolvedValueOnce({ results: [flag(7, 'new-checkout', [11])] })
+ .mockResolvedValueOnce({ ...experiment(11, 'new-checkout'), metrics: [] })
+
+ const result = await tool.handler(createMockContext(request), { feature_flag_key: 'new-checkout' })
+
+ // The flag row already lists its experiments: one list call, then the full experiment.
+ expect(request).toHaveBeenCalledTimes(2)
+ expect(request).toHaveBeenNthCalledWith(1, FLAG_LIST)
+ expect(request).toHaveBeenNthCalledWith(2, EXPERIMENT_GET(11))
+ expect(result).toMatchObject({ id: 11, feature_flag_key: 'new-checkout', metrics: [], found: true })
+ expect((result as { _posthogUrl?: string })._posthogUrl).toContain('/experiments/11')
+ })
+
+ it('finds the experiment behind an archived flag, which the flag list hides by default', async () => {
+ const request = vi
+ .fn()
+ .mockResolvedValueOnce({ results: [] })
+ .mockResolvedValueOnce({ results: [{ ...flag(7, 'new-checkout', [11]), archived: true }] })
+ .mockResolvedValueOnce({ ...experiment(11, 'new-checkout'), archived: true })
+
+ const result = await tool.handler(createMockContext(request), { feature_flag_key: 'new-checkout' })
+
+ expect(request).toHaveBeenNthCalledWith(2, FLAG_LIST_ARCHIVED)
+ expect(result).toMatchObject({ id: 11, archived: true, found: true })
+ })
+
+ it('picks the exact-case flag when the key filter also returns a same-key different-case duplicate', async () => {
+ const request = vi
+ .fn()
+ .mockResolvedValueOnce({ results: [flag(7, 'new-checkout', [11]), flag(8, 'New-Checkout', [12])] })
+ .mockResolvedValueOnce(experiment(11, 'new-checkout'))
+
+ const result = await tool.handler(createMockContext(request), { feature_flag_key: 'new-checkout' })
+
+ expect(request).toHaveBeenNthCalledWith(2, EXPERIMENT_GET(11))
+ expect(result).toMatchObject({ id: 11, found: true })
+ })
+
+ it('returns a non-error found:false result when no flag has the key, live or archived', async () => {
+ const request = vi.fn().mockResolvedValue({ results: [] })
+
+ const result = await tool.handler(createMockContext(request), { feature_flag_key: 'new-checkout' })
+
+ expect(result).toMatchObject({ found: false, reason: 'no_flag', feature_flag_key: 'new-checkout' })
+ expect((result as { message: string }).message).toContain('new-checkout')
+ expect(request).toHaveBeenCalledTimes(2)
+ expect(request).toHaveBeenNthCalledWith(2, FLAG_LIST_ARCHIVED)
+ })
+
+ it('returns a non-error found:false result when the flag exists but no experiment is linked to it', async () => {
+ const request = vi.fn().mockResolvedValueOnce({ results: [flag(7, 'new-checkout')] })
+
+ const result = await tool.handler(createMockContext(request), { feature_flag_key: 'new-checkout' })
+
+ expect(result).toMatchObject({ found: false, reason: 'no_experiment', feature_flag_key: 'new-checkout' })
+ expect((result as { message: string }).message).toContain('ID 7')
+ expect(request).toHaveBeenCalledTimes(1)
+ })
+
+ describe('several experiments on one flag (experiment-duplicate reuses the source flag)', () => {
+ it('picks the single live experiment over archived re-runs', async () => {
+ const request = vi
+ .fn()
+ .mockResolvedValueOnce({ results: [flag(7, 'new-checkout', [11, 12, 13])] })
+ .mockResolvedValueOnce({ results: [experiment(13, 'new-checkout')] })
+ .mockResolvedValueOnce(experiment(13, 'new-checkout'))
+
+ const result = await tool.handler(createMockContext(request), { feature_flag_key: 'new-checkout' })
+
+ expect(request).toHaveBeenNthCalledWith(2, EXPERIMENTS_LIVE)
+ expect(request).toHaveBeenNthCalledWith(3, EXPERIMENT_GET(13))
+ expect(result).toMatchObject({ id: 13, found: true })
+ })
+
+ it('picks the single archived experiment when none is live', async () => {
+ const request = vi
+ .fn()
+ .mockResolvedValueOnce({ results: [flag(7, 'new-checkout', [11, 12])] })
+ .mockResolvedValueOnce({ results: [] })
+ .mockResolvedValueOnce({ results: [experiment(12, 'new-checkout', { archived: true })] })
+ .mockResolvedValueOnce(experiment(12, 'new-checkout', { archived: true }))
+
+ const result = await tool.handler(createMockContext(request), { feature_flag_key: 'new-checkout' })
+
+ expect(request).toHaveBeenNthCalledWith(3, EXPERIMENTS_ARCHIVED)
+ expect(result).toMatchObject({ id: 12, found: true })
+ })
+
+ it('returns the candidates as data when none stands out', async () => {
+ const request = vi
+ .fn()
+ .mockResolvedValueOnce({ results: [flag(7, 'new-checkout', [11, 12, 13])] })
+ .mockResolvedValueOnce({
+ results: [
+ experiment(12, 'new-checkout', { status: 'running', created_at: '2026-08-01T00:00:00Z' }),
+ experiment(13, 'new-checkout', { status: 'draft', created_at: '2026-09-01T00:00:00Z' }),
+ ],
+ })
+ .mockResolvedValueOnce({ results: [experiment(11, 'new-checkout', { status: 'stopped' })] })
+
+ const result = await tool.handler(createMockContext(request), { feature_flag_key: 'new-checkout' })
+
+ expect(request).toHaveBeenCalledTimes(3)
+ expect(result).toMatchObject({ found: false, reason: 'ambiguous', feature_flag_key: 'new-checkout' })
+ expect((result as { candidates: unknown[] }).candidates).toEqual([
+ expect.objectContaining({
+ id: 12,
+ status: 'running',
+ archived: false,
+ created_at: '2026-08-01T00:00:00Z',
+ }),
+ expect.objectContaining({ id: 13, status: 'draft', archived: false }),
+ expect.objectContaining({ id: 11, status: 'stopped', archived: true }),
+ ])
+ expect((result as { message: string }).message).toContain('experiment-get')
+ })
+ })
+
+ it('raises a validation error when a key matches multiple flags only case-insensitively', async () => {
+ const request = vi.fn().mockResolvedValueOnce({ results: [flag(7, 'Checkout', [1]), flag(8, 'CHECKOUT', [2])] })
+
+ await expect(tool.handler(createMockContext(request), { feature_flag_key: 'checkout' })).rejects.toBeInstanceOf(
+ ToolInputValidationError
+ )
+ })
+
+ it('raises a validation error for a blank key without calling the API', async () => {
+ const request = vi.fn()
+
+ await expect(tool.handler(createMockContext(request), { feature_flag_key: ' ' })).rejects.toBeInstanceOf(
+ ToolInputValidationError
+ )
+ expect(request).not.toHaveBeenCalled()
+ })
+
+ describe('input aliases', () => {
+ it.each([
+ ['feature_flag_key', { feature_flag_key: 'new-checkout' }],
+ ['flagKey', { flagKey: 'new-checkout' }],
+ ['flag_key', { flag_key: 'new-checkout' }],
+ ['featureFlagKey', { featureFlagKey: 'new-checkout' }],
+ ['key', { key: 'new-checkout' }],
+ ])('accepts %s', (_label, input) => {
+ const result = tool.schema.safeParse(input)
+ expect(result.success).toBe(true)
+ expect(result.data).toEqual({ feature_flag_key: 'new-checkout' })
+ })
+
+ it('prefers the canonical name on conflict', () => {
+ const result = tool.schema.safeParse({ feature_flag_key: 'a', key: 'b' })
+ expect(result.data).toEqual({ feature_flag_key: 'a' })
+ })
+
+ it('still rejects a call with no key', () => {
+ expect(tool.schema.safeParse({}).success).toBe(false)
+ })
+ })
+})
diff --git a/services/mcp/tests/unit/experiment-id-aliases.test.ts b/services/mcp/tests/unit/experiment-id-aliases.test.ts
new file mode 100644
index 000000000000..a9d91d27d5b6
--- /dev/null
+++ b/services/mcp/tests/unit/experiment-id-aliases.test.ts
@@ -0,0 +1,183 @@
+import { describe, expect, it } from 'vitest'
+import { z } from 'zod'
+
+import { ExperimentResultsGetSchema } from '@/schema/tool-inputs'
+import { GENERATED_TOOLS as EXPERIMENT_TOOLS } from '@/tools/generated/experiments'
+import { GENERATED_TOOLS as FEATURE_FLAG_TOOLS } from '@/tools/generated/feature_flags'
+
+import { EXPERIMENT_ID_TOOLS } from '../fixtures/experiment-id-tools'
+
+// Production traces show the dominant validation failure on the experiment tools is the
+// experiment id arriving as `experimentId` / `experiment_id` where the schema requires
+// `id` (the same mismatch the insight and flag tools already absorb). Every alias must
+// normalize to `id` on every tool that takes an experiment id, or those failures come back.
+/** Tool names whose advertised input schema has a top-level `id` property. */
+function toolsWithIdParam(tools: Record<string, () => { schema: z.ZodTypeAny }>): string[] {
+ return Object.entries(tools)
+ .filter(([, factory]) => {
+ const json = z.toJSONSchema(factory().schema, { io: 'input', reused: 'inline' }) as {
+ properties?: Record<string, unknown>
+ }
+ return Boolean(json.properties?.id)
+ })
+ .map(([name]) => name)
+ .sort()
+}
+
+describe('experiment id aliases', () => {
+ const ALIAS_KEYS = ['experimentId', 'experiment_id'] as const
+
+ // `id` on these is a holdout or saved-metric id, not an experiment id.
+ const NON_EXPERIMENT_ID_TOOLS = new Set([
+ 'experiment-holdouts-retrieve',
+ 'experiment-holdouts-partial-update',
+ 'experiment-holdouts-destroy',
+ 'experiment-saved-metrics-retrieve',
+ 'experiment-saved-metrics-partial-update',
+ 'experiment-saved-metrics-destroy',
+ ])
+
+ // The alias list is hand-maintained; this keeps it in step with the generated tools so
+ // a new id-taking experiment tool cannot ship without the aliases.
+ it('covers every generated experiment tool that takes an experiment id', () => {
+ const idTools = toolsWithIdParam(EXPERIMENT_TOOLS).filter((name) => !NON_EXPERIMENT_ID_TOOLS.has(name))
+ expect(idTools).toEqual(EXPERIMENT_ID_TOOLS.map(([name]) => name).sort())
+ })
+
+ describe.each(EXPERIMENT_ID_TOOLS)('%s normalizes aliases to `id`', (toolName, extras) => {
+ const factory = EXPERIMENT_TOOLS[toolName]
+
+ it('is a generated tool', () => {
+ expect(factory).not.toBeUndefined()
+ })
+
+ it.each([
+ ['id (numeric)', { id: 123 }, 123],
+ ['id (numeric string)', { id: '123' }, 123],
+ ['experimentId', { experimentId: 123 }, 123],
+ ['experiment_id', { experiment_id: 123 }, 123],
+ ['experiment_id (numeric string)', { experiment_id: '123' }, 123],
+ ['id over aliases on conflict', { id: 1, experimentId: 2, experiment_id: 3 }, 1],
+ ['first-listed alias on alias conflict', { experimentId: 2, experiment_id: 3 }, 2],
+ ])('accepts %s', (_label, input, expected) => {
+ const schema = factory!().schema
+ const result = schema.safeParse({ ...extras, ...input })
+ expect(result.success, JSON.stringify(result.error?.issues)).toBe(true)
+ const data = result.data as Record<string, unknown>
+ expect(data.id).toEqual(expected)
+ for (const alias of ALIAS_KEYS) {
+ expect(data).not.toHaveProperty(alias)
+ }
+ })
+
+ it('still rejects a call with no identifier', () => {
+ expect(factory!().schema.safeParse({ ...extras }).success).toBe(false)
+ })
+ })
+
+ describe('experiment-metrics-recalculation-retrieve normalizes run id aliases to `recalculation_id`', () => {
+ const schema = EXPERIMENT_TOOLS['experiment-metrics-recalculation-retrieve']!().schema
+ const runId = '0199a1c0-0000-7000-8000-000000000000'
+
+ it.each([
+ ['recalculation_id', { id: 1, recalculation_id: runId }],
+ ['run_id', { id: 1, run_id: runId }],
+ ['runId', { id: 1, runId: runId }],
+ ['recalculationId', { experimentId: 1, recalculationId: runId }],
+ ['recalculation_id over aliases on conflict', { id: 1, recalculation_id: runId, run_id: 'stale' }],
+ ])('accepts %s', (_label, input) => {
+ const result = schema.safeParse(input)
+ expect(result.success, JSON.stringify(result.error?.issues)).toBe(true)
+ const data = result.data as Record<string, unknown>
+ expect(data.id).toBe(1)
+ expect(data.recalculation_id).toBe(runId)
+ for (const alias of ['run_id', 'runId', 'recalculationId']) {
+ expect(data).not.toHaveProperty(alias)
+ }
+ })
+
+ it('still rejects a call with no run id', () => {
+ expect(schema.safeParse({ id: 1 }).success).toBe(false)
+ })
+ })
+
+ describe('experiment-results-get (hand-written) normalizes aliases to `id`', () => {
+ it.each([
+ ['id (numeric)', { id: 123 }, 123],
+ ['id (numeric string)', { id: '123' }, 123],
+ ['experimentId', { experimentId: 123 }, 123],
+ ['experiment_id', { experiment_id: '123' }, 123],
+ ['id over aliases on conflict', { id: 1, experimentId: 2 }, 1],
+ ])('accepts %s', (_label, input, expected) => {
+ const result = ExperimentResultsGetSchema.safeParse(input)
+ expect(result.success, JSON.stringify(result.error?.issues)).toBe(true)
+ expect(result.data?.id).toBe(expected)
+ expect(result.data?.refresh).toBe(false)
+ for (const alias of ALIAS_KEYS) {
+ expect(result.data).not.toHaveProperty(alias)
+ }
+ })
+
+ it('still rejects a call with no identifier', () => {
+ expect(ExperimentResultsGetSchema.safeParse({}).success).toBe(false)
+ })
+ })
+})
+
+// The flag tools only gained aliases on the by-key lookup; the id-based tools kept failing on
+// `flagId` / `flag_id` at the same rate, so they take the numeric-id aliases too.
+describe('feature flag id aliases', () => {
+ const FLAG_ID_TOOLS = [
+ 'delete-feature-flag',
+ 'feature-flag-archive',
+ 'feature-flag-disable',
+ 'feature-flag-enable',
+ 'feature-flag-get-definition',
+ 'feature-flag-unarchive',
+ 'feature-flags-activity-retrieve',
+ 'feature-flags-dependent-flags-retrieve',
+ 'feature-flags-status-retrieve',
+ 'feature-flags-test-evaluation-create',
+ 'update-feature-flag',
+ ] as const
+
+ const ALIAS_KEYS = ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] as const
+
+ const REQUIRED_EXTRAS: Record<string, Record<string, unknown>> = {
+ 'feature-flags-test-evaluation-create': { distinct_id: 'user-1' },
+ }
+
+ // `id` on these is a scheduled change id, not a flag id.
+ const NON_FLAG_ID_TOOLS = new Set(['scheduled-changes-delete', 'scheduled-changes-get', 'scheduled-changes-update'])
+
+ it('covers every generated flag tool that takes a flag id', () => {
+ const idTools = toolsWithIdParam(FEATURE_FLAG_TOOLS).filter((name) => !NON_FLAG_ID_TOOLS.has(name))
+ expect(idTools).toEqual([...FLAG_ID_TOOLS].sort())
+ })
+
+ describe.each(FLAG_ID_TOOLS.map((name) => [name]))('%s normalizes aliases to `id`', (toolName) => {
+ const factory = FEATURE_FLAG_TOOLS[toolName]
+ const extras = REQUIRED_EXTRAS[toolName] ?? {}
+
+ it.each([
+ ['id (numeric)', { id: 7 }, 7],
+ ['flagId', { flagId: 7 }, 7],
+ ['flag_id', { flag_id: '7' }, 7],
+ ['feature_flag_id', { feature_flag_id: 7 }, 7],
+ ['featureFlagId', { featureFlagId: 7 }, 7],
+ ['id over aliases on conflict', { id: 1, flagId: 2 }, 1],
+ ])('accepts %s', (_label, input, expected) => {
+ const result = factory!().schema.safeParse({ ...extras, ...input })
+ expect(result.success, JSON.stringify(result.error?.issues)).toBe(true)
+ const data = result.data as Record<string, unknown>
+ expect(data.id).toEqual(expected)
+ for (const alias of ALIAS_KEYS) {
+ expect(data).not.toHaveProperty(alias)
+ }
+ })
+
+ it('still rejects a call with no identifier', () => {
+ expect(factory!().schema.safeParse({ ...extras }).success).toBe(false)
+ })
+ })
+})
diff --git a/services/mcp/tests/unit/experiment-not-found.test.ts b/services/mcp/tests/unit/experiment-not-found.test.ts
new file mode 100644
index 000000000000..4c8254c9eb65
--- /dev/null
+++ b/services/mcp/tests/unit/experiment-not-found.test.ts
@@ -0,0 +1,269 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { ApiClient } from '@/api/client'
+import {
+ findRecoverableApiError,
+ handleToolError,
+ PostHogApiError,
+ PostHogPermissionError,
+ PostHogRateLimitError,
+ PostHogValidationError,
+} from '@/lib/errors'
+import { getResultsHandler } from '@/tools/experiments/getResults'
+import type { Context } from '@/tools/types'
+
+const captureException = vi.fn()
+vi.mock('@/lib/posthog', () => ({
+ getPostHogClient: () => ({ captureException }),
+}))
+vi.mock('@/lib/posthog/analytics', () => ({
+ AnalyticsEvent: { MCP_TOOL_CALL: '$mcp_tool_call' },
+}))
+vi.mock('@/lib/posthog/flags', () => ({
+ isFeatureFlagEnabled: vi.fn().mockResolvedValue(false),
+}))
+
+// An agent passing a guessed or stale experiment id gets a 404. The client rewrites it
+// into a message that names the recovery path, but that message must stay a typed 4xx:
+// a bare Error skipped the recoverable branch of handleToolError, so every such miss was
+// captured as an exception and counted as an internal failure with no message.
+describe('experiment not-found rewrite', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ })
+
+ const stubNotFound = (): void => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(new Response(JSON.stringify({ detail: 'Not found.' }), { status: 404 }))
+ )
+ }
+ const buildClient = (): ApiClient => new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://us.posthog.com' })
+
+ it('returns a typed 404 that keeps the experiment-specific message', async () => {
+ stubNotFound()
+
+ const result = await buildClient().experiments({ projectId: '42' }).get({ experimentId: 999 })
+
+ expect(result.success).toBe(false)
+ if (result.success) {
+ return
+ }
+ expect(result.error).toBeInstanceOf(PostHogApiError)
+ expect((result.error as PostHogApiError).status).toBe(404)
+ expect(result.error.message).toContain('Experiment 999 not found in this project')
+ expect(result.error.message).toContain('experiment-list')
+ })
+
+ it('rewrites a lifecycle action 404 that carries only the generic detail, since that means the experiment is missing', async () => {
+ stubNotFound()
+
+ const result = await buildClient()
+ .request({ method: 'POST', path: '/api/projects/42/experiments/999/launch/' })
+ .then(
+ () => undefined,
+ (error: unknown) => error
+ )
+
+ expect(result).toBeInstanceOf(PostHogApiError)
+ expect((result as PostHogApiError).status).toBe(404)
+ expect((result as PostHogApiError).message).toContain('Experiment 999 not found in this project')
+ })
+
+ it('passes a sub-resource 404 through with the backend detail instead of claiming the experiment is missing', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValue(
+ new Response(JSON.stringify({ detail: 'No completed recalculation found' }), { status: 404 })
+ )
+ )
+
+ const result = await buildClient()
+ .request({ method: 'GET', path: '/api/projects/42/experiments/29/metrics_recalculation/latest/' })
+ .then(
+ () => undefined,
+ (error: unknown) => error
+ )
+
+ expect(result).toBeInstanceOf(PostHogApiError)
+ expect((result as PostHogApiError).status).toBe(404)
+ expect((result as PostHogApiError).message).toContain('No completed recalculation found')
+ expect((result as PostHogApiError).message).not.toContain('Experiment 29 not found')
+ })
+
+ it('still rewrites the experiment resource 404 when the URL carries a query string', async () => {
+ stubNotFound()
+
+ const result = await buildClient()
+ .request({ method: 'GET', path: '/api/projects/42/experiments/999/', query: { refresh: true } })
+ .then(
+ () => undefined,
+ (error: unknown) => error
+ )
+
+ expect((result as PostHogApiError).message).toContain('Experiment 999 not found in this project')
+ })
+
+ it('keeps the plain path for 404s on other endpoints', async () => {
+ stubNotFound()
+
+ const result = await buildClient()
+ .request({ method: 'GET', path: '/api/projects/42/feature_flags/999/' })
+ .then(
+ () => undefined,
+ (error: unknown) => error
+ )
+
+ expect(result).toBeInstanceOf(PostHogApiError)
+ expect((result as PostHogApiError).status).toBe(404)
+ expect((result as PostHogApiError).message).not.toContain('Experiment')
+ })
+
+ it('is handled as agent-recoverable: the message is returned verbatim and no exception is captured', async () => {
+ stubNotFound()
+
+ const result = await buildClient().experiments({ projectId: '42' }).get({ experimentId: 999 })
+ const handled = handleToolError(result.success ? undefined : result.error, 'experiment-get')
+
+ expect(handled.isError).toBe(true)
+ expect(handled.content[0]).toMatchObject({
+ type: 'text',
+ text: expect.stringContaining('Experiment 999 not found in this project'),
+ })
+ expect(captureException).not.toHaveBeenCalled()
+ })
+
+ it('stays reachable through the results tool, which wraps the failure with a cause', async () => {
+ const notFound = new PostHogApiError({
+ status: 404,
+ statusText: 'Not Found',
+ body: '{"detail":"Not found."}',
+ url: 'https://us.posthog.com/api/projects/42/experiments/999/',
+ method: 'GET',
+ message: 'Experiment 999 not found in this project.',
+ })
+ const context = {
+ api: {
+ experiments: () => ({
+ getMetricResults: vi.fn().mockResolvedValue({ success: false, error: notFound }),
+ }),
+ },
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('42') },
+ } as unknown as Context
+
+ const thrown = await getResultsHandler(context, { id: 999, refresh: false }).then(
+ () => undefined,
+ (error: unknown) => error
+ )
+
+ expect(thrown).toBeInstanceOf(Error)
+ expect((thrown as Error).message).toContain('Experiment 999 not found in this project')
+ expect(findRecoverableApiError(thrown)).toBe(notFound)
+ expect(handleToolError(thrown, 'experiment-results-get').isError).toBe(true)
+ expect(captureException).not.toHaveBeenCalled()
+ })
+
+ it('keeps other 4xx failures of the results tool captured, since they point at a query built here', async () => {
+ const badQuery = new PostHogValidationError({
+ detail: 'exposure_criteria contains unknown key(s): properties.',
+ attr: 'exposure_criteria',
+ code: 'invalid_input',
+ extra: undefined,
+ url: 'https://us.posthog.com/api/environments/42/query/',
+ method: 'POST',
+ })
+ const context = {
+ api: {
+ experiments: () => ({
+ getMetricResults: vi.fn().mockResolvedValue({ success: false, error: badQuery }),
+ }),
+ },
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('42') },
+ } as unknown as Context
+
+ const thrown = await getResultsHandler(context, { id: 999, refresh: false }).then(
+ () => undefined,
+ (error: unknown) => error
+ )
+
+ expect((thrown as Error).message).toContain('Failed to get experiment results')
+ expect(findRecoverableApiError(thrown)).toBeUndefined()
+ const handled = handleToolError(thrown, 'experiment-results-get')
+ expect(handled.isError).toBe(true)
+ expect(handled.content[0]).toMatchObject({ text: expect.stringContaining('unknown key(s): properties') })
+ expect(captureException).toHaveBeenCalledTimes(1)
+ })
+
+ const resultsContextFailingWith = (error: Error): Context =>
+ ({
+ api: {
+ experiments: () => ({
+ getMetricResults: vi.fn().mockResolvedValue({ success: false, error }),
+ }),
+ },
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('42') },
+ }) as unknown as Context
+
+ const throwFromResults = (error: Error): Promise<unknown> =>
+ getResultsHandler(resultsContextFailingWith(error), { id: 999, refresh: false }).then(
+ () => undefined,
+ (thrown: unknown) => thrown
+ )
+
+ it('keeps a rate limit on the results tool agent-recoverable instead of capturing it', async () => {
+ const throttled = new PostHogRateLimitError({
+ body: '{"detail":"Request was throttled."}',
+ url: 'https://us.posthog.com/api/environments/42/query/',
+ method: 'POST',
+ retryAfterSeconds: 5,
+ })
+
+ const thrown = await throwFromResults(throttled)
+
+ expect(findRecoverableApiError(thrown)).toBe(throttled)
+ const handled = handleToolError(thrown, 'experiment-results-get')
+ expect(handled.content[0]).toMatchObject({ text: expect.stringContaining('rate limit') })
+ expect(captureException).not.toHaveBeenCalled()
+ })
+
+ it('keeps a permission denial on the results tool on the permission path with its guidance', async () => {
+ const denied = new PostHogPermissionError({
+ detail: 'You do not have access to this project.',
+ url: 'https://us.posthog.com/api/environments/42/query/',
+ method: 'POST',
+ })
+
+ const thrown = await throwFromResults(denied)
+
+ const handled = handleToolError(thrown, 'experiment-results-get')
+ expect(handled.content[0]).toMatchObject({ text: expect.stringContaining('do not have access') })
+ expect(captureException).toHaveBeenCalledWith(
+ expect.anything(),
+ undefined,
+ expect.objectContaining({ is_permission_error: true })
+ )
+ })
+
+ it('still captures a 5xx from the results tool as an exception', async () => {
+ const serverError = new PostHogApiError({
+ status: 500,
+ statusText: 'Internal Server Error',
+ body: '{"detail":"query failed"}',
+ url: 'https://us.posthog.com/api/environments/42/query/',
+ method: 'POST',
+ })
+
+ const thrown = await throwFromResults(serverError)
+
+ expect(handleToolError(thrown, 'experiment-results-get').isError).toBe(true)
+ expect(captureException).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/services/mcp/tests/unit/experiments-schema-cast.test.ts b/services/mcp/tests/unit/experiments-schema-cast.test.ts
index ed16d7c2b2c8..479925c9131f 100644
--- a/services/mcp/tests/unit/experiments-schema-cast.test.ts
+++ b/services/mcp/tests/unit/experiments-schema-cast.test.ts
@@ -23,6 +23,8 @@ import { z } from 'zod'
import { GENERATED_TOOLS } from '@/tools/generated/experiments'
import type { ToolBase, ZodObjectAny } from '@/tools/types'
+import { EXPERIMENT_ID_TOOLS } from '../fixtures/experiment-id-tools'
+
const PROJECT_ID = '2'
/** Resolve a generated tool's input schema. Cast through `unknown` so individual
@@ -39,38 +41,14 @@ function parseWith(schema: z.ZodTypeAny, input: unknown): Record<string, unknown
return schema.parse(input) as Record<string, unknown>
}
-/**
- * One row per lifecycle tool that has `param_overrides: { id: { cast: 'string-int' } }`
- * in tools.yaml. The `extras` map captures each tool's *additional* required-input
- * fields beyond `id`/`project_id`, so the parameterised assertion can build a minimal
- * valid input for every shape. Adding a new cast'd lifecycle tool means appending
- * one row here — the test will then cover it automatically.
- */
-const LIFECYCLE_TOOLS_WITH_ID_CAST = [
- ['experiment-archive', {}],
- ['experiment-copy-to-project', { target_team_id: 5 }],
- ['experiment-delete', {}],
- ['experiment-duplicate', { name: 'A duplicate', feature_flag_key: 'duplicated-flag' }],
- ['experiment-end', {}],
- ['experiment-get', {}],
- ['experiment-launch', {}],
- ['experiment-pause', {}],
- ['experiment-reset', {}],
- ['experiment-resume', {}],
- ['experiment-ship-variant', { variant_key: 'test' }],
- ['experiment-timeseries-results', { metric_uuid: 'metric-uuid', fingerprint: 'fp' }],
- ['experiment-unarchive', {}],
- ['experiment-update', {}],
-] as const satisfies ReadonlyArray<readonly [keyof typeof GENERATED_TOOLS, Record<string, unknown>]>
-
describe('experiment lifecycle tools — id cast', () => {
- it.each(LIFECYCLE_TOOLS_WITH_ID_CAST)('%s accepts a stringified id', (toolName, extras) => {
+ it.each(EXPERIMENT_ID_TOOLS)('%s accepts a stringified id', (toolName, extras) => {
const parsed = parseWith(getToolSchema(toolName), { id: '123', project_id: PROJECT_ID, ...extras })
expect(parsed.id).toBe(123)
expect(typeof parsed.id).toBe('number')
})
- it.each(LIFECYCLE_TOOLS_WITH_ID_CAST)('%s still accepts a plain numeric id', (toolName, extras) => {
+ it.each(EXPERIMENT_ID_TOOLS)('%s still accepts a plain numeric id', (toolName, extras) => {
const parsed = parseWith(getToolSchema(toolName), { id: 123, project_id: PROJECT_ID, ...extras })
expect(parsed.id).toBe(123)
})
diff --git a/services/mcp/tests/unit/feature-flag-get-definition-by-key.test.ts b/services/mcp/tests/unit/feature-flag-get-definition-by-key.test.ts
index 52f21bb45710..e16a09f2509f 100644
--- a/services/mcp/tests/unit/feature-flag-get-definition-by-key.test.ts
+++ b/services/mcp/tests/unit/feature-flag-get-definition-by-key.test.ts
@@ -35,7 +35,7 @@ describe('feature-flag-get-definition-by-key', () => {
expect(request).toHaveBeenCalledWith({
method: 'GET',
path: '/api/projects/42/feature_flags/',
- query: { key: 'new-checkout', limit: 5 },
+ query: { key: 'new-checkout', limit: 20 },
})
expect(result).toMatchObject({ id: 7, key: 'new-checkout', found: true })
})
@@ -64,14 +64,32 @@ describe('feature-flag-get-definition-by-key', () => {
)
})
- it('returns a non-error found:false result naming the missing key when no flag matches', async () => {
+ it('returns a non-error found:false result naming the missing key when no flag matches, live or archived', async () => {
const request = vi.fn().mockResolvedValue({ results: [] })
const result = await tool.handler(createMockContext(request), { key: 'checkout' })
expect(result).toMatchObject({ found: false, key: 'checkout' })
expect((result as { message: string }).message).toContain('checkout')
- expect(request).toHaveBeenCalledTimes(1)
+ // The list hides archived flags by default, so a miss is confirmed against them too.
+ expect(request).toHaveBeenCalledTimes(2)
+ expect(request).toHaveBeenNthCalledWith(2, {
+ method: 'GET',
+ path: '/api/projects/42/feature_flags/',
+ query: { key: 'checkout', archived: true, limit: 20 },
+ })
+ })
+
+ it('finds an archived flag on the retry instead of reporting it missing', async () => {
+ const request = vi
+ .fn()
+ .mockResolvedValueOnce({ results: [] })
+ .mockResolvedValueOnce({ results: [{ ...flag(9, 'old-checkout'), archived: true }] })
+
+ const result = await tool.handler(createMockContext(request), { key: 'old-checkout' })
+
+ expect(result).toMatchObject({ id: 9, key: 'old-checkout', archived: true, found: true })
+ expect(request).toHaveBeenCalledTimes(2)
})
it('raises a validation error for a blank key without calling the API', async () => {
diff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.ts
index 4d30076695dd..5bbf03693738 100644
--- a/services/mcp/tests/unit/generate-tools.test.ts
+++ b/services/mcp/tests/unit/generate-tools.test.ts
@@ -2217,3 +2217,105 @@ describe('optional param with state fallback', () => {
expect(collapsed).toContain('.optional()).optional()')
})
})
+
+describe('composeToolSchema param aliases', () => {
+ const resolvedWithIdAndQuery = makeResolved({
+ path: '/api/projects/{project_id}/things/{id}/',
+ operation: {
+ operationId: 'things_retrieve',
+ parameters: [
+ { name: 'project_id', in: 'path', required: true, schema: { type: 'string' } },
+ { name: 'id', in: 'path', required: true, schema: { type: 'integer' } },
+ { name: 'thing_id', in: 'query', required: false, schema: { type: 'string' } },
+ ],
+ },
+ })
+
+ it('collects aliases that shadow nothing', () => {
+ const config: ToolConfig = {
+ operation: 'things_retrieve',
+ enabled: true,
+ param_overrides: { id: { aliases: ['thingId', 'thing_identifier'] } },
+ }
+
+ const result = composeToolSchema(config, resolvedWithIdAndQuery, makeSpec(), stubGetQuerySchema)
+
+ expect(result.paramAliases).toEqual({ id: ['thingId', 'thing_identifier'] })
+ })
+
+ // normalizeParamAliases deletes alias keys, so an alias that is also a real parameter
+ // would drop that parameter's value with no error at runtime. The generator is the only
+ // place that sees both the alias list and the operation's parameters.
+ it('rejects an alias that is also a declared parameter of the operation', () => {
+ const config: ToolConfig = {
+ operation: 'things_retrieve',
+ enabled: true,
+ param_overrides: { id: { aliases: ['thingId', 'thing_id'] } },
+ }
+
+ expect(() => composeToolSchema(config, resolvedWithIdAndQuery, makeSpec(), stubGetQuerySchema)).toThrow(
+ /alias "thing_id" for param "id" is also a declared parameter/
+ )
+ })
+
+ it('rejects an alias that collides with a body field, including one added by a later override', () => {
+ const withBody = makeResolved({
+ method: 'POST',
+ path: '/api/projects/{project_id}/things/{id}/',
+ operation: {
+ operationId: 'things_update',
+ parameters: [
+ { name: 'project_id', in: 'path', required: true, schema: { type: 'string' } },
+ { name: 'id', in: 'path', required: true, schema: { type: 'integer' } },
+ ],
+ requestBody: {
+ content: { 'application/json': { schema: { properties: { name: { type: 'string' } } } } },
+ },
+ },
+ })
+
+ const collidesWithBody: ToolConfig = {
+ operation: 'things_update',
+ enabled: true,
+ param_overrides: { id: { aliases: ['name'] } },
+ }
+ expect(() => composeToolSchema(collidesWithBody, withBody, makeSpec(), stubGetQuerySchema)).toThrow(
+ /alias "name" for param "id" is also a declared parameter/
+ )
+
+ // The alias override comes first in key order; the field it collides with is only
+ // added by the input_schema override after it, so the check must run after the loop.
+ const collidesWithLaterOverride: ToolConfig = {
+ operation: 'things_update',
+ enabled: true,
+ param_overrides: { id: { aliases: ['steps'] }, steps: { input_schema: 'StepsSchema' } },
+ }
+ expect(() => composeToolSchema(collidesWithLaterOverride, withBody, makeSpec(), stubGetQuerySchema)).toThrow(
+ /alias "steps" for param "id" is also a declared parameter/
+ )
+ })
+
+ it('rejects one alias claimed by two params', () => {
+ const config: ToolConfig = {
+ operation: 'things_retrieve',
+ enabled: true,
+ param_overrides: { id: { aliases: ['ref'] }, thing_id: { aliases: ['ref'] } },
+ }
+
+ expect(() => composeToolSchema(config, resolvedWithIdAndQuery, makeSpec(), stubGetQuerySchema)).toThrow(
+ /alias "ref" is declared by both "id" and "thing_id"/
+ )
+ })
+
+ it('rejects an alias equal to its own canonical name', () => {
+ const config: ToolConfig = {
+ operation: 'things_retrieve',
+ enabled: true,
+ param_overrides: { id: { aliases: ['id'] } },
+ }
+
+ expect(() => composeToolSchema(config, resolvedWithIdAndQuery, makeSpec(), stubGetQuerySchema)).toThrow(
+ /alias "id" for param "id"/
+ )
+ })
+})
diff --git a/services/mcp/tests/unit/schema.experiments.test.ts b/services/mcp/tests/unit/schema.experiments.test.ts
index e3decf842c4e..f413c80605fe 100644
--- a/services/mcp/tests/unit/schema.experiments.test.ts
+++ b/services/mcp/tests/unit/schema.experiments.test.ts
@@ -31,4 +31,74 @@ describe('Experiment exposure query schema', () => {
expect(parsed.exposure_criteria).toEqual(exposureCriteria)
})
+
+ // The backend defaults `kind` and accepts `properties` omitted on write, and API clients
+ // clear a config with an explicit null, so stored criteria carry all three shapes. A read
+ // schema stricter than the store fails every results read for those experiments.
+ it('accepts a stored exposure config without kind or properties, filling the backend defaults', () => {
+ const parsed = ExperimentExposureQuerySchema.parse({
+ kind: 'ExperimentExposureQuery',
+ experiment_id: 1,
+ experiment_name: 'test',
+ exposure_criteria: { exposure_config: { event: '$pageview' } },
+ })
+
+ expect(parsed.exposure_criteria?.exposure_config).toEqual({
+ kind: 'ExperimentEventExposureConfig',
+ event: '$pageview',
+ properties: [],
+ })
+ })
+
+ it('accepts a stored exposure config with null kind or properties, filling the backend defaults', () => {
+ const parsed = ExperimentExposureQuerySchema.parse({
+ kind: 'ExperimentExposureQuery',
+ experiment_id: 1,
+ experiment_name: 'test',
+ exposure_criteria: { exposure_config: { kind: null, event: '$pageview', properties: null } },
+ })
+
+ expect(parsed.exposure_criteria?.exposure_config).toEqual({
+ kind: 'ExperimentEventExposureConfig',
+ event: '$pageview',
+ properties: [],
+ })
+ })
+
+ it('accepts explicit null exposure and activation configs', () => {
+ const parsed = ExperimentExposureQuerySchema.parse({
+ kind: 'ExperimentExposureQuery',
+ experiment_id: 1,
+ experiment_name: 'test',
+ exposure_criteria: { exposure_config: null, activation_config: null, filterTestAccounts: false },
+ })
+
+ expect(parsed.exposure_criteria).toEqual({
+ exposure_config: null,
+ activation_config: null,
+ filterTestAccounts: false,
+ })
+ })
+
+ it('still routes an action-based config to the ActionsNode branch', () => {
+ const parsed = ExperimentExposureQuerySchema.parse({
+ kind: 'ExperimentExposureQuery',
+ experiment_id: 1,
+ experiment_name: 'test',
+ exposure_criteria: { exposure_config: { kind: 'ActionsNode', id: 5 } },
+ })
+
+ expect(parsed.exposure_criteria?.exposure_config).toEqual({ kind: 'ActionsNode', id: 5 })
+ })
+
+ it('still rejects an event config with no event', () => {
+ expect(
+ ExperimentExposureQuerySchema.safeParse({
+ kind: 'ExperimentExposureQuery',
+ experiment_id: 1,
+ experiment_name: 'test',
+ exposure_criteria: { exposure_config: { properties: [] } },
+ }).success
+ ).toBe(false)
+ })
})