: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): enable MCP tools for prompt experiments (#77488)
Juraj Majerik034447ccee5a
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex 8452568641dc..060befd39260 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -894,6 +894,12 @@ class EnterpriseExperimentsViewSet(metric per selected template, each scoped to the prompt's $ai_prompt_name.Resulting experiment is in draft state."""+ # Scope checks alone don't cover resource-level access controls: this action runs on the+ # experiment viewset, so AccessControlPermission only verifies experiment access. Check+ # prompt access explicitly before validation queries LLMPrompt and leaks which names exist.+ if not self.user_access_control.check_access_level_for_resource("llm_prompt", required_level="viewer"):+ raise PermissionDenied("Creating an experiment from a prompt requires LLM analytics access.")+serializer = CreateFromPromptInputSerializer(data=request.data, context={"team": self.team})serializer.is_valid(raise_exception=True)data = serializer.validated_datadiff --git a/products/experiments/backend/test/test_create_from_prompt.py b/products/experiments/backend/test/test_create_from_prompt.pyindex 5bcd7474ed68..a0e4ffa63008 100644--- a/products/experiments/backend/test/test_create_from_prompt.py+++ b/products/experiments/backend/test/test_create_from_prompt.py@@ -4,12 +4,15 @@ from typing import Anyfrom parameterized import parameterizedfrom rest_framework import status+from posthog.constants import AvailableFeature+from products.ai_observability.backend.models.llm_prompt import LLMPromptfrom products.experiments.backend.llm_metric_templates import TEMPLATE_NAMESfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.api.test.base import APILicensedTest+from ee.models.rbac.access_control import AccessControldef _split_distribution(variants: list[dict[str, Any]]) -> list[int]:@@ -189,6 +192,16 @@ class TestExperimentsCreateFromPrompt(APILicensedTest):response = self._post(prompt_name="does-not-exist", versions=[1, 2])self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ def test_403_without_llm_analytics_resource_access(self) -> None:+ features = self.organization.available_product_features or []+ features.append({"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL})+ self.organization.available_product_features = features+ self.organization.save()+ AccessControl.objects.create(team=self.team, resource="llm_analytics", access_level="none")++ response = self._post()+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+def test_400_when_template_unknown(self) -> None:response = self._post(templates=["bogus"])self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex 6fb558c1c4eb..2e5b21d4be34 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -258,6 +258,44 @@ tools:- metrics_secondary- conclusion- conclusion_comment+ experiment-create-from-prompt:+ operation: experiments_create_from_prompt_create+ enabled: true+ scopes:+ - experiment:write+ - llm_prompt:read+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ enrich_url: '{id}'+ title: Create experiment from LLM prompt+ description: >+ Create a draft experiment that compares versions of an existing LLM prompt (managed with the llma-prompt+ tools). Pass the prompt's exact name (call llma-prompt-list to discover names), two or more of its version+ numbers (the first entry becomes the control variant), and one or more metric templates — call+ experiment-prompt-templates for the allowed template keys. Builds one variant per version, each carrying a+ feature flag payload with the prompt name and version so the SDK can resolve which version to serve, and+ attaches one primary metric per template, scoped to the prompt. The feature flag is auto-created — do not+ create one separately. Launch the experiment with the launch tool when ready.+ ui_app: experiment+ response:+ include:+ - id+ - name+ - description+ - type+ - feature_flag_key+ - status+ - archived+ - start_date+ - end_date+ - created_at+ - parameters+ - metrics+ - metrics_secondary+ - conclusion+ - conclusion_commentexperiment-delete:operation: experiments_destroyenabled: true@@ -785,6 +823,19 @@ tools:id:cast: string-intui_app: experiment+ experiment-prompt-templates:+ operation: experiments_prompt_templates_retrieve+ enabled: true+ scopes:+ - experiment:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List LLM prompt metric templates+ description: >+ List the metric templates accepted by experiment-create-from-prompt. Each entry has a key (the value to pass+ in that tool's templates parameter), a label, and a description of what the metric measures.experiment-reset:operation: experiments_reset_createenabled: true@@ -1251,18 +1302,12 @@ tools:experiments-create-exposure-cohort:operation: experiments_create_exposure_cohort_for_experiment_createenabled: false- experiments-create-from-prompt-create:- operation: experiments_create_from_prompt_create- enabled: falseexperiments-flag-cleanup-target-retrieve:operation: experiments_flag_cleanup_target_retrieveenabled: falseexperiments-flag-cleanup-task-retrieve:operation: experiments_flag_cleanup_task_retrieveenabled: false- experiments-prompt-templates-retrieve:- operation: experiments_prompt_templates_retrieve- enabled: falseexperiments-recalculate-timeseries:operation: experiments_recalculate_timeseries_createenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 7fa0d4de01d4..376074730258 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3421,6 +3421,20 @@"readOnlyHint": false}},+ "experiment-create-from-prompt": {+ "description": "Create a draft experiment that compares versions of an existing LLM prompt (managed with the llma-prompt tools). Pass the prompt's exact name (call llma-prompt-list to discover names), two or more of its version numbers (the first entry becomes the control variant), and one or more metric templates — call experiment-prompt-templates for the allowed template keys. Builds one variant per version, each carrying a feature flag payload with the prompt name and version so the SDK can resolve which version to serve, and attaches one primary metric per template, scoped to the prompt. The feature flag is auto-created — do not create one separately. Launch the experiment with the launch tool when ready.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "Create experiment from LLM prompt",+ "title": "Create experiment from LLM prompt",+ "required_scopes": ["experiment:write", "llm_prompt:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"experiment-delete": {"description": "Delete an experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Always confirm by name before deleting.","category": "Experiments",@@ -3645,6 +3659,20 @@"readOnlyHint": false}},+ "experiment-prompt-templates": {+ "description": "List the metric templates accepted by experiment-create-from-prompt. Each entry has a key (the value to pass in that tool's templates parameter), a label, and a description of what the metric measures.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "List LLM prompt metric templates",+ "title": "List LLM prompt metric templates",+ "required_scopes": ["experiment:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"experiment-reset": {"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\nReset an experiment back to draft state. Clears start_date, end_date, conclusion, conclusion_comment, and archived flag (all set to null/false). The feature flag is left unchanged — users continue to see their currently assigned variants.\n\nPreviously collected events still exist in the database but won't be included in results unless start_date is manually adjusted after re-launch.\n\nReturns 400 if the experiment is already in draft (\"Experiment is already in draft state.\").\n\nNo request body needed.","category": "Experiments",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex c3ba80995550..fa97f17d361d 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -3576,6 +3576,20 @@"readOnlyHint": false}},+ "experiment-create-from-prompt": {+ "description": "Create a draft experiment that compares versions of an existing LLM prompt (managed with the llma-prompt tools). Pass the prompt's exact name (call llma-prompt-list to discover names), two or more of its version numbers (the first entry becomes the control variant), and one or more metric templates — call experiment-prompt-templates for the allowed template keys. Builds one variant per version, each carrying a feature flag payload with the prompt name and version so the SDK can resolve which version to serve, and attaches one primary metric per template, scoped to the prompt. The feature flag is auto-created — do not create one separately. Launch the experiment with the launch tool when ready.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "Create experiment from LLM prompt",+ "title": "Create experiment from LLM prompt",+ "required_scopes": ["experiment:write", "llm_prompt:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"experiment-delete": {"description": "Delete an experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Always confirm by name before deleting.","category": "Experiments",@@ -3814,6 +3828,20 @@"readOnlyHint": false}},+ "experiment-prompt-templates": {+ "description": "List the metric templates accepted by experiment-create-from-prompt. Each entry has a key (the value to pass in that tool's templates parameter), a label, and a description of what the metric measures.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "List LLM prompt metric templates",+ "title": "List LLM prompt metric templates",+ "required_scopes": ["experiment:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"experiment-reset": {"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\nReset an experiment back to draft state. Clears start_date, end_date, conclusion, conclusion_comment, and archived flag (all set to null/false). The feature flag is left unchanged — users continue to see their currently assigned variants.\n\nPreviously collected events still exist in the database but won't be included in results unless start_date is manually adjusted after re-launch.\n\nReturns 400 if the experiment is already in draft (\"Experiment is already in draft state.\").\n\nNo request body needed.","category": "Experiments",diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.tsindex a27b2e29a676..db8c633f290f 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 34 enabled ops+ * PostHog API - MCP 36 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -12481,6 +12481,72 @@ export const ExperimentsCalculateRunningTimeCreateBody = /* @__PURE__ */ zod}).describe('Inputs for estimating the recommended sample size and running time of an experiment.')+/**+ * Create an experiment that compares N versions of an LLM prompt using a metric template.+ *+ * The user picks 2+ versions of an existing LLMPrompt and 1+ metric templates+ * (cost / latency / eval_pass_rate). The endpoint builds the matching variants+ * (control + test-N, each named after its prompt version) and attaches one+ * metric per selected template, each scoped to the prompt's $ai_prompt_name.+ * Resulting experiment is in draft state.+ */+export const ExperimentsCreateFromPromptCreateParams = /* @__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 experimentsCreateFromPromptCreateBodyVersionsMin = 2+export const experimentsCreateFromPromptCreateBodyVersionsMax = 10++export const experimentsCreateFromPromptCreateBodyTemplatesMax = 3++export const ExperimentsCreateFromPromptCreateBody = /* @__PURE__ */ zod.object({+ prompt_name: zod+ .string()+ .describe('The name of the LLM prompt to experiment on. Must already exist for this team.'),+ versions: zod+ .array(zod.number().min(1))+ .min(experimentsCreateFromPromptCreateBodyVersionsMin)+ .max(experimentsCreateFromPromptCreateBodyVersionsMax)+ .describe(+ 'Ordered list of prompt version numbers to assign to experiment variants. The first entry is the control variant. Must contain between 2 and 10 distinct versions.'+ ),+ templates: zod+ .array(+ zod+ .enum(['cost', 'latency', 'eval_pass_rate'])+ .describe('\* `cost` - cost\n\* `latency` - latency\n\* `eval_pass_rate` - eval_pass_rate')+ )+ .min(1)+ .max(experimentsCreateFromPromptCreateBodyTemplatesMax)+ .describe(+ 'One or more metric templates to attach as primary metrics. Each template becomes one metric on the experiment. Allowed values: cost, latency, eval_pass_rate.'+ ),+ name: zod+ .string()+ .optional()+ .describe('Optional experiment name. If omitted, a name is generated from the prompt and versions.'),+ feature_flag_key: zod+ .string()+ .optional()+ .describe('Optional feature flag key. If omitted, a slug is derived from the experiment name.'),+ description: zod.string().optional().describe('Optional experiment description.'),+})++/**+ * List the LLM metric templates that can be passed to `create_from_prompt`.+ */+export const ExperimentsPromptTemplatesRetrieveParams = /* @__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\/."+ ),+})+/*** Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.*diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.tsindex fcdb1b50ad8d..1032debaecec 100644--- a/services/mcp/src/tools/generated/experiments.ts+++ b/services/mcp/src/tools/generated/experiments.ts@@ -23,6 +23,7 @@ import {ExperimentsCopyToProjectCreateBody,ExperimentsCopyToProjectCreateParams,ExperimentsCreateBody,+ ExperimentsCreateFromPromptCreateBody,ExperimentsDestroyParams,ExperimentsDuplicateCreateBody,ExperimentsDuplicateCreateParams,@@ -277,6 +278,62 @@ const experimentCreate = (): ToolBase<typeof ExperimentCreateSchema, WithPostHog},})+const ExperimentCreateFromPromptSchema = ExperimentsCreateFromPromptCreateBody++const experimentCreateFromPrompt = (): ToolBase<+ typeof ExperimentCreateFromPromptSchema,+ WithPostHogUrl<Schemas.Experiment>+> =>+ withUiApp('experiment', {+ name: 'experiment-create-from-prompt',+ schema: ExperimentCreateFromPromptSchema,+ handler: async (context: Context, params: z.infer<typeof ExperimentCreateFromPromptSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.prompt_name !== undefined) {+ body['prompt_name'] = params.prompt_name+ }+ if (params.versions !== undefined) {+ body['versions'] = params.versions+ }+ if (params.templates !== undefined) {+ body['templates'] = params.templates+ }+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.feature_flag_key !== undefined) {+ body['feature_flag_key'] = params.feature_flag_key+ }+ if (params.description !== undefined) {+ body['description'] = params.description+ }+ const result = await context.api.request<Schemas.Experiment>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/create_from_prompt/`,+ 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 await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)+ },+ })+const ExperimentDeleteSchema = ExperimentsDestroyParams.omit({ project_id: true }).extend({id: z.preprocess(castStringToInt, ExperimentsDestroyParams.shape['id']),})@@ -736,6 +793,22 @@ const experimentPause = (): ToolBase<typeof ExperimentPauseSchema, WithPostHogUr},})+const ExperimentPromptTemplatesSchema = z.object({})++const experimentPromptTemplates = (): ToolBase<typeof ExperimentPromptTemplatesSchema, unknown> => ({+ name: 'experiment-prompt-templates',+ schema: ExperimentPromptTemplatesSchema,+ // eslint-disable-next-line no-unused-vars+ handler: async (context: Context, params: z.infer<typeof ExperimentPromptTemplatesSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<unknown>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/prompt_templates/`,+ })+ return result+ },+})+const ExperimentResetSchema = ExperimentsResetCreateParams.omit({ project_id: true }).extend({id: z.preprocess(castStringToInt, ExperimentsResetCreateParams.shape['id']),})@@ -1149,6 +1222,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'experiment-calculate-running-time': experimentCalculateRunningTime,'experiment-copy-to-project': experimentCopyToProject,'experiment-create': experimentCreate,+ 'experiment-create-from-prompt': experimentCreateFromPrompt,'experiment-delete': experimentDelete,'experiment-duplicate': experimentDuplicate,'experiment-end': experimentEnd,@@ -1165,6 +1239,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'experiment-metrics-recalculation-latest-retrieve': experimentMetricsRecalculationLatestRetrieve,'experiment-metrics-recalculation-retrieve': experimentMetricsRecalculationRetrieve,'experiment-pause': experimentPause,+ 'experiment-prompt-templates': experimentPromptTemplates,'experiment-reset': experimentReset,'experiment-resume': experimentResume,'experiment-saved-metrics-create': experimentSavedMetricsCreate,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create-from-prompt.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create-from-prompt.jsonnew file mode 100644index 000000000000..bb0574738bff--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create-from-prompt.json@@ -0,0 +1,44 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "description": {+ "description": "Optional experiment description.",+ "type": "string"+ },+ "feature_flag_key": {+ "description": "Optional feature flag key. If omitted, a slug is derived from the experiment name.",+ "type": "string"+ },+ "name": {+ "description": "Optional experiment name. If omitted, a name is generated from the prompt and versions.",+ "type": "string"+ },+ "prompt_name": {+ "description": "The name of the LLM prompt to experiment on. Must already exist for this team.",+ "type": "string"+ },+ "templates": {+ "description": "One or more metric templates to attach as primary metrics. Each template becomes one metric on the experiment. Allowed values: cost, latency, eval_pass_rate.",+ "items": {+ "description": "* `cost` - cost\n* `latency` - latency\n* `eval_pass_rate` - eval_pass_rate",+ "enum": ["cost", "latency", "eval_pass_rate"],+ "type": "string"+ },+ "maxItems": 3,+ "minItems": 1,+ "type": "array"+ },+ "versions": {+ "description": "Ordered list of prompt version numbers to assign to experiment variants. The first entry is the control variant. Must contain between 2 and 10 distinct versions.",+ "items": {+ "minimum": 1,+ "type": "number"+ },+ "maxItems": 10,+ "minItems": 2,+ "type": "array"+ }+ },+ "required": ["prompt_name", "versions", "templates"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-prompt-templates.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-prompt-templates.jsonnew file mode 100644index 000000000000..7b7ea9186078--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-prompt-templates.json@@ -0,0 +1,5 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {},+ "type": "object"+}