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/mcp): enable experiment-copy-to-project tool (#63164)

Marcel Poelker8e667910374f
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index 41b335a72b9d..69dca7dfa123 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -598,6 +598,7 @@ class EnterpriseExperimentsViewSet(
)
@action(methods=["POST"], detail=True, url_path="copy_to_project", required_scopes=["experiment:write"])
def copy_to_project(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """Copy an experiment into another project in the same organization as a new draft."""
source_experiment: Experiment = self.get_object()
if experiment_has_legacy_metrics(source_experiment):
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index dc40650d8499..bb5e68fbfbcb 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -421,11 +421,7 @@ export const getExperimentsCopyToProjectCreateUrl = (projectId: string, id: numb
}
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
- *
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Copy an experiment into another project in the same organization as a new draft.
*/
export const experimentsCopyToProjectCreate = async (
projectId: string,
diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.ts
index f02702950e0b..62d1ec612c7c 100644
--- a/products/experiments/frontend/generated/api.zod.ts
+++ b/products/experiments/frontend/generated/api.zod.ts
@@ -139,11 +139,7 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
- *
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Copy an experiment into another project in the same organization as a new draft.
*/
export const ExperimentsCopyToProjectCreateBody = /* @__PURE__ */ zod.object({
target_team_id: zod.number().describe('The team ID to copy the experiment to.'),
diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yaml
index 733a4a542dc2..2a2159e2e360 100644
--- a/products/experiments/mcp/tools.yaml
+++ b/products/experiments/mcp/tools.yaml
@@ -48,6 +48,81 @@ tools:
id:
cast: string-int
ui_app: experiment
+ experiment-copy-to-project:
+ operation: experiments_copy_to_project_create
+ enabled: true
+ scopes:
+ - experiment:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Copy experiment to another 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.
+
+
+ REQUIRES 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.
+
+
+ Copies 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.
+
+
+ What 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.
+
+
+ What 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.
+
+
+ Feature 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 have at least 2 variants including one with key "control", otherwise the call returns 400
+ ("Feature flag must have at least 2 variants (control and at least one test variant)" or "Feature flag must
+ have a variant with key 'control'").
+
+
+ Returns 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.").
+
+
+ The returned experiment (including its id) belongs to the TARGET project, not the source project.
+ param_overrides:
+ id:
+ cast: string-int
+ target_team_id:
+ cast: string-int
+ response:
+ include:
+ - id
+ - name
+ - description
+ - type
+ - feature_flag_key
+ - status
+ - archived
+ - start_date
+ - end_date
+ - created_at
+ - parameters
+ - metrics
+ - metrics_secondary
+ - conclusion
+ - conclusion_comment
experiment-create:
operation: experiments_create
enabled: true
@@ -764,9 +839,6 @@ tools:
- metrics_secondary
- conclusion
- conclusion_comment
- experiments-copy-to-project-create:
- operation: experiments_copy_to_project_create
- enabled: false
experiments-create-exposure-cohort:
operation: experiments_create_exposure_cohort_for_experiment_create
enabled: false
diff --git a/products/experiments/skills/managing-experiment-lifecycle/SKILL.md b/products/experiments/skills/managing-experiment-lifecycle/SKILL.md
index e46e02f267ba..06e1d0b4d914 100644
--- a/products/experiments/skills/managing-experiment-lifecycle/SKILL.md
+++ b/products/experiments/skills/managing-experiment-lifecycle/SKILL.md
@@ -1,6 +1,6 @@
---
name: managing-experiment-lifecycle
-description: "Guides experiment state transitions: launching, pausing, resuming, ending, shipping variants, archiving, resetting, and duplicating. Covers preconditions, implications for variant assignment and analysis, and the decision framework for when to use each action.\nTRIGGER when: user asks to launch, pause, resume, end, ship, archive, reset, or duplicate an experiment.\nDO NOT TRIGGER when: user is creating an experiment (use creating-experiments), configuring rollout (use configuring-experiment-rollout), or setting up metrics (use configuring-experiment-analytics)."
+description: "Guides experiment state transitions: launching, pausing, resuming, ending, shipping variants, archiving, resetting, duplicating, and copying to another project. Covers preconditions, implications for variant assignment and analysis, and the decision framework for when to use each action.\nTRIGGER when: user asks to launch, pause, resume, end, ship, archive, reset, duplicate, or copy an experiment to another project.\nDO NOT TRIGGER when: user is creating an experiment (use creating-experiments), configuring rollout (use configuring-experiment-rollout), or setting up metrics (use configuring-experiment-analytics)."
---
# Managing experiment lifecycle
@@ -112,18 +112,43 @@ Creates a copy as a new draft with fresh dates and no results.
Optional: custom `name` (defaults to "Original Name (Copy)").
+### Copy to project (`experiment-copy-to-project`)
+
+Copies an experiment into a **different project in the same organization** as a new draft. Use this instead of
+`experiment-duplicate` when the copy should land in another project; use duplicate when it stays in the same project.
+
+- **Preconditions**: source must not use legacy metrics; target project must be in the same organization and you must
+ have write access to it. Cannot copy across organizations or regions.
+- **What's copied**: name, description, type, parameters, filters, primary/secondary metrics (fresh uuids), stats and
+ scheduling config, exposure criteria. **Not copied**: saved-metric references (project-scoped), holdout, exposure
+ cohort, dates, results, conclusion.
+- **Feature flag**: `target_team_id` is required; `feature_flag_key` is optional. The resolved key is then looked up
+ **in the target project**, and the lookup result — not whether you passed the key — decides what happens:
+ - **If `feature_flag_key` is omitted**: it defaults to the _source_ experiment's flag key. That key normally
+ doesn't exist in the target project, so a new flag with it is created there. (The default can still collide — see
+ the next point — so to be safe, pass an explicit key.)
+ - **If the resolved key already exists as a flag in the target project**: the copy **shares** that existing flag
+ instead of creating one. Both experiments then point at the same flag, so lifecycle ops (ship, pause) on either
+ affect both. The existing flag must have ≥2 variants including one keyed `control`, otherwise the call returns 400.
+ - **If the resolved key does not exist in the target project**: a new, independent flag is created with that key.
+ To guarantee independence, pass a `feature_flag_key` that doesn't already exist in the target.
+
+**Confirm the source experiment and target project by name before calling** — this writes into a project the user
+isn't looking at. The returned experiment (and its id) belongs to the target project.
+
## Decision framework
-| Situation | Action | Tool |
-| -------------------------------------------------- | ------------------------ | ------------------------- |
-| Draft ready, flag implemented, metrics set | Launch | `experiment-launch` |
-| Clear winner, significant results | Ship the winning variant | `experiment-ship-variant` |
-| No significant difference after sufficient time | End as inconclusive | `experiment-end` |
-| Something wrong, need to stop exposure temporarily | Pause | `experiment-pause` |
-| Resume after pause | Resume | `experiment-resume` |
-| Experiment ended, ready to clean up | Archive | `experiment-archive` |
-| Need to start over with same config | Reset to draft | `experiment-reset` |
-| Want a similar experiment with a fresh start | Duplicate | `experiment-duplicate` |
+| Situation | Action | Tool |
+| -------------------------------------------------- | ------------------------ | ---------------------------- |
+| Draft ready, flag implemented, metrics set | Launch | `experiment-launch` |
+| Clear winner, significant results | Ship the winning variant | `experiment-ship-variant` |
+| No significant difference after sufficient time | End as inconclusive | `experiment-end` |
+| Something wrong, need to stop exposure temporarily | Pause | `experiment-pause` |
+| Resume after pause | Resume | `experiment-resume` |
+| Experiment ended, ready to clean up | Archive | `experiment-archive` |
+| Need to start over with same config | Reset to draft | `experiment-reset` |
+| Want a similar experiment with a fresh start | Duplicate | `experiment-duplicate` |
+| Want the same experiment in a different project | Copy to another project | `experiment-copy-to-project` |
## Resolving experiments
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index b6b80b420640..b9e403f9ea3e 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1871,6 +1871,20 @@
"readOnlyHint": false
}
},
+ "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 have at least 2 variants including one with key \"control\", otherwise the call returns 400 (\"Feature flag must have at least 2 variants (control and at least one test variant)\" or \"Feature flag must have 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",
+ "feature": "experiments",
+ "summary": "Copy experiment to another project",
+ "title": "Copy experiment to another project",
+ "required_scopes": ["experiment:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"experiment-create": {
"description": "RULES (follow before calling):\n1. Load the creating-experiments skill for the full\n creation workflow.\n\n2. If the user mentions a rollout percentage (e.g. \"25%\"),\n load the configuring-experiment-rollout skill and\n ask the user to clarify BEFORE calling this tool.\n A percentage is always ambiguous — it can mean a\n variant split change OR an overall rollout change.\n\n3. Do NOT pass metrics on creation. Create the draft\n first, then add metrics via experiment-update. Use\n the configuring-experiment-analytics skill for\n metric guidance.\n\n\nCreates a new experiment in draft status (ignore the \"type\" param, since no-code/toolbar experiments must be created in the PostHog UI). Requires name and feature_flag_key. Feature flag is auto-created — do not create one separately. Defaults: 50/50 control/test, 100% rollout, Bayesian stats. Launch the experiment with the launch tool when ready.",
"category": "Experiments",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 3cf442437d88..b1db6db2ba6d 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2027,6 +2027,20 @@
"readOnlyHint": false
}
},
+ "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 have at least 2 variants including one with key \"control\", otherwise the call returns 400 (\"Feature flag must have at least 2 variants (control and at least one test variant)\" or \"Feature flag must have 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",
+ "feature": "experiments",
+ "summary": "Copy experiment to another project",
+ "title": "Copy experiment to another project",
+ "required_scopes": ["experiment:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"experiment-create": {
"description": "RULES (follow before calling):\n1. Load the creating-experiments skill for the full\n creation workflow.\n\n2. If the user mentions a rollout percentage (e.g. \"25%\"),\n load the configuring-experiment-rollout skill and\n ask the user to clarify BEFORE calling this tool.\n A percentage is always ambiguous — it can mean a\n variant split change OR an overall rollout change.\n\n3. Do NOT pass metrics on creation. Create the draft\n first, then add metrics via experiment-update. Use\n the configuring-experiment-analytics skill for\n metric guidance.\n\n\nCreates a new experiment in draft status (ignore the \"type\" param, since no-code/toolbar experiments must be created in the PostHog UI). Requires name and feature_flag_key. Feature flag is auto-created — do not create one separately. Defaults: 50/50 control/test, 100% rollout, Bayesian stats. Launch the experiment with the launch tool when ready.",
"category": "Experiments",
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index 85eec3ec6f26..62b0363cc988 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 21 enabled ops
+ * PostHog API - MCP 22 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -4772,6 +4772,24 @@ export const ExperimentsArchiveCreateParams = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Copy an experiment into another project in the same organization as a new draft.
+ */
+export const ExperimentsCopyToProjectCreateParams = /* @__PURE__ */ zod.object({
+ id: zod.number().describe('A unique integer value identifying this experiment.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const ExperimentsCopyToProjectCreateBody = /* @__PURE__ */ zod.object({
+ target_team_id: zod.number().describe('The team ID to copy the experiment to.'),
+ feature_flag_key: zod.string().optional().describe('Optional feature flag key to use in the destination team.'),
+ name: zod.string().optional().describe('Optional name for the copied experiment.'),
+})
+
/**
* Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
*
diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.ts
index 50a0a2b045ad..d6c986e75fb6 100644
--- a/services/mcp/src/tools/generated/experiments.ts
+++ b/services/mcp/src/tools/generated/experiments.ts
@@ -10,6 +10,8 @@ import {
ExperimentSavedMetricsPartialUpdateParams,
ExperimentSavedMetricsRetrieveParams,
ExperimentsArchiveCreateParams,
+ ExperimentsCopyToProjectCreateBody,
+ ExperimentsCopyToProjectCreateParams,
ExperimentsCreateBody,
ExperimentsDestroyParams,
ExperimentsDuplicateCreateBody,
@@ -53,6 +55,54 @@ const experimentArchive = (): ToolBase<typeof ExperimentArchiveSchema, WithPostH
},
})
+const ExperimentCopyToProjectSchema = 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<typeof ExperimentCopyToProjectSchema, Schemas.Experiment> => ({
+ name: 'experiment-copy-to-project',
+ schema: ExperimentCopyToProjectSchema,
+ handler: async (context: Context, params: z.infer<typeof ExperimentCopyToProjectSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.target_team_id !== undefined) {
+ body['target_team_id'] = params.target_team_id
+ }
+ if (params.feature_flag_key !== undefined) {
+ body['feature_flag_key'] = params.feature_flag_key
+ }
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ const result = await context.api.request<Schemas.Experiment>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/copy_to_project/`,
+ body,
+ })
+ const filtered = pickResponseFields(result, [
+ 'id',
+ 'name',
+ 'description',
+ 'type',
+ 'feature_flag_key',
+ 'status',
+ 'archived',
+ 'start_date',
+ 'end_date',
+ 'created_at',
+ 'parameters',
+ 'metrics',
+ 'metrics_secondary',
+ 'conclusion',
+ 'conclusion_comment',
+ ]) as typeof result
+ return filtered
+ },
+})
+
const ExperimentCreateSchema = ExperimentsCreateBody.omit({
start_date: true,
end_date: true,
@@ -761,6 +811,7 @@ const experimentUpdate = (): ToolBase<typeof ExperimentUpdateSchema, WithPostHog
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'experiment-archive': experimentArchive,
+ 'experiment-copy-to-project': experimentCopyToProject,
'experiment-create': experimentCreate,
'experiment-delete': experimentDelete,
'experiment-duplicate': experimentDuplicate,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-copy-to-project.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-copy-to-project.json
new file mode 100644
index 000000000000..56d793144d27
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-copy-to-project.json
@@ -0,0 +1,23 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "feature_flag_key": {
+ "description": "Optional feature flag key to use in the destination team.",
+ "type": "string"
+ },
+ "id": {
+ "description": "A unique integer value identifying this experiment.",
+ "type": "number"
+ },
+ "name": {
+ "description": "Optional name for the copied experiment.",
+ "type": "string"
+ },
+ "target_team_id": {
+ "description": "The team ID to copy the experiment to.",
+ "type": "number"
+ }
+ },
+ "required": ["id", "target_team_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/experiments-copy-to-project.test.ts b/services/mcp/tests/unit/experiments-copy-to-project.test.ts
new file mode 100644
index 000000000000..589fd346cc27
--- /dev/null
+++ b/services/mcp/tests/unit/experiments-copy-to-project.test.ts
@@ -0,0 +1,137 @@
+/**
+ * Tests for the generated `experiment-copy-to-project` tool.
+ *
+ * This tool POSTs to the experiments `copy_to_project` action, which copies an
+ * experiment into a different project in the same organization. The MCP layer
+ * adds two narrow string→int casts (`id` path param + `target_team_id` body
+ * param, both routinely passed stringified by agents) and forwards the body.
+ * These tests pin the schema shape, both casts, and the request the handler
+ * builds — drift the backend can't catch (its tests post raw dicts).
+ */
+import { describe, expect, it, vi } from 'vitest'
+import { z } from 'zod'
+
+import { GENERATED_TOOLS } from '@/tools/generated/experiments'
+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+
+const PROJECT_ID = '2'
+
+function getTool(): ToolBase<ZodObjectAny> {
+ return (GENERATED_TOOLS['experiment-copy-to-project'] as () => ToolBase<ZodObjectAny>)()
+}
+
+function getSchema(): z.ZodTypeAny {
+ return getTool().schema as z.ZodTypeAny
+}
+
+function parseWith(input: unknown): Record<string, unknown> {
+ return getSchema().parse(input) as Record<string, unknown>
+}
+
+function createMockContext(requestMock: ReturnType<typeof vi.fn>): Context {
+ return {
+ api: { request: requestMock } as any,
+ stateManager: { getProjectId: vi.fn().mockResolvedValue(PROJECT_ID) } as any,
+ env: {} as any,
+ sessionManager: {} as any,
+ cache: {} as any,
+ getDistinctId: async () => 'test-distinct-id',
+ trackEvent: async () => {},
+ }
+}
+
+describe('experiment-copy-to-project', () => {
+ it('is registered under the expected tool name', () => {
+ expect(getTool().name).toBe('experiment-copy-to-project')
+ })
+
+ describe('schema', () => {
+ it('requires target_team_id', () => {
+ expect(() => getSchema().parse({ id: 1, project_id: PROJECT_ID })).toThrow()
+ })
+
+ it('accepts a minimal input with only id + target_team_id', () => {
+ const parsed = parseWith({ id: 1, target_team_id: 5, project_id: PROJECT_ID })
+ expect(parsed.target_team_id).toBe(5)
+ // optional fields are absent, not coerced to undefined values
+ expect(parsed).not.toHaveProperty('feature_flag_key')
+ expect(parsed).not.toHaveProperty('name')
+ })
+
+ it('accepts optional feature_flag_key and name', () => {
+ const parsed = parseWith({
+ id: 1,
+ target_team_id: 5,
+ project_id: PROJECT_ID,
+ feature_flag_key: 'my-flag',
+ name: 'My copy',
+ })
+ expect(parsed.feature_flag_key).toBe('my-flag')
+ expect(parsed.name).toBe('My copy')
+ })
+ })
+
+ describe('casts', () => {
+ it('casts a stringified id', () => {
+ const parsed = parseWith({ id: '123', target_team_id: 5, project_id: PROJECT_ID })
+ expect(parsed.id).toBe(123)
+ expect(typeof parsed.id).toBe('number')
+ })
+
+ it('casts a stringified target_team_id', () => {
+ const parsed = parseWith({ id: 1, target_team_id: '42', project_id: PROJECT_ID })
+ expect(parsed.target_team_id).toBe(42)
+ expect(typeof parsed.target_team_id).toBe('number')
+ })
+
+ it.each([
+ ['boolean true', true],
+ ['null', null],
+ ['empty string', ''],
+ ['decimal string', '1.5'],
+ ['non-numeric string', 'abc'],
+ ] as const)('rejects unsafe target_team_id: %s', (_label, bad) => {
+ expect(() => getSchema().parse({ id: 1, target_team_id: bad, project_id: PROJECT_ID })).toThrow()
+ })
+ })
+
+ describe('handler', () => {
+ it('POSTs to the copy_to_project action with the cast ids and body fields', async () => {
+ const requestMock = vi.fn().mockResolvedValue({ id: 999, name: 'My copy' })
+ const context = createMockContext(requestMock)
+
+ await getTool().handler(
+ context,
+ parseWith({
+ id: '123',
+ target_team_id: '42',
+ project_id: PROJECT_ID,
+ feature_flag_key: 'my-flag',
+ name: 'My copy',
+ })
+ )
+
+ expect(requestMock).toHaveBeenCalledWith({
+ method: 'POST',
+ path: '/api/projects/2/experiments/123/copy_to_project/',
+ body: {
+ target_team_id: 42,
+ feature_flag_key: 'my-flag',
+ name: 'My copy',
+ },
+ })
+ })
+
+ it('omits feature_flag_key and name from the body when not provided', async () => {
+ const requestMock = vi.fn().mockResolvedValue({ id: 999 })
+ const context = createMockContext(requestMock)
+
+ await getTool().handler(context, parseWith({ id: 1, target_team_id: 5, project_id: PROJECT_ID }))
+
+ const body = requestMock.mock.calls[0]![0].body
+ expect(body).toEqual({ target_team_id: 5 })
+ expect(body).not.toHaveProperty('feature_flag_key')
+ expect(body).not.toHaveProperty('name')
+ })
+ })
+})
diff --git a/services/mcp/tests/unit/experiments-schema-cast.test.ts b/services/mcp/tests/unit/experiments-schema-cast.test.ts
index 8666314fb837..e30443708d40 100644
--- a/services/mcp/tests/unit/experiments-schema-cast.test.ts
+++ b/services/mcp/tests/unit/experiments-schema-cast.test.ts
@@ -48,6 +48,7 @@ function parseWith(schema: z.ZodTypeAny, input: unknown): Record<string, unknown
*/
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', {}],