: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): recalculation workflow MCP tools (#73418)
Rodrigo Iloroa09e12d1e726
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex f9c018df1925..1055cc8b2275 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -1087,6 +1087,7 @@ export interface eventUsageLogicActions {succeeded?: numbertotal_metrics?: numbertrigger?:+ | 'agent_mcp'| 'auto_refresh'| 'cold_run'| 'config_change'@@ -1107,6 +1108,7 @@ export interface eventUsageLogicActions {succeeded?: number | undefinedtotal_metrics?: number | undefinedtrigger?:+ | 'agent_mcp'| 'auto_refresh'| 'cold_run'| 'config_change'@@ -2441,6 +2443,7 @@ export const eventUsageLogic = kea<eventUsageLogicType>([| 'experiment_launch'| 'experiment_stop'| 'experiment_update'+ | 'agent_mcp'is_existing?: booleantotal_metrics?: numbersucceeded?: numberdiff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.tsindex 43bacc152cc5..7aabfba1064f 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts@@ -7,8 +7,10 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { projectLogic } from 'scenes/projectLogic'+import type { FeatureFlagsSet } from '~/lib/logic/featureFlagLogic'import type { Breakdown, CachedNewExperimentQueryResponse, ExperimentMetric } from '~/queries/schema/schema-general'import { Experiment } from '~/types'+import type { ExperimentIdType } from '~/types'import {experimentsMetricsRecalculationCreate,@@ -20,8 +22,6 @@ import type {TriggerEnumApi,} from 'products/experiments/frontend/generated/api.schemas'-import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'-import type { ExperimentIdType } from '../../types'import { isLaunched } from './experimentsLogic'type ExperimentSavedMetric = {@@ -196,6 +196,7 @@ export interface experimentMetricsLogicActions {succeeded?: numbertotal_metrics?: numbertrigger?:+ | 'agent_mcp'| 'auto_refresh'| 'cold_run'| 'config_change'@@ -216,6 +217,7 @@ export interface experimentMetricsLogicActions {succeeded?: number | undefinedtotal_metrics?: number | undefinedtrigger?:+ | 'agent_mcp'| 'auto_refresh'| 'cold_run'| 'config_change'diff --git a/products/experiments/backend/migrations/0030_alter_experimentmetricsrecalculation_trigger.py b/products/experiments/backend/migrations/0030_alter_experimentmetricsrecalculation_trigger.pynew file mode 100644index 000000000000..b8216e352624--- /dev/null+++ b/products/experiments/backend/migrations/0030_alter_experimentmetricsrecalculation_trigger.py@@ -0,0 +1,31 @@+# Generated by Django 5.2.14 on 2026-07-24 20:12++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("experiments", "0029_experiment_repository"),+ ]++ operations = [+ migrations.AlterField(+ model_name="experimentmetricsrecalculation",+ name="trigger",+ field=models.CharField(+ choices=[+ ("manual", "Manual"),+ ("agent_mcp", "Agent (MCP)"),+ ("cold_run", "Cold Run"),+ ("stale_refresh", "Stale Refresh"),+ ("auto_refresh", "Auto Refresh"),+ ("config_change", "Config Change"),+ ("experiment_launch", "Experiment Launch"),+ ("experiment_stop", "Experiment Stop"),+ ("experiment_update", "Experiment Update"),+ ],+ default="manual",+ max_length=30,+ ),+ ),+ ]diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txtindex 1a4311f39a7b..b729a1fcfb00 100644--- a/products/experiments/backend/migrations/max_migration.txt+++ b/products/experiments/backend/migrations/max_migration.txt@@ -1 +1 @@-0029_experiment_repository+0030_alter_experimentmetricsrecalculation_triggerdiff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.pyindex 8bd88129fc75..145ff2c0fff1 100644--- a/products/experiments/backend/models/experiment.py+++ b/products/experiments/backend/models/experiment.py@@ -503,6 +503,7 @@ class ExperimentMetricsRecalculation(TeamScopedRootMixin, UUIDModel):class Trigger(models.TextChoices):MANUAL = "manual", "Manual"+ AGENT_MCP = "agent_mcp", "Agent (MCP)"COLD_RUN = "cold_run", "Cold Run"STALE_REFRESH = "stale_refresh", "Stale Refresh"AUTO_REFRESH = "auto_refresh", "Auto Refresh"diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex 644a49cafb15..d3bb25e7b393 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -1066,7 +1066,13 @@ class EnterpriseExperimentsViewSet(experiment: Experiment = self.get_object()request_serializer = RecalculateMetricsRequestSerializer(data=request.data)request_serializer.is_valid(raise_exception=True)- trigger = request_serializer.validated_data["trigger"]++ is_mcp_client = request.headers.get("x-posthog-client") == "mcp"+ trigger = (+ ExperimentMetricsRecalculation.Trigger.AGENT_MCP+ if is_mcp_client+ else request_serializer.validated_data["trigger"]+ )# request.user is User | AnonymousUser at the DRF level; the viewset enforces auth so it's a User here.result = request_recalculation(experiment, cast(User, request.user), trigger)@@ -1134,7 +1140,23 @@ class EnterpriseExperimentsViewSet(return Response({"detail": "No completed recalculation found"}, status=404)- @extend_schema(responses={200: ExperimentMetricsRecalculationSerializer, 404: None})+ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="recalculation_id",+ location=OpenApiParameter.PATH,+ # Keep the URL's UUID pattern in the schema; declaring a bare UUID type drops it.+ type={+ "type": "string",+ "pattern": r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$",+ },+ description=(+ "UUID of the recalculation run to fetch. This is the run's own id, not the experiment id."+ ),+ )+ ],+ responses={200: ExperimentMetricsRecalculationSerializer, 404: None},+ )@action(methods=["GET"],detail=True,diff --git a/products/experiments/backend/test/test_metrics_recalculation_api.py b/products/experiments/backend/test/test_metrics_recalculation_api.pyindex 7461610970fc..3c2062496b8d 100644--- a/products/experiments/backend/test/test_metrics_recalculation_api.py+++ b/products/experiments/backend/test/test_metrics_recalculation_api.py@@ -81,6 +81,26 @@ class TestMetricsRecalculationAPI(APIBaseTest):assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 1assert mock_run.called+ @mock.patch("products.experiments.backend.presentation.views.sync_connect")+ @mock.patch("products.experiments.backend.presentation.views.asyncio.run")+ def test_post_from_mcp_client_attributes_trigger_to_agent(self, mock_run, mock_connect):+ exp = self._launched_experiment()+ resp = self.client.post(self._post_url(exp.id), format="json", headers={"X-PostHog-Client": "mcp"})+ assert resp.status_code == status.HTTP_201_CREATED, resp.content+ assert resp.json()["trigger"] == ExperimentMetricsRecalculation.Trigger.AGENT_MCP+ assert (+ ExperimentMetricsRecalculation.objects.get(experiment=exp).trigger+ == ExperimentMetricsRecalculation.Trigger.AGENT_MCP+ )++ @mock.patch("products.experiments.backend.presentation.views.sync_connect")+ @mock.patch("products.experiments.backend.presentation.views.asyncio.run")+ def test_post_without_mcp_header_honors_body_trigger(self, mock_run, mock_connect):+ exp = self._launched_experiment()+ resp = self.client.post(self._post_url(exp.id), {"trigger": "manual"}, format="json")+ assert resp.status_code == status.HTTP_201_CREATED, resp.content+ assert resp.json()["trigger"] == ExperimentMetricsRecalculation.Trigger.MANUAL+@mock.patch("products.experiments.backend.presentation.views.sync_connect")@mock.patch("products.experiments.backend.presentation.views.asyncio.run")def test_post_is_idempotent_returns_200(self, mock_run, mock_connect):diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 53a0213a71c7..71b2e6217ce3 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -1857,6 +1857,7 @@ export interface ExperimentFlagCleanupTaskApi {/*** * `manual` - Manual+ * * `agent_mcp` - Agent (MCP)* * `cold_run` - Cold Run* * `stale_refresh` - Stale Refresh* * `auto_refresh` - Auto Refresh@@ -1869,6 +1870,7 @@ export type TriggerEnumApi = (typeof TriggerEnumApi)[keyof typeof TriggerEnumApiexport const TriggerEnumApi = {Manual: 'manual',+ AgentMcp: 'agent_mcp',ColdRun: 'cold_run',StaleRefresh: 'stale_refresh',AutoRefresh: 'auto_refresh',@@ -1885,6 +1887,7 @@ export interface RecalculateMetricsRequestApi {/** What triggered this recalculation (manual is the default for user-initiated runs)** * `manual` - Manual+ * * `agent_mcp` - Agent (MCP)* * `cold_run` - Cold Run* * `stale_refresh` - Stale Refresh* * `auto_refresh` - Auto Refresh@@ -2000,6 +2003,7 @@ export interface ExperimentMetricsRecalculationApi {/** What triggered this recalculation** * `manual` - Manual+ * * `agent_mcp` - Agent (MCP)* * `cold_run` - Cold Run* * `stale_refresh` - Stale Refresh* * `auto_refresh` - Auto Refreshdiff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.tsindex b47bd96f9ad7..28fc16bd8227 100644--- a/products/experiments/frontend/generated/api.zod.ts+++ b/products/experiments/frontend/generated/api.zod.ts@@ -1005,6 +1005,7 @@ export const ExperimentsMetricsRecalculationCreateBody = /* @__PURE__ */ zodtrigger: zod.enum(['manual',+ 'agent_mcp','cold_run','stale_refresh','auto_refresh',@@ -1014,11 +1015,11 @@ export const ExperimentsMetricsRecalculationCreateBody = /* @__PURE__ */ zod'experiment_update',]).describe(- '\* `manual` - Manual\n\* `cold_run` - Cold Run\n\* `stale_refresh` - Stale Refresh\n\* `auto_refresh` - Auto Refresh\n\* `config_change` - Config Change\n\* `experiment_launch` - Experiment Launch\n\* `experiment_stop` - Experiment Stop\n\* `experiment_update` - Experiment Update'+ '\* `manual` - Manual\n\* `agent_mcp` - Agent (MCP)\n\* `cold_run` - Cold Run\n\* `stale_refresh` - Stale Refresh\n\* `auto_refresh` - Auto Refresh\n\* `config_change` - Config Change\n\* `experiment_launch` - Experiment Launch\n\* `experiment_stop` - Experiment Stop\n\* `experiment_update` - Experiment Update').default(experimentsMetricsRecalculationCreateBodyTriggerDefault).describe(- 'What triggered this recalculation (manual is the default for user-initiated runs)\n\n\* `manual` - Manual\n\* `cold_run` - Cold Run\n\* `stale_refresh` - Stale Refresh\n\* `auto_refresh` - Auto Refresh\n\* `config_change` - Config Change\n\* `experiment_launch` - Experiment Launch\n\* `experiment_stop` - Experiment Stop\n\* `experiment_update` - Experiment Update'+ 'What triggered this recalculation (manual is the default for user-initiated runs)\n\n\* `manual` - Manual\n\* `agent_mcp` - Agent (MCP)\n\* `cold_run` - Cold Run\n\* `stale_refresh` - Stale Refresh\n\* `auto_refresh` - Auto Refresh\n\* `config_change` - Config Change\n\* `experiment_launch` - Experiment Launch\n\* `experiment_stop` - Experiment Stop\n\* `experiment_update` - Experiment Update'),}).describe('Request body for triggering a metrics recalculation.')diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex bd0046d7b5e7..e34f93782f99 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -647,6 +647,112 @@ tools:- status- created_at- updated_at+ experiment-metrics-recalculation-create:+ operation: experiments_metrics_recalculation_create+ enabled: true+ scopes:+ - experiment:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ enrich_url: '{params.id}'+ title: Recalculate experiment metrics+ description: >+ Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the+ user's reference first.+++ Start a fresh calculation of every metric on this experiment against the latest data. Use this when the user+ asks to refresh, recalculate, or re-run results, or when results returned by+ experiment-metrics-recalculation-latest look stale. Reading results does NOT trigger a new run, this tool is+ the only way to start one.+++ This queues background work that can take minutes on large experiments. Safe to call more than once: if a+ run is already pending or in progress, it returns that run (with is_existing true, HTTP 200) instead of+ starting a second one.+++ The response has no results array, the run has only just been queued. Take the returned id and poll+ experiment-metrics-recalculation-retrieve with it, or call experiment-metrics-recalculation-latest, until+ status is completed or failed. Watch rows_read and completed_metrics for progress. Do not poll in a tight+ loop; wait a few seconds between checks.+ exclude_params:+ - trigger+ param_overrides:+ id:+ cast: string-int+ experiment-metrics-recalculation-latest-retrieve:+ operation: experiments_metrics_recalculation_latest_retrieve+ enabled: true+ scopes:+ - experiment:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ enrich_url: '{params.id}'+ title: Get experiment results+ description: >+ The default way to read an experiment's current results. Requires an experiment ID. If you don't have the+ ID, load the finding-experiments skill to resolve the user's reference first. To interpret what the numbers+ mean, load the diagnosing-experiment-results skill.+++ Returns the most recent completed metrics run for the experiment: a results array with one entry per metric,+ each carrying per-variant statistics (exposures, counts, means, credible intervals, chance to beat control,+ significance), plus run-level status, created_at, completed_at, and query_to (the data freshness cutoff+ these numbers were computed against, use it to tell the user how fresh the results are).+++ This is a pure read and never starts a calculation, so the numbers can be stale. If the user wants fresh+ numbers, or query_to is old, call experiment-metrics-recalculation-create and then poll.+++ Two fields matter for reading the response correctly. active_run is present when a run is currently+ executing, the returned results are from the previous run, and you can poll active_run.id with+ experiment-metrics-recalculation-retrieve for live progress. result_source is 'timeseries_fallback' when the+ experiment has never completed a run and these numbers are a cold-start placeholder built from daily+ timeseries data, rather than 'recalculation' for a real run; say so if you report those numbers.+++ Returns 404 when the experiment has no results at all yet, which usually means it has not run long enough or+ has never been calculated.+ param_overrides:+ id:+ cast: string-int+ experiment-metrics-recalculation-retrieve:+ operation: experiments_metrics_recalculation_retrieve+ enabled: true+ scopes:+ - experiment:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ enrich_url: '{params.id}'+ title: Get experiment recalculation run+ description: >+ Get one specific metrics recalculation run by its UUID, for the experiment it belongs to. Use this to poll a+ run you started with experiment-metrics-recalculation-create, or the active_run.id returned by+ experiment-metrics-recalculation-latest.+++ To read an experiment's current results without a specific run id, use+ experiment-metrics-recalculation-latest instead.+++ Returns the run's status (pending, in_progress, completed, failed), progress counters (completed_metrics and+ failed_metrics out of total_metrics, plus rows_read against estimated_rows_total), the results array once+ metrics finish, and metric_errors for metrics that failed. metric_retries holds transient state for metrics+ between failed attempts; ignore entries for metrics that already have a result, as those are stale.+++ Returns 404 if the run id does not exist or belongs to a different experiment.+ param_overrides:+ id:+ cast: string-intexperiment-pause:operation: experiments_pause_createenabled: true@@ -939,11 +1045,16 @@ tools:readOnly: truedestructive: falseidempotent: true- title: Get experiment timeseries results+ title: Get experiment metric results over timedescription: >- Get day-by-day experiment results for a specific metric. Requires metric_uuid and fingerprint as query- parameters (both available from the experiment's metrics array — each metric has a uuid and the fingerprint- is computed from its configuration).+ Only for the day-by-day history of a SINGLE metric — how its results moved over the course of the+ experiment. For an experiment's current results across all metrics, which is what "how is this experiment+ doing" almost always means, use experiment-metrics-recalculation-latest instead.+++ Requires metric_uuid and fingerprint as query parameters (both available from the experiment's metrics array+ — each metric has a uuid and the fingerprint is computed from its configuration), so you generally need to+ fetch the experiment first.Returns a timeseries object keyed by date (YYYY-MM-DD) with per-variant statistical results for each day,@@ -1146,15 +1257,6 @@ tools:experiments-flag-cleanup-task-retrieve:operation: experiments_flag_cleanup_task_retrieveenabled: false- experiments-metrics-recalculation-create:- operation: experiments_metrics_recalculation_create- enabled: false- experiments-metrics-recalculation-latest-retrieve:- operation: experiments_metrics_recalculation_latest_retrieve- enabled: false- experiments-metrics-recalculation-retrieve:- operation: experiments_metrics_recalculation_retrieve- enabled: falseexperiments-prompt-templates-retrieve:operation: experiments_prompt_templates_retrieveenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 6810bb13ad09..cb19e23b0577 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3959,6 +3959,48 @@"readOnlyHint": true}},+ "experiment-metrics-recalculation-create": {+ "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\nStart a fresh calculation of every metric on this experiment against the latest data. Use this when the user asks to refresh, recalculate, or re-run results, or when results returned by experiment-metrics-recalculation-latest look stale. Reading results does NOT trigger a new run, this tool is the only way to start one.\n\nThis queues background work that can take minutes on large experiments. Safe to call more than once: if a run is already pending or in progress, it returns that run (with is_existing true, HTTP 200) instead of starting a second one.\n\nThe response has no results array, the run has only just been queued. Take the returned id and poll experiment-metrics-recalculation-retrieve with it, or call experiment-metrics-recalculation-latest, until status is completed or failed. Watch rows_read and completed_metrics for progress. Do not poll in a tight loop; wait a few seconds between checks.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "Recalculate experiment metrics",+ "title": "Recalculate experiment metrics",+ "required_scopes": ["experiment:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "experiment-metrics-recalculation-latest-retrieve": {+ "description": "The default way to read an experiment's current results. Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. To interpret what the numbers mean, load the diagnosing-experiment-results skill.\n\nReturns the most recent completed metrics run for the experiment: a results array with one entry per metric, each carrying per-variant statistics (exposures, counts, means, credible intervals, chance to beat control, significance), plus run-level status, created_at, completed_at, and query_to (the data freshness cutoff these numbers were computed against, use it to tell the user how fresh the results are).\n\nThis is a pure read and never starts a calculation, so the numbers can be stale. If the user wants fresh numbers, or query_to is old, call experiment-metrics-recalculation-create and then poll.\n\nTwo fields matter for reading the response correctly. active_run is present when a run is currently executing, the returned results are from the previous run, and you can poll active_run.id with experiment-metrics-recalculation-retrieve for live progress. result_source is 'timeseries_fallback' when the experiment has never completed a run and these numbers are a cold-start placeholder built from daily timeseries data, rather than 'recalculation' for a real run; say so if you report those numbers.\n\nReturns 404 when the experiment has no results at all yet, which usually means it has not run long enough or has never been calculated.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "Get experiment results",+ "title": "Get experiment results",+ "required_scopes": ["experiment:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "experiment-metrics-recalculation-retrieve": {+ "description": "Get one specific metrics recalculation run by its UUID, for the experiment it belongs to. Use this to poll a run you started with experiment-metrics-recalculation-create, or the active_run.id returned by experiment-metrics-recalculation-latest.\n\nTo read an experiment's current results without a specific run id, use experiment-metrics-recalculation-latest instead.\n\nReturns the run's status (pending, in_progress, completed, failed), progress counters (completed_metrics and failed_metrics out of total_metrics, plus rows_read against estimated_rows_total), the results array once metrics finish, and metric_errors for metrics that failed. metric_retries holds transient state for metrics between failed attempts; ignore entries for metrics that already have a result, as those are stale.\n\nReturns 404 if the run id does not exist or belongs to a different experiment.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "Get experiment recalculation run",+ "title": "Get experiment recalculation run",+ "required_scopes": ["experiment:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"experiment-pause": {"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\nPause a running experiment by deactivating its feature flag (sets flag active=false). The flag is no longer returned by the /decide endpoint, so users fall back to the application default (typically control). No new exposure events ($feature_flag_called) are recorded while paused. The experiment stays in running status — it is not ended.\n\nReturns 400 if: experiment is in draft (\"Experiment has not been launched yet.\"), already stopped (\"Experiment has already ended.\"), no linked flag (\"Experiment does not have a feature flag linked.\"), or already paused (\"Experiment is already paused.\").\n\nNo request body needed. Use resume to reactivate.","category": "Experiments",@@ -4100,11 +4142,11 @@}},"experiment-timeseries-results": {- "description": "Get day-by-day experiment results for a specific metric. Requires metric_uuid and fingerprint as query parameters (both available from the experiment's metrics array — each metric has a uuid and the fingerprint is computed from its configuration).\n\nReturns a timeseries object keyed by date (YYYY-MM-DD) with per-variant statistical results for each day, overall status (\"pending\", \"completed\", \"partial\", \"failed\"), computed_at timestamp, and recalculation_status if a recalculation is in progress.",+ "description": "Only for the day-by-day history of a SINGLE metric — how its results moved over the course of the experiment. For an experiment's current results across all metrics, which is what \"how is this experiment doing\" almost always means, use experiment-metrics-recalculation-latest instead.\n\nRequires metric_uuid and fingerprint as query parameters (both available from the experiment's metrics array — each metric has a uuid and the fingerprint is computed from its configuration), so you generally need to fetch the experiment first.\n\nReturns a timeseries object keyed by date (YYYY-MM-DD) with per-variant statistical results for each day, overall status (\"pending\", \"completed\", \"partial\", \"failed\"), computed_at timestamp, and recalculation_status if a recalculation is in progress.","category": "Experiments","feature": "experiments",- "summary": "Get experiment timeseries results",- "title": "Get experiment timeseries results",+ "summary": "Get experiment metric results over time",+ "title": "Get experiment metric results over time","required_scopes": ["experiment:read"],"annotations": {"destructiveHint": false,diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex e656ea88b0d5..014409e81886 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -4142,6 +4142,48 @@"readOnlyHint": true}},+ "experiment-metrics-recalculation-create": {+ "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\nStart a fresh calculation of every metric on this experiment against the latest data. Use this when the user asks to refresh, recalculate, or re-run results, or when results returned by experiment-metrics-recalculation-latest look stale. Reading results does NOT trigger a new run, this tool is the only way to start one.\n\nThis queues background work that can take minutes on large experiments. Safe to call more than once: if a run is already pending or in progress, it returns that run (with is_existing true, HTTP 200) instead of starting a second one.\n\nThe response has no results array, the run has only just been queued. Take the returned id and poll experiment-metrics-recalculation-retrieve with it, or call experiment-metrics-recalculation-latest, until status is completed or failed. Watch rows_read and completed_metrics for progress. Do not poll in a tight loop; wait a few seconds between checks.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "Recalculate experiment metrics",+ "title": "Recalculate experiment metrics",+ "required_scopes": ["experiment:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "experiment-metrics-recalculation-latest-retrieve": {+ "description": "The default way to read an experiment's current results. Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. To interpret what the numbers mean, load the diagnosing-experiment-results skill.\n\nReturns the most recent completed metrics run for the experiment: a results array with one entry per metric, each carrying per-variant statistics (exposures, counts, means, credible intervals, chance to beat control, significance), plus run-level status, created_at, completed_at, and query_to (the data freshness cutoff these numbers were computed against, use it to tell the user how fresh the results are).\n\nThis is a pure read and never starts a calculation, so the numbers can be stale. If the user wants fresh numbers, or query_to is old, call experiment-metrics-recalculation-create and then poll.\n\nTwo fields matter for reading the response correctly. active_run is present when a run is currently executing, the returned results are from the previous run, and you can poll active_run.id with experiment-metrics-recalculation-retrieve for live progress. result_source is 'timeseries_fallback' when the experiment has never completed a run and these numbers are a cold-start placeholder built from daily timeseries data, rather than 'recalculation' for a real run; say so if you report those numbers.\n\nReturns 404 when the experiment has no results at all yet, which usually means it has not run long enough or has never been calculated.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "Get experiment results",+ "title": "Get experiment results",+ "required_scopes": ["experiment:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "experiment-metrics-recalculation-retrieve": {+ "description": "Get one specific metrics recalculation run by its UUID, for the experiment it belongs to. Use this to poll a run you started with experiment-metrics-recalculation-create, or the active_run.id returned by experiment-metrics-recalculation-latest.\n\nTo read an experiment's current results without a specific run id, use experiment-metrics-recalculation-latest instead.\n\nReturns the run's status (pending, in_progress, completed, failed), progress counters (completed_metrics and failed_metrics out of total_metrics, plus rows_read against estimated_rows_total), the results array once metrics finish, and metric_errors for metrics that failed. metric_retries holds transient state for metrics between failed attempts; ignore entries for metrics that already have a result, as those are stale.\n\nReturns 404 if the run id does not exist or belongs to a different experiment.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "Get experiment recalculation run",+ "title": "Get experiment recalculation run",+ "required_scopes": ["experiment:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"experiment-pause": {"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\nPause a running experiment by deactivating its feature flag (sets flag active=false). The flag is no longer returned by the /decide endpoint, so users fall back to the application default (typically control). No new exposure events ($feature_flag_called) are recorded while paused. The experiment stays in running status — it is not ended.\n\nReturns 400 if: experiment is in draft (\"Experiment has not been launched yet.\"), already stopped (\"Experiment has already ended.\"), no linked flag (\"Experiment does not have a feature flag linked.\"), or already paused (\"Experiment is already paused.\").\n\nNo request body needed. Use resume to reactivate.","category": "Experiments",@@ -4297,11 +4339,11 @@}},"experiment-timeseries-results": {- "description": "Get day-by-day experiment results for a specific metric. Requires metric_uuid and fingerprint as query parameters (both available from the experiment's metrics array — each metric has a uuid and the fingerprint is computed from its configuration).\n\nReturns a timeseries object keyed by date (YYYY-MM-DD) with per-variant statistical results for each day, overall status (\"pending\", \"completed\", \"partial\", \"failed\"), computed_at timestamp, and recalculation_status if a recalculation is in progress.",+ "description": "Only for the day-by-day history of a SINGLE metric — how its results moved over the course of the experiment. For an experiment's current results across all metrics, which is what \"how is this experiment doing\" almost always means, use experiment-metrics-recalculation-latest instead.\n\nRequires metric_uuid and fingerprint as query parameters (both available from the experiment's metrics array — each metric has a uuid and the fingerprint is computed from its configuration), so you generally need to fetch the experiment first.\n\nReturns a timeseries object keyed by date (YYYY-MM-DD) with per-variant statistical results for each day, overall status (\"pending\", \"completed\", \"partial\", \"failed\"), computed_at timestamp, and recalculation_status if a recalculation is in progress.","category": "Experiments","feature": "experiments",- "summary": "Get experiment timeseries results",- "title": "Get experiment timeseries results",+ "summary": "Get experiment metric results over time",+ "title": "Get experiment metric results over time","required_scopes": ["experiment:read"],"annotations": {"destructiveHint": false,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d90f50122606..590d706aec11 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -27034,6 +27034,7 @@ export namespace Schemas {/*** * `manual` - Manual+ * * `agent_mcp` - Agent (MCP)* * `cold_run` - Cold Run* * `stale_refresh` - Stale Refresh* * `auto_refresh` - Auto Refresh@@ -27047,6 +27048,7 @@ export namespace Schemas {export const TriggerEnum = {Manual: 'manual',+ AgentMcp: 'agent_mcp',ColdRun: 'cold_run',StaleRefresh: 'stale_refresh',AutoRefresh: 'auto_refresh',@@ -27131,6 +27133,7 @@ export namespace Schemas {/** What triggered this recalculation** * `manual` - Manual+ * * `agent_mcp` - Agent (MCP)* * `cold_run` - Cold Run* * `stale_refresh` - Stale Refresh* * `auto_refresh` - Auto Refresh@@ -58884,6 +58887,7 @@ export namespace Schemas {/** What triggered this recalculation (manual is the default for user-initiated runs)** * `manual` - Manual+ * * `agent_mcp` - Agent (MCP)* * `cold_run` - Cold Run* * `stale_refresh` - Stale Refresh* * `auto_refresh` - Auto Refreshdiff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.tsindex 29ec3af7c864..5efcbe47d2a7 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 31 enabled ops+ * PostHog API - MCP 34 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -11677,6 +11677,68 @@ export const ExperimentsLaunchCreateParams = /* @__PURE__ */ zod.object({),})+/**+ * Trigger a batch recalculation of all metrics for this experiment.+ *+ * Returns 201 with the new pending recalculation, or 200 with the active one if a recalculation is+ * already pending or in progress for this experiment. The response payload intentionally does not+ * include the `results` array — at POST time the workflow has just been queued and no per-metric+ * results exist yet. Clients should poll `GET metrics_recalculation/{id}/` for results as the workflow+ * progresses.+ */+export const ExperimentsMetricsRecalculationCreateParams = /* @__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 ExperimentsMetricsRecalculationCreateBody = /* @__PURE__ */ zod+ .looseObject({})+ .describe('Request body for triggering a metrics recalculation.')++/**+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.+ *+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate+ * decorator on serializer methods and converts them into the same responses the viewset path+ * produces (see decorators._result_to_response), so both paths share one contract.+ */+export const experimentsMetricsRecalculationRetrievePathRecalculationIdRegExp = new RegExp(+ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'+)++export const ExperimentsMetricsRecalculationRetrieveParams = /* @__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\/."+ ),+ recalculation_id: zod+ .string()+ .regex(experimentsMetricsRecalculationRetrievePathRecalculationIdRegExp)+ .describe("UUID of the recalculation run to fetch. This is the run's own id, not the experiment id."),+})++/**+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.+ *+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate+ * decorator on serializer methods and converts them into the same responses the viewset path+ * produces (see decorators._result_to_response), so both paths share one contract.+ */+export const ExperimentsMetricsRecalculationLatestRetrieveParams = /* @__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\/."+ ),+})+/*** Pause a running experiment.*diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.tsindex b0e517bb7ac6..6b490a6f64c6 100644--- a/services/mcp/src/tools/generated/experiments.ts+++ b/services/mcp/src/tools/generated/experiments.ts@@ -31,6 +31,10 @@ import {ExperimentsFreezeExposureCreateParams,ExperimentsLaunchCreateParams,ExperimentsListQueryParams,+ ExperimentsMetricsRecalculationCreateBody,+ ExperimentsMetricsRecalculationCreateParams,+ ExperimentsMetricsRecalculationLatestRetrieveParams,+ ExperimentsMetricsRecalculationRetrieveParams,ExperimentsPartialUpdateBody,ExperimentsPartialUpdateParams,ExperimentsPauseCreateParams,@@ -645,6 +649,68 @@ const experimentList = (): ToolBase<},})+const ExperimentMetricsRecalculationCreateSchema = ExperimentsMetricsRecalculationCreateParams.omit({+ project_id: true,+})+ .extend(ExperimentsMetricsRecalculationCreateBody.shape)+ .extend({ id: z.preprocess(castStringToInt, ExperimentsMetricsRecalculationCreateParams.shape['id']) })++const experimentMetricsRecalculationCreate = (): ToolBase<+ typeof ExperimentMetricsRecalculationCreateSchema,+ WithPostHogUrl<Schemas.ExperimentMetricsRecalculation>+> => ({+ name: 'experiment-metrics-recalculation-create',+ schema: ExperimentMetricsRecalculationCreateSchema,+ handler: async (context: Context, params: z.infer<typeof ExperimentMetricsRecalculationCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.ExperimentMetricsRecalculation>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/metrics_recalculation/`,+ })+ return await withPostHogUrl(context, result, `/experiments/${params.id}`)+ },+})++const ExperimentMetricsRecalculationLatestRetrieveSchema = ExperimentsMetricsRecalculationLatestRetrieveParams.omit({+ project_id: true,+}).extend({ id: z.preprocess(castStringToInt, ExperimentsMetricsRecalculationLatestRetrieveParams.shape['id']) })++const experimentMetricsRecalculationLatestRetrieve = (): ToolBase<+ typeof ExperimentMetricsRecalculationLatestRetrieveSchema,+ WithPostHogUrl<Schemas.ExperimentMetricsRecalculation>+> => ({+ name: 'experiment-metrics-recalculation-latest-retrieve',+ schema: ExperimentMetricsRecalculationLatestRetrieveSchema,+ handler: async (context: Context, params: z.infer<typeof ExperimentMetricsRecalculationLatestRetrieveSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.ExperimentMetricsRecalculation>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/metrics_recalculation/latest/`,+ })+ return await withPostHogUrl(context, result, `/experiments/${params.id}`)+ },+})++const ExperimentMetricsRecalculationRetrieveSchema = ExperimentsMetricsRecalculationRetrieveParams.omit({+ project_id: true,+}).extend({ id: z.preprocess(castStringToInt, ExperimentsMetricsRecalculationRetrieveParams.shape['id']) })++const experimentMetricsRecalculationRetrieve = (): ToolBase<+ typeof ExperimentMetricsRecalculationRetrieveSchema,+ WithPostHogUrl<Schemas.ExperimentMetricsRecalculation>+> => ({+ name: 'experiment-metrics-recalculation-retrieve',+ schema: ExperimentMetricsRecalculationRetrieveSchema,+ handler: async (context: Context, params: z.infer<typeof ExperimentMetricsRecalculationRetrieveSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.ExperimentMetricsRecalculation>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/metrics_recalculation/${encodeURIComponent(String(params.recalculation_id))}/`,+ })+ return await withPostHogUrl(context, result, `/experiments/${params.id}`)+ },+})+const ExperimentPauseSchema = ExperimentsPauseCreateParams.omit({ project_id: true }).extend({id: z.preprocess(castStringToInt, ExperimentsPauseCreateParams.shape['id']),})@@ -1083,6 +1149,9 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'experiment-holdouts-retrieve': experimentHoldoutsRetrieve,'experiment-launch': experimentLaunch,'experiment-list': experimentList,+ 'experiment-metrics-recalculation-create': experimentMetricsRecalculationCreate,+ 'experiment-metrics-recalculation-latest-retrieve': experimentMetricsRecalculationLatestRetrieve,+ 'experiment-metrics-recalculation-retrieve': experimentMetricsRecalculationRetrieve,'experiment-pause': experimentPause,'experiment-reset': experimentReset,'experiment-resume': experimentResume,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-metrics-recalculation-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-metrics-recalculation-create.jsonnew file mode 100644index 000000000000..1f1461179dd3--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-metrics-recalculation-create.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A unique integer value identifying this experiment.",+ "type": "number"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-metrics-recalculation-latest-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-metrics-recalculation-latest-retrieve.jsonnew file mode 100644index 000000000000..1f1461179dd3--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-metrics-recalculation-latest-retrieve.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A unique integer value identifying this experiment.",+ "type": "number"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-metrics-recalculation-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-metrics-recalculation-retrieve.jsonnew file mode 100644index 000000000000..593b27814095--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-metrics-recalculation-retrieve.json@@ -0,0 +1,16 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A unique integer value identifying this experiment.",+ "type": "number"+ },+ "recalculation_id": {+ "description": "UUID of the recalculation run to fetch. This is the run's own id, not the experiment id.",+ "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$",+ "type": "string"+ }+ },+ "required": ["id", "recalculation_id"],+ "type": "object"+}