Skip to content

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

feat(experiments): expose flag cleanup in the MCP tools (#86946)

Juraj Majerikd17a7e11c732
diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yaml
index f152e159b74a..76c479a1062c 100644
--- a/products/experiments/mcp/tools.yaml
+++ b/products/experiments/mcp/tools.yaml
@@ -100,6 +100,36 @@ tools:
Optionally pass exposure_rate_per_day (expected exposures per day across all variants) to also get
recommended_running_time_days. The response returns baseline_value, variance (null for funnels),
recommended_sample_size (total across variants), and recommended_running_time_days.
+ experiment-cleanup-task:
+ operation: experiments_flag_cleanup_task_retrieve
+ enabled: true
+ scopes:
+ - experiment:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get flag cleanup task status
+ description: >
+ Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the
+ user's reference first.
+
+
+ Status of the flag cleanup task opened when this experiment was ended or shipped with open_cleanup_pr=true.
+ Returns run_status, is_terminal, and pr_url: the draft pull request that removes the experiment's feature
+ flag code, null until the task opens it. A cleanup typically takes several minutes; poll until is_terminal
+ is true rather than assuming failure. A terminal run without a pr_url means the task found no flag
+ references to remove, or it failed.
+
+
+ Returns 404 when no cleanup task was opened for this experiment.
+ param_overrides:
+ id:
+ cast: string-int
+ feature_flag: experiment-flag-cleanup-pr
+ response:
+ exclude:
+ - can_view_task
experiment-copy-to-project:
operation: experiments_copy_to_project_create
enabled: true
@@ -379,9 +409,27 @@ tools:
Other options: use experiment-ship-variant to end AND roll out a winner. Use pause to temporarily deactivate
the flag without ending.
+
+
+ Optional flag cleanup: pass open_cleanup_pr=true to also open a draft pull request that removes the
+ experiment's feature flag code from the team's connected repository. Only offer this when the user asks for
+ it or confirms it. Track progress with experiment-cleanup-task.
+ exclude_params:
+ - set_repository_as_team_default
param_overrides:
id:
cast: string-int
+ open_cleanup_pr:
+ description: >
+ 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:
+ description: >
+ 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.
ui_app: experiment
experiment-freeze-exposure:
operation: experiments_freeze_exposure_create
@@ -1093,9 +1141,28 @@ tools:
Returns 400 if: experiment is in draft ("Experiment has not been launched yet."), variant_key not found on
the flag, or no linked feature flag. Returns 409 if an approval policy requires review before the flag
change takes effect — includes a change_request_id in the response.
+
+
+ Optional flag cleanup: pass open_cleanup_pr=true to also open a draft pull request that removes the
+ experiment's feature flag code, keeping the shipped variant's code path. Only offer this when the user asks
+ for it or confirms it. Track progress with experiment-cleanup-task.
+ exclude_params:
+ - set_repository_as_team_default
param_overrides:
id:
cast: string-int
+ open_cleanup_pr:
+ description: >
+ 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:
+ description: >
+ 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.
ui_app: experiment
experiment-stats:
operation: experiments_stats_retrieve
@@ -1341,9 +1408,6 @@ tools:
experiments-flag-cleanup-target-retrieve:
operation: experiments_flag_cleanup_target_retrieve
enabled: false
- experiments-flag-cleanup-task-retrieve:
- operation: experiments_flag_cleanup_task_retrieve
- enabled: false
experiments-recalculate-timeseries:
operation: experiments_recalculate_timeseries_create
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index f15721887f5e..00578d4894f8 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3864,6 +3864,21 @@
"readOnlyHint": true
}
},
+ "experiment-cleanup-task": {
+ "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first.\n\nStatus of the flag cleanup task opened when this experiment was ended or shipped with open_cleanup_pr=true. Returns run_status, is_terminal, and pr_url: the draft pull request that removes the experiment's feature flag code, null until the task opens it. A cleanup typically takes several minutes; poll until is_terminal is true rather than assuming failure. A terminal run without a pr_url means the task found no flag references to remove, or it failed.\n\nReturns 404 when no cleanup task was opened for this experiment.",
+ "category": "Experiments",
+ "feature": "experiments",
+ "summary": "Get flag cleanup task status",
+ "title": "Get flag cleanup task status",
+ "required_scopes": ["experiment:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "experiment-flag-cleanup-pr"
+ },
"experiment-copy-to-project": {
"description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nREQUIRES EXPLICIT USER CONFIRMATION BEFORE CALLING. This writes a new experiment into a DIFFERENT project than the one the user is currently looking at. Resolve the target project from the user's wording to a concrete team id, then confirm the source experiment and the target project by name before invoking.\n\nCopies an experiment into another project in the SAME organization as a new draft. The target project must belong to the same organization — this CANNOT copy across organizations or regions. Use experiment-duplicate instead when the copy should land in the same project.\n\nWhat IS copied: name (defaults to \"Original Name (Copy)\", de-duplicated with a numeric suffix if that name already exists in the target), description, type, parameters (variant split, rollout), filters, primary and secondary metrics (each with freshly regenerated uuids and preserved ordering), stats config, scheduling config, exposure criteria, and the only_count_matured_users setting.\n\nWhat is NOT copied: saved-metric references (saved metrics are project-scoped, so they are dropped on a cross-project copy), holdout, exposure cohort, start/end dates, results, and conclusion. The copy always starts as a fresh draft.\n\nFeature flag: pass feature_flag_key to control the flag key created in the target project. If omitted, the source experiment's flag key is reused — and if a flag with that key already exists in the target project, the copy SHARES that existing flag (its variants are reused) rather than creating a new one. A shared flag means lifecycle operations on either experiment (shipping a variant, pausing) affect both. To avoid this, pass a feature_flag_key that does not already exist in the target project. If an existing target flag is reused, it must be multivariate with 2 to 20 variants, otherwise the call returns 400 (\"Feature flag must have at least 2 variants (a baseline and at least one test variant)\" or \"Feature flag must have at most 20 variants\"). No specific variant key is required — the analysis baseline defaults to the variant keyed \"control\" when present, else the first variant. Exception: copying a web experiment requires the reused target flag to have a variant keyed \"control\", otherwise the call returns 400 (\"Web experiments require a variant with key 'control'\").\n\nReturns 400 if the source experiment uses legacy metrics (\"Copying is not supported for experiments using legacy metrics.\"). Returns 404 if the target project is not found in the organization (\"Target team not found.\"). Returns 403 if you lack write access to the target project (\"You do not have write access to the target project.\").\n\nThe returned experiment (including its id) belongs to the TARGET project, not the source project.",
"category": "Experiments",
@@ -3935,7 +3950,7 @@
}
},
"experiment-end": {
- "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nEnd a running experiment without shipping a variant. Sets end_date to now and transitions status to stopped. The feature flag is NOT modified — users continue seeing their assigned variants and exposure events continue to fire, but only data up to end_date is included in results.\n\nOptionally provide conclusion (\"won\", \"lost\", \"inconclusive\", \"stopped_early\", \"invalid\") and conclusion_comment.\n\nReturns 400 if the experiment is in draft (\"Experiment has not been launched yet.\") or already stopped (\"Experiment has already ended.\").\n\nOther options: use experiment-ship-variant to end AND roll out a winner. Use pause to temporarily deactivate the flag without ending.",
+ "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nEnd a running experiment without shipping a variant. Sets end_date to now and transitions status to stopped. The feature flag is NOT modified — users continue seeing their assigned variants and exposure events continue to fire, but only data up to end_date is included in results.\n\nOptionally provide conclusion (\"won\", \"lost\", \"inconclusive\", \"stopped_early\", \"invalid\") and conclusion_comment.\n\nReturns 400 if the experiment is in draft (\"Experiment has not been launched yet.\") or already stopped (\"Experiment has already ended.\").\n\nOther options: use experiment-ship-variant to end AND roll out a winner. Use pause to temporarily deactivate the flag without ending.\n\nOptional flag cleanup: pass open_cleanup_pr=true to also open a draft pull request that removes the experiment's feature flag code from the team's connected repository. Only offer this when the user asks for it or confirms it. Track progress with experiment-cleanup-task.",
"category": "Experiments",
"feature": "experiments",
"summary": "End experiment",
@@ -4243,7 +4258,7 @@
}
},
"experiment-ship-variant": {
- "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nREQUIRES EXPLICIT USER CONFIRMATION BEFORE CALLING. This permanently rewrites the linked feature flag and cannot be undone via the API. Two release modes — confirm which one the user wants before invoking:\n\n- Default (release_to_everyone=false): updates only the variant distribution so the selected variant gets 100%. Existing release conditions and per-user variant overrides on the flag are preserved untouched — the variant is served only to users who already match them.\n\n- release_to_everyone=true: in addition to flipping the variant distribution, prepends a catch-all release condition that rolls the variant out to 100% of users. This OVERRIDES any existing release conditions and per-user variant overrides on the flag. Only use this when the user explicitly wants to release beyond the experiment's existing population.\n\nEven when the user has asked you to ship a specific variant, ask them to confirm with the variant key, target experiment, and release mode before invoking this tool.\n\nShip a variant to 100% of users by rewriting the feature flag. Requires variant_key — the key of the variant to ship (e.g. \"test\" or \"control\"). The flag is rewritten so the selected variant gets 100% rollout via a new catch-all release group prepended to existing groups (preserved for rollback).\n\nCan be called on both running and stopped experiments. If the experiment is still running, it is also ended (end_date set, status becomes stopped). If already stopped, only the flag is rewritten — supports the \"end first, ship later\" workflow.\n\nOptionally provide conclusion (\"won\", \"lost\", \"inconclusive\", \"stopped_early\", \"invalid\") and conclusion_comment.\n\nReturns 400 if: experiment is in draft (\"Experiment has not been launched yet.\"), variant_key not found on the flag, or no linked feature flag. Returns 409 if an approval policy requires review before the flag change takes effect — includes a change_request_id in the response.",
+ "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nREQUIRES EXPLICIT USER CONFIRMATION BEFORE CALLING. This permanently rewrites the linked feature flag and cannot be undone via the API. Two release modes — confirm which one the user wants before invoking:\n\n- Default (release_to_everyone=false): updates only the variant distribution so the selected variant gets 100%. Existing release conditions and per-user variant overrides on the flag are preserved untouched — the variant is served only to users who already match them.\n\n- release_to_everyone=true: in addition to flipping the variant distribution, prepends a catch-all release condition that rolls the variant out to 100% of users. This OVERRIDES any existing release conditions and per-user variant overrides on the flag. Only use this when the user explicitly wants to release beyond the experiment's existing population.\n\nEven when the user has asked you to ship a specific variant, ask them to confirm with the variant key, target experiment, and release mode before invoking this tool.\n\nShip a variant to 100% of users by rewriting the feature flag. Requires variant_key — the key of the variant to ship (e.g. \"test\" or \"control\"). The flag is rewritten so the selected variant gets 100% rollout via a new catch-all release group prepended to existing groups (preserved for rollback).\n\nCan be called on both running and stopped experiments. If the experiment is still running, it is also ended (end_date set, status becomes stopped). If already stopped, only the flag is rewritten — supports the \"end first, ship later\" workflow.\n\nOptionally provide conclusion (\"won\", \"lost\", \"inconclusive\", \"stopped_early\", \"invalid\") and conclusion_comment.\n\nReturns 400 if: experiment is in draft (\"Experiment has not been launched yet.\"), variant_key not found on the flag, or no linked feature flag. Returns 409 if an approval policy requires review before the flag change takes effect — includes a change_request_id in the response.\n\nOptional flag cleanup: pass open_cleanup_pr=true to also open a draft pull request that removes the experiment's feature flag code, keeping the shipped variant's code path. Only offer this when the user asks for it or confirms it. Track progress with experiment-cleanup-task.",
"category": "Experiments",
"feature": "experiments",
"summary": "Ship experiment variant",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 66b6c5d0dc7f..dd8d3b69e450 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3921,6 +3921,21 @@
"readOnlyHint": true
}
},
+ "experiment-cleanup-task": {
+ "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first.\n\nStatus of the flag cleanup task opened when this experiment was ended or shipped with open_cleanup_pr=true. Returns run_status, is_terminal, and pr_url: the draft pull request that removes the experiment's feature flag code, null until the task opens it. A cleanup typically takes several minutes; poll until is_terminal is true rather than assuming failure. A terminal run without a pr_url means the task found no flag references to remove, or it failed.\n\nReturns 404 when no cleanup task was opened for this experiment.",
+ "category": "Experiments",
+ "feature": "experiments",
+ "summary": "Get flag cleanup task status",
+ "title": "Get flag cleanup task status",
+ "required_scopes": ["experiment:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "experiment-flag-cleanup-pr"
+ },
"experiment-copy-to-project": {
"description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nREQUIRES EXPLICIT USER CONFIRMATION BEFORE CALLING. This writes a new experiment into a DIFFERENT project than the one the user is currently looking at. Resolve the target project from the user's wording to a concrete team id, then confirm the source experiment and the target project by name before invoking.\n\nCopies an experiment into another project in the SAME organization as a new draft. The target project must belong to the same organization — this CANNOT copy across organizations or regions. Use experiment-duplicate instead when the copy should land in the same project.\n\nWhat IS copied: name (defaults to \"Original Name (Copy)\", de-duplicated with a numeric suffix if that name already exists in the target), description, type, parameters (variant split, rollout), filters, primary and secondary metrics (each with freshly regenerated uuids and preserved ordering), stats config, scheduling config, exposure criteria, and the only_count_matured_users setting.\n\nWhat is NOT copied: saved-metric references (saved metrics are project-scoped, so they are dropped on a cross-project copy), holdout, exposure cohort, start/end dates, results, and conclusion. The copy always starts as a fresh draft.\n\nFeature flag: pass feature_flag_key to control the flag key created in the target project. If omitted, the source experiment's flag key is reused — and if a flag with that key already exists in the target project, the copy SHARES that existing flag (its variants are reused) rather than creating a new one. A shared flag means lifecycle operations on either experiment (shipping a variant, pausing) affect both. To avoid this, pass a feature_flag_key that does not already exist in the target project. If an existing target flag is reused, it must be multivariate with 2 to 20 variants, otherwise the call returns 400 (\"Feature flag must have at least 2 variants (a baseline and at least one test variant)\" or \"Feature flag must have at most 20 variants\"). No specific variant key is required — the analysis baseline defaults to the variant keyed \"control\" when present, else the first variant. Exception: copying a web experiment requires the reused target flag to have a variant keyed \"control\", otherwise the call returns 400 (\"Web experiments require a variant with key 'control'\").\n\nReturns 400 if the source experiment uses legacy metrics (\"Copying is not supported for experiments using legacy metrics.\"). Returns 404 if the target project is not found in the organization (\"Target team not found.\"). Returns 403 if you lack write access to the target project (\"You do not have write access to the target project.\").\n\nThe returned experiment (including its id) belongs to the TARGET project, not the source project.",
"category": "Experiments",
@@ -3992,7 +4007,7 @@
}
},
"experiment-end": {
- "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nEnd a running experiment without shipping a variant. Sets end_date to now and transitions status to stopped. The feature flag is NOT modified — users continue seeing their assigned variants and exposure events continue to fire, but only data up to end_date is included in results.\n\nOptionally provide conclusion (\"won\", \"lost\", \"inconclusive\", \"stopped_early\", \"invalid\") and conclusion_comment.\n\nReturns 400 if the experiment is in draft (\"Experiment has not been launched yet.\") or already stopped (\"Experiment has already ended.\").\n\nOther options: use experiment-ship-variant to end AND roll out a winner. Use pause to temporarily deactivate the flag without ending.",
+ "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nEnd a running experiment without shipping a variant. Sets end_date to now and transitions status to stopped. The feature flag is NOT modified — users continue seeing their assigned variants and exposure events continue to fire, but only data up to end_date is included in results.\n\nOptionally provide conclusion (\"won\", \"lost\", \"inconclusive\", \"stopped_early\", \"invalid\") and conclusion_comment.\n\nReturns 400 if the experiment is in draft (\"Experiment has not been launched yet.\") or already stopped (\"Experiment has already ended.\").\n\nOther options: use experiment-ship-variant to end AND roll out a winner. Use pause to temporarily deactivate the flag without ending.\n\nOptional flag cleanup: pass open_cleanup_pr=true to also open a draft pull request that removes the experiment's feature flag code from the team's connected repository. Only offer this when the user asks for it or confirms it. Track progress with experiment-cleanup-task.",
"category": "Experiments",
"feature": "experiments",
"summary": "End experiment",
@@ -4328,7 +4343,7 @@
}
},
"experiment-ship-variant": {
- "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nREQUIRES EXPLICIT USER CONFIRMATION BEFORE CALLING. This permanently rewrites the linked feature flag and cannot be undone via the API. Two release modes — confirm which one the user wants before invoking:\n\n- Default (release_to_everyone=false): updates only the variant distribution so the selected variant gets 100%. Existing release conditions and per-user variant overrides on the flag are preserved untouched — the variant is served only to users who already match them.\n\n- release_to_everyone=true: in addition to flipping the variant distribution, prepends a catch-all release condition that rolls the variant out to 100% of users. This OVERRIDES any existing release conditions and per-user variant overrides on the flag. Only use this when the user explicitly wants to release beyond the experiment's existing population.\n\nEven when the user has asked you to ship a specific variant, ask them to confirm with the variant key, target experiment, and release mode before invoking this tool.\n\nShip a variant to 100% of users by rewriting the feature flag. Requires variant_key — the key of the variant to ship (e.g. \"test\" or \"control\"). The flag is rewritten so the selected variant gets 100% rollout via a new catch-all release group prepended to existing groups (preserved for rollback).\n\nCan be called on both running and stopped experiments. If the experiment is still running, it is also ended (end_date set, status becomes stopped). If already stopped, only the flag is rewritten — supports the \"end first, ship later\" workflow.\n\nOptionally provide conclusion (\"won\", \"lost\", \"inconclusive\", \"stopped_early\", \"invalid\") and conclusion_comment.\n\nReturns 400 if: experiment is in draft (\"Experiment has not been launched yet.\"), variant_key not found on the flag, or no linked feature flag. Returns 409 if an approval policy requires review before the flag change takes effect — includes a change_request_id in the response.",
+ "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nREQUIRES EXPLICIT USER CONFIRMATION BEFORE CALLING. This permanently rewrites the linked feature flag and cannot be undone via the API. Two release modes — confirm which one the user wants before invoking:\n\n- Default (release_to_everyone=false): updates only the variant distribution so the selected variant gets 100%. Existing release conditions and per-user variant overrides on the flag are preserved untouched — the variant is served only to users who already match them.\n\n- release_to_everyone=true: in addition to flipping the variant distribution, prepends a catch-all release condition that rolls the variant out to 100% of users. This OVERRIDES any existing release conditions and per-user variant overrides on the flag. Only use this when the user explicitly wants to release beyond the experiment's existing population.\n\nEven when the user has asked you to ship a specific variant, ask them to confirm with the variant key, target experiment, and release mode before invoking this tool.\n\nShip a variant to 100% of users by rewriting the feature flag. Requires variant_key — the key of the variant to ship (e.g. \"test\" or \"control\"). The flag is rewritten so the selected variant gets 100% rollout via a new catch-all release group prepended to existing groups (preserved for rollback).\n\nCan be called on both running and stopped experiments. If the experiment is still running, it is also ended (end_date set, status becomes stopped). If already stopped, only the flag is rewritten — supports the \"end first, ship later\" workflow.\n\nOptionally provide conclusion (\"won\", \"lost\", \"inconclusive\", \"stopped_early\", \"invalid\") and conclusion_comment.\n\nReturns 400 if: experiment is in draft (\"Experiment has not been launched yet.\"), variant_key not found on the flag, or no linked feature flag. Returns 409 if an approval policy requires review before the flag change takes effect — includes a change_request_id in the response.\n\nOptional flag cleanup: pass open_cleanup_pr=true to also open a draft pull request that removes the experiment's feature flag code, keeping the shipped variant's code path. Only offer this when the user asks for it or confirms it. Track progress with experiment-cleanup-task.",
"category": "Experiments",
"feature": "experiments",
"summary": "Ship experiment variant",
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index 3c7e05315536..e2d8e5d9b495 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 37 enabled ops
+ * PostHog API - MCP 38 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -18496,8 +18496,6 @@ export const experimentsEndCreateBodyConclusionCommentMax = 4000
export const experimentsEndCreateBodyOpenCleanupPrDefault = false
export const experimentsEndCreateBodyRepositoryMax = 255
-export const experimentsEndCreateBodySetRepositoryAsTeamDefaultDefault = false
-
export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({
conclusion: zod
.union([
@@ -18530,11 +18528,22 @@ export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({
.describe(
"GitHub repository to open the cleanup pull request in, in `organization\/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository, the team's default cleanup repository, or the team's only connected repository is used."
),
- set_repository_as_team_default: zod
- .boolean()
- .default(experimentsEndCreateBodySetRepositoryAsTeamDefaultDefault)
+})
+
+/**
+ * Status of the flag-cleanup Desktop task opened for this experiment.
+ *
+ * When an experiment was ended or shipped with open_cleanup_pr=true, a Desktop task
+ * removes the experiment's feature-flag code and opens a draft pull request. This
+ * returns that task's latest run status and the PR URL once one is opened. Poll
+ * until is_terminal is true. Returns 404 when no cleanup task was opened.
+ */
+export const ExperimentsFlagCleanupTaskRetrieveParams = /* @__PURE__ */ zod.object({
+ id: zod.number().describe('A unique integer value identifying this experiment.'),
+ project_id: zod
+ .string()
.describe(
- "When true, also save `repository` as this environment's default cleanup repository, used for experiments that have no repository of their own. Only acts when open_cleanup_pr is true and `repository` is provided and belongs to the team's GitHub installation. Requires project admin access (403 otherwise)."
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
),
})
@@ -18757,7 +18766,6 @@ export const experimentsShipVariantCreateBodyConclusionCommentMax = 4000
export const experimentsShipVariantCreateBodyOpenCleanupPrDefault = false
export const experimentsShipVariantCreateBodyRepositoryMax = 255
-export const experimentsShipVariantCreateBodySetRepositoryAsTeamDefaultDefault = false
export const experimentsShipVariantCreateBodyReleaseToEveryoneDefault = false
export const ExperimentsShipVariantCreateBody = /* @__PURE__ */ zod.object({
@@ -18792,12 +18800,6 @@ export const ExperimentsShipVariantCreateBody = /* @__PURE__ */ zod.object({
.describe(
"GitHub repository to open the cleanup pull request in, in `organization\/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository, the team's default cleanup repository, or the team's only connected repository is used."
),
- set_repository_as_team_default: zod
- .boolean()
- .default(experimentsShipVariantCreateBodySetRepositoryAsTeamDefaultDefault)
- .describe(
- "When true, also save `repository` as this environment's default cleanup repository, used for experiments that have no repository of their own. Only acts when open_cleanup_pr is true and `repository` is provided and belongs to the team's GitHub installation. Requires project admin access (403 otherwise)."
- ),
variant_key: zod.string().describe('The key of the variant to ship.'),
release_to_everyone: zod
.boolean()
diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.ts
index b81bb2b8c7a6..66655ee410af 100644
--- a/services/mcp/src/tools/generated/experiments.ts
+++ b/services/mcp/src/tools/generated/experiments.ts
@@ -29,6 +29,7 @@ import {
ExperimentsDuplicateCreateParams,
ExperimentsEndCreateBody,
ExperimentsEndCreateParams,
+ ExperimentsFlagCleanupTaskRetrieveParams,
ExperimentsFreezeExposureCreateParams,
ExperimentsLaunchCreateParams,
ExperimentsListQueryParams,
@@ -55,8 +56,8 @@ import { SavedMetricsAttachSchema } from '@/schema/tool-inputs'
import { castStringToInt } from '@/tools/cast-helpers'
import {
withPostHogUrl,
- pickResponseFields,
omitResponseFields,
+ pickResponseFields,
withInformationalResponse,
type WithPostHogUrl,
type WithInformationalResponse,
@@ -148,6 +149,24 @@ const experimentCalculateRunningTime = (): ToolBase<
},
})
+const ExperimentCleanupTaskSchema = ExperimentsFlagCleanupTaskRetrieveParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsFlagCleanupTaskRetrieveParams.shape['id']),
+})
+
+const experimentCleanupTask = (): ToolBase<typeof ExperimentCleanupTaskSchema, Schemas.ExperimentFlagCleanupTask> => ({
+ name: 'experiment-cleanup-task',
+ schema: ExperimentCleanupTaskSchema,
+ handler: async (context: Context, params: z.infer<typeof ExperimentCleanupTaskSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.ExperimentFlagCleanupTask>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/flag_cleanup_task/`,
+ })
+ const filtered = omitResponseFields(result, ['can_view_task']) as typeof result
+ return filtered
+ },
+})
+
const ExperimentCopyToProjectSchema = ExperimentsCopyToProjectCreateParams.omit({ project_id: true })
.extend(ExperimentsCopyToProjectCreateBody.shape)
.extend({
@@ -420,7 +439,15 @@ const experimentDuplicate = (): ToolBase<typeof ExperimentDuplicateSchema, unkno
const ExperimentEndSchema = ExperimentsEndCreateParams.omit({ project_id: true })
.extend(ExperimentsEndCreateBody.shape)
- .extend({ id: z.preprocess(castStringToInt, ExperimentsEndCreateParams.shape['id']) })
+ .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<typeof ExperimentEndSchema, WithPostHogUrl<Schemas.Experiment>> =>
withUiApp('experiment', {
@@ -441,9 +468,6 @@ const experimentEnd = (): ToolBase<typeof ExperimentEndSchema, WithPostHogUrl<Sc
if (params.repository !== undefined) {
body['repository'] = params.repository
}
- if (params.set_repository_as_team_default !== undefined) {
- body['set_repository_as_team_default'] = params.set_repository_as_team_default
- }
const result = await context.api.request<Schemas.Experiment>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/end/`,
@@ -1025,7 +1049,15 @@ const experimentSavedMetricsRetrieve = (): ToolBase<
const ExperimentShipVariantSchema = ExperimentsShipVariantCreateParams.omit({ project_id: true })
.extend(ExperimentsShipVariantCreateBody.shape)
- .extend({ id: z.preprocess(castStringToInt, ExperimentsShipVariantCreateParams.shape['id']) })
+ .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<typeof ExperimentShipVariantSchema, WithPostHogUrl<Schemas.Experiment>> =>
withUiApp('experiment', {
@@ -1046,9 +1078,6 @@ const experimentShipVariant = (): ToolBase<typeof ExperimentShipVariantSchema, W
if (params.repository !== undefined) {
body['repository'] = params.repository
}
- if (params.set_repository_as_team_default !== undefined) {
- body['set_repository_as_team_default'] = params.set_repository_as_team_default
- }
if (params.variant_key !== undefined) {
body['variant_key'] = params.variant_key
}
@@ -1297,6 +1326,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'experiment-activity': experimentActivity,
'experiment-archive': experimentArchive,
'experiment-calculate-running-time': experimentCalculateRunningTime,
+ 'experiment-cleanup-task': experimentCleanupTask,
'experiment-copy-to-project': experimentCopyToProject,
'experiment-create': experimentCreate,
'experiment-create-from-prompt': experimentCreateFromPrompt,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-end.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-end.json
index b61187163726..35497a8a7485 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-end.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-end.json
@@ -32,7 +32,7 @@
},
"open_cleanup_pr": {
"default": false,
- "description": "When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Desktop (403 otherwise). Only acts for allowlisted teams; ignored otherwise.",
+ "description": "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.",
"type": "boolean"
},
"repository": {
@@ -45,12 +45,7 @@
"type": "null"
}
],
- "description": "GitHub repository to open the cleanup pull request in, in `organization/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository, the team's default cleanup repository, or the team's only connected repository is used."
- },
- "set_repository_as_team_default": {
- "default": false,
- "description": "When true, also save `repository` as this environment's default cleanup repository, used for experiments that have no repository of their own. Only acts when open_cleanup_pr is true and `repository` is provided and belongs to the team's GitHub installation. Requires project admin access (403 otherwise).",
- "type": "boolean"
+ "description": "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."
}
},
"required": ["id"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-ship-variant.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-ship-variant.json
index 18d3a73cb0a8..9e5806a95179 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-ship-variant.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-ship-variant.json
@@ -32,7 +32,7 @@
},
"open_cleanup_pr": {
"default": false,
- "description": "When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Desktop (403 otherwise). Only acts for allowlisted teams; ignored otherwise.",
+ "description": "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.",
"type": "boolean"
},
"release_to_everyone": {
@@ -50,12 +50,7 @@
"type": "null"
}
],
- "description": "GitHub repository to open the cleanup pull request in, in `organization/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository, the team's default cleanup repository, or the team's only connected repository is used."
- },
- "set_repository_as_team_default": {
- "default": false,
- "description": "When true, also save `repository` as this environment's default cleanup repository, used for experiments that have no repository of their own. Only acts when open_cleanup_pr is true and `repository` is provided and belongs to the team's GitHub installation. Requires project admin access (403 otherwise).",
- "type": "boolean"
+ "description": "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."
},
"variant_key": {
"description": "The key of the variant to ship.",
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index c2940a66d58d..6388624b077a 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
-import { OAUTH_SCOPES_HIDDEN, OAUTH_SCOPES_SUPPORTED } from '@/lib/constants'
import { hasScope } from '@/lib/api'
+import { OAUTH_SCOPES_HIDDEN, OAUTH_SCOPES_SUPPORTED } from '@/lib/constants'
import type { EvaluatedFlags } from '@/lib/posthog/flags'
import { SessionManager } from '@/lib/SessionManager'
import { getToolsFromContext } from '@/tools'
@@ -889,12 +889,13 @@ describe('Tool Filtering - Feature Flags', () => {
'streamlit-apps',
'posthog-connect',
'experiment-behavior-comparison',
+ 'experiment-flag-cleanup-pr',
'data-warehouse-scene',
'data-quality-checks',
'context-layer',
])
)
- expect(flags).toHaveLength(33)
+ expect(flags).toHaveLength(34)
})
it('every loops tool is gated on the loops flag', () => {