:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(experiments): expose running-time calculator as an MCP tool (#64042)
Andersd6ea4779b911
diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex b6cd4e385a16..d4f4dfcb91e2 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -48,6 +48,38 @@ tools:id:cast: string-intui_app: experiment+ experiment-calculate-running-time:+ operation: experiments_calculate_running_time_create+ enabled: true+ scopes:+ - experiment:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Calculate experiment running time+ description: >+ Estimate the recommended sample size and how many days an experiment needs to run to detect an effect. This+ is a stateless statistical calculation — it does not read or modify any experiment, so it works for planning+ before an experiment exists.+++ Required: metric_type ('funnel' for conversion rates, 'mean_count' for events per user, 'mean_sum_or_avg'+ for summed property values per user, 'ratio' or 'retention' for ratio-style metrics) and+ minimum_detectable_effect (the smallest relative change to detect, as a percentage — e.g. 5 means a 5%+ lift). number_of_variants defaults to 2 (control + one test).+++ Provide the baseline one of two ways: pass baseline_value directly (a conversion rate as a fraction 0-1 for+ funnels, or an average per user for mean metrics), or pass baseline_stats (raw control-group statistics) and+ let the server derive it. Ratio and retention metrics REQUIRE baseline_stats (with denominator_sum /+ denominator_sum_squares / numerator_denominator_sum_product for the delta-method variance) or an explicit+ variance — baseline_value alone is not enough.+++ 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-copy-to-project:operation: experiments_copy_to_project_createenabled: true@@ -837,9 +869,6 @@ tools:- metrics_secondary- conclusion- conclusion_comment- experiments-calculate-running-time-create:- operation: experiments_calculate_running_time_create- enabled: falseexperiments-create-exposure-cohort:operation: experiments_create_exposure_cohort_for_experiment_createenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex f7998015abc2..a1e9b750e5e6 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -2582,6 +2582,20 @@"readOnlyHint": false}},+ "experiment-calculate-running-time": {+ "description": "Estimate the recommended sample size and how many days an experiment needs to run to detect an effect. This is a stateless statistical calculation — it does not read or modify any experiment, so it works for planning before an experiment exists.\n\nRequired: metric_type ('funnel' for conversion rates, 'mean_count' for events per user, 'mean_sum_or_avg' for summed property values per user, 'ratio' or 'retention' for ratio-style metrics) and minimum_detectable_effect (the smallest relative change to detect, as a percentage — e.g. 5 means a 5% lift). number_of_variants defaults to 2 (control + one test).\n\nProvide the baseline one of two ways: pass baseline_value directly (a conversion rate as a fraction 0-1 for funnels, or an average per user for mean metrics), or pass baseline_stats (raw control-group statistics) and let the server derive it. Ratio and retention metrics REQUIRE baseline_stats (with denominator_sum / denominator_sum_squares / numerator_denominator_sum_product for the delta-method variance) or an explicit variance — baseline_value alone is not enough.\n\nOptionally 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.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "Calculate experiment running time",+ "title": "Calculate experiment running time",+ "required_scopes": ["experiment:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"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",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 527483aee0f9..aa03148ea65c 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -2752,6 +2752,20 @@"readOnlyHint": false}},+ "experiment-calculate-running-time": {+ "description": "Estimate the recommended sample size and how many days an experiment needs to run to detect an effect. This is a stateless statistical calculation — it does not read or modify any experiment, so it works for planning before an experiment exists.\n\nRequired: metric_type ('funnel' for conversion rates, 'mean_count' for events per user, 'mean_sum_or_avg' for summed property values per user, 'ratio' or 'retention' for ratio-style metrics) and minimum_detectable_effect (the smallest relative change to detect, as a percentage — e.g. 5 means a 5% lift). number_of_variants defaults to 2 (control + one test).\n\nProvide the baseline one of two ways: pass baseline_value directly (a conversion rate as a fraction 0-1 for funnels, or an average per user for mean metrics), or pass baseline_stats (raw control-group statistics) and let the server derive it. Ratio and retention metrics REQUIRE baseline_stats (with denominator_sum / denominator_sum_squares / numerator_denominator_sum_product for the delta-method variance) or an explicit variance — baseline_value alone is not enough.\n\nOptionally 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.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "Calculate experiment running time",+ "title": "Calculate experiment running time",+ "required_scopes": ["experiment:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"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",diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.tsindex 000ba49c3b72..16699868440d 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 22 enabled ops+ * PostHog API - MCP 23 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -7527,6 +7527,114 @@ export const ExperimentsUnarchiveCreateParams = /* @__PURE__ */ zod.object({),})+/**+ * Estimate the recommended sample size and running time for an experiment.+ *+ * Pure statistical calculation — does not read or write any experiment. Pass the metric type, a+ * minimum detectable effect, and either a baseline value or raw baseline statistics. When+ * `exposure_rate_per_day` is provided, the response also includes the estimated running time in days.+ */+export const ExperimentsCalculateRunningTimeCreateParams = /* @__PURE__ */ zod.object({+ 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 experimentsCalculateRunningTimeCreateBodyMinimumDetectableEffectMin = 0++export const experimentsCalculateRunningTimeCreateBodyNumberOfVariantsDefault = 2+export const experimentsCalculateRunningTimeCreateBodyNumberOfVariantsMin = 2++export const experimentsCalculateRunningTimeCreateBodyExposureRatePerDayMin = 0++export const experimentsCalculateRunningTimeCreateBodyBaselineStatsOneNumberOfSamplesMin = 0++export const experimentsCalculateRunningTimeCreateBodyBaselineStatsOneSumSquaresDefault = 0++export const ExperimentsCalculateRunningTimeCreateBody = /* @__PURE__ */ zod+ .object({+ metric_type: zod+ .enum(['funnel', 'mean_count', 'mean_sum_or_avg', 'ratio', 'retention'])+ .describe(+ '* `funnel` - funnel\n* `mean_count` - mean_count\n* `mean_sum_or_avg` - mean_sum_or_avg\n* `ratio` - ratio\n* `retention` - retention'+ )+ .describe(+ "Metric type to size for. 'funnel' for conversion rates, 'mean_count' for event counts per user, 'mean_sum_or_avg' for summed property values per user, 'ratio' and 'retention' for ratio-style metrics (both require baseline_stats or an explicit variance).\n\n* `funnel` - funnel\n* `mean_count` - mean_count\n* `mean_sum_or_avg` - mean_sum_or_avg\n* `ratio` - ratio\n* `retention` - retention"+ ),+ minimum_detectable_effect: zod+ .number()+ .min(experimentsCalculateRunningTimeCreateBodyMinimumDetectableEffectMin)+ .describe('Smallest relative change to detect, as a percentage (e.g. 5 means a 5% lift). Must be > 0.'),+ number_of_variants: zod+ .number()+ .min(experimentsCalculateRunningTimeCreateBodyNumberOfVariantsMin)+ .default(experimentsCalculateRunningTimeCreateBodyNumberOfVariantsDefault)+ .describe('Total number of variants including control (default 2).'),+ exposure_rate_per_day: zod+ .number()+ .min(experimentsCalculateRunningTimeCreateBodyExposureRatePerDayMin)+ .nullish()+ .describe('Expected exposures per day. When provided, the response includes the recommended running time.'),+ baseline_value: zod+ .number()+ .nullish()+ .describe(+ 'Baseline metric value: conversion rate as a fraction 0-1 (funnel), average per user (mean), or the ratio (ratio/retention). Provide this or baseline_stats.'+ ),+ variance: zod+ .number()+ .nullish()+ .describe(+ 'Pre-computed variance for ratio/retention metrics. Provide this or baseline_stats when metric_type is ratio/retention and baseline_value is given directly.'+ ),+ baseline_stats: zod+ .union([+ zod+ .object({+ number_of_samples: zod+ .number()+ .min(experimentsCalculateRunningTimeCreateBodyBaselineStatsOneNumberOfSamplesMin)+ .describe('Number of control-group samples (users/units) observed.'),+ sum: zod+ .number()+ .describe(+ 'Sum of the metric values across the control group (for funnels, the numerator/conversions).'+ ),+ sum_squares: zod+ .number()+ .default(experimentsCalculateRunningTimeCreateBodyBaselineStatsOneSumSquaresDefault)+ .describe('Sum of squared metric values. Required for ratio/retention variance.'),+ denominator_sum: zod+ .number()+ .nullish()+ .describe('Sum of the denominator values. Required for ratio/retention metrics.'),+ denominator_sum_squares: zod+ .number()+ .nullish()+ .describe('Sum of squared denominator values (ratio/retention variance).'),+ numerator_denominator_sum_product: zod+ .number()+ .nullish()+ .describe(+ 'Sum of numerator×denominator products, used for the delta-method covariance term.'+ ),+ step_counts: zod+ .array(zod.number())+ .optional()+ .describe('Per-step counts for funnel metrics; the last entry is the final-step count.'),+ })+ .describe(+ 'Raw control-group statistics the calculator uses to derive a baseline value and variance.\n\nSupply this when you want the server to compute the baseline value and (for ratio/retention)\nthe delta-method variance, instead of passing `baseline_value`/`variance` directly.'+ ),+ zod.null(),+ ])+ .optional()+ .describe('Raw control-group statistics. When provided, the server derives baseline_value and variance.'),+ })+ .describe('Inputs for estimating the recommended sample size and running time of an 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.tsindex 766ff3471aa7..5955c721313c 100644--- a/services/mcp/src/tools/generated/experiments.ts+++ b/services/mcp/src/tools/generated/experiments.ts@@ -10,6 +10,7 @@ import {ExperimentSavedMetricsPartialUpdateParams,ExperimentSavedMetricsRetrieveParams,ExperimentsArchiveCreateParams,+ ExperimentsCalculateRunningTimeCreateBody,ExperimentsCopyToProjectCreateBody,ExperimentsCopyToProjectCreateParams,ExperimentsCreateBody,@@ -55,6 +56,47 @@ const experimentArchive = (): ToolBase<typeof ExperimentArchiveSchema, WithPostH},})+const ExperimentCalculateRunningTimeSchema = ExperimentsCalculateRunningTimeCreateBody++const experimentCalculateRunningTime = (): ToolBase<+ typeof ExperimentCalculateRunningTimeSchema,+ Schemas.RunningTimeCalculationResult+> => ({+ name: 'experiment-calculate-running-time',+ schema: ExperimentCalculateRunningTimeSchema,+ handler: async (context: Context, params: z.infer<typeof ExperimentCalculateRunningTimeSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.metric_type !== undefined) {+ body['metric_type'] = params.metric_type+ }+ if (params.minimum_detectable_effect !== undefined) {+ body['minimum_detectable_effect'] = params.minimum_detectable_effect+ }+ if (params.number_of_variants !== undefined) {+ body['number_of_variants'] = params.number_of_variants+ }+ if (params.exposure_rate_per_day !== undefined) {+ body['exposure_rate_per_day'] = params.exposure_rate_per_day+ }+ if (params.baseline_value !== undefined) {+ body['baseline_value'] = params.baseline_value+ }+ if (params.variance !== undefined) {+ body['variance'] = params.variance+ }+ if (params.baseline_stats !== undefined) {+ body['baseline_stats'] = params.baseline_stats+ }+ const result = await context.api.request<Schemas.RunningTimeCalculationResult>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/calculate_running_time/`,+ body,+ })+ return result+ },+})+const ExperimentCopyToProjectSchema = ExperimentsCopyToProjectCreateParams.omit({ project_id: true }).extend(ExperimentsCopyToProjectCreateBody.shape).extend({@@ -815,6 +857,7 @@ const experimentUpdate = (): ToolBase<typeof ExperimentUpdateSchema, WithPostHogexport const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'experiment-archive': experimentArchive,+ 'experiment-calculate-running-time': experimentCalculateRunningTime,'experiment-copy-to-project': experimentCopyToProject,'experiment-create': experimentCreate,'experiment-delete': experimentDelete,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-calculate-running-time.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-calculate-running-time.jsonnew file mode 100644index 000000000000..fa5a2ce6867e--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-calculate-running-time.json@@ -0,0 +1,127 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "description": "Inputs for estimating the recommended sample size and running time of an experiment.",+ "properties": {+ "baseline_stats": {+ "anyOf": [+ {+ "description": "Raw control-group statistics the calculator uses to derive a baseline value and variance.\n\nSupply this when you want the server to compute the baseline value and (for ratio/retention)\nthe delta-method variance, instead of passing `baseline_value`/`variance` directly.",+ "properties": {+ "denominator_sum": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Sum of the denominator values. Required for ratio/retention metrics."+ },+ "denominator_sum_squares": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Sum of squared denominator values (ratio/retention variance)."+ },+ "number_of_samples": {+ "description": "Number of control-group samples (users/units) observed.",+ "minimum": 0,+ "type": "number"+ },+ "numerator_denominator_sum_product": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Sum of numerator×denominator products, used for the delta-method covariance term."+ },+ "step_counts": {+ "description": "Per-step counts for funnel metrics; the last entry is the final-step count.",+ "items": {+ "type": "number"+ },+ "type": "array"+ },+ "sum": {+ "description": "Sum of the metric values across the control group (for funnels, the numerator/conversions).",+ "type": "number"+ },+ "sum_squares": {+ "default": 0,+ "description": "Sum of squared metric values. Required for ratio/retention variance.",+ "type": "number"+ }+ },+ "required": ["number_of_samples", "sum"],+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Raw control-group statistics. When provided, the server derives baseline_value and variance."+ },+ "baseline_value": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Baseline metric value: conversion rate as a fraction 0-1 (funnel), average per user (mean), or the ratio (ratio/retention). Provide this or baseline_stats."+ },+ "exposure_rate_per_day": {+ "anyOf": [+ {+ "minimum": 0,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Expected exposures per day. When provided, the response includes the recommended running time."+ },+ "metric_type": {+ "description": "Metric type to size for. 'funnel' for conversion rates, 'mean_count' for event counts per user, 'mean_sum_or_avg' for summed property values per user, 'ratio' and 'retention' for ratio-style metrics (both require baseline_stats or an explicit variance).\n\n* `funnel` - funnel\n* `mean_count` - mean_count\n* `mean_sum_or_avg` - mean_sum_or_avg\n* `ratio` - ratio\n* `retention` - retention",+ "enum": ["funnel", "mean_count", "mean_sum_or_avg", "ratio", "retention"],+ "type": "string"+ },+ "minimum_detectable_effect": {+ "description": "Smallest relative change to detect, as a percentage (e.g. 5 means a 5% lift). Must be > 0.",+ "minimum": 0,+ "type": "number"+ },+ "number_of_variants": {+ "default": 2,+ "description": "Total number of variants including control (default 2).",+ "minimum": 2,+ "type": "number"+ },+ "variance": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Pre-computed variance for ratio/retention metrics. Provide this or baseline_stats when metric_type is ratio/retention and baseline_value is given directly."+ }+ },+ "required": ["metric_type", "minimum_detectable_effect"],+ "type": "object"+}