: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): add experiment activity endpoint and MCP tool (#73446)
Juraj Majerik5f444ac81b60
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 316940006be4..c3c478d37d5e 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -1560,3 +1560,8 @@ class ExperimentSessionContextResponseSerializer(serializers.Serializer):"experiment's run window overlaps the recording or no flag data was observed in the session."),)+++class ExperimentActivityQuerySerializer(serializers.Serializer):+ limit = serializers.IntegerField(required=False, default=10, min_value=1, help_text="Number of items per page")+ page = serializers.IntegerField(required=False, default=1, min_value=1, help_text="Page number")diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex 7b8116f83865..89db98a212f5 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -29,6 +29,8 @@ from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.auth import IDJagAccessTokenAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication+from posthog.models.activity_logging.activity_log import ActivityLog, get_activity_page+from posthog.models.activity_logging.activity_page import ActivityLogPaginatedResponseSerializer, activity_page_responsefrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -56,6 +58,7 @@ from products.experiments.backend.presentation.serializers import (CopyExperimentToProjectSerializer,CreateFromPromptInputSerializer,EndExperimentSerializer,+ ExperimentActivityQuerySerializer,ExperimentBasicSerializer,ExperimentFlagCleanupTaskSerializer,ExperimentMetricsRecalculationSerializer,@@ -614,6 +617,46 @@ class EnterpriseExperimentsViewSet()return Response(response_serializer.data)+ @validated_request(+ query_serializer=ExperimentActivityQuerySerializer,+ responses={+ 200: OpenApiResponse(response=ActivityLogPaginatedResponseSerializer),+ 404: OpenApiResponse(response=None),+ },+ )+ @action(methods=["GET"], detail=True, required_scopes=["activity_log:read"])+ def activity(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:+ """+ Change history for this experiment.++ Returns a paginated audit trail of changes to the experiment and its holdouts+ and shared metrics: who made each change, what changed (field-level before/after+ values), and when. Ordered newest first.+ """+ limit = request.validated_query_data["limit"]+ page = request.validated_query_data["page"]++ experiment: Experiment = self.get_object()++ # Holdout and shared-metric changes log under the Experiment scope with the child+ # object's own id, so they need their own type-matched clauses. The experiment's own+ # clause must exclude those detail types in turn: an unrelated holdout or shared+ # metric whose pk collides with this experiment's id would otherwise leak in.+ activity_filter = Q(item_id=str(experiment.id)) & ~Q(detail__type__in=["holdout", "shared_metric"])+ if experiment.holdout_id is not None:+ activity_filter |= Q(item_id=str(experiment.holdout_id), detail__type="holdout")+ saved_metric_ids = [str(pk) for pk in experiment.saved_metrics.values_list("id", flat=True)]+ if saved_metric_ids:+ activity_filter |= Q(item_id__in=saved_metric_ids, detail__type="shared_metric")++ activity_query = (+ ActivityLog.objects.select_related("user")+ .filter(activity_filter, team_id=self.team_id, scope="Experiment")+ .order_by("-created_at")+ )+ activity_page = get_activity_page(activity_query, limit, page)+ return activity_page_response(activity_page, limit, page, request)+@extend_schema(request=None,responses=ExperimentSerializer,diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex ee632cd4b0ad..388809b88ef9 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -6995,6 +6995,88 @@ class TestExperimentAuxiliaryEndpoints(_HoistFlagConfigClientMixin, ClickhouseTe# Verify the fix: the update activity log should NOT show the first userself.assertNotEqual(update_logs[0].user, self.user)+ def test_activity_endpoint_returns_only_this_experiments_changes(self):+ saved_metric_response = self.client.post(+ f"/api/projects/{self.team.id}/experiment_saved_metrics/",+ {+ "name": "Activity saved metric",+ "query": {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ },+ )+ self.assertEqual(saved_metric_response.status_code, status.HTTP_201_CREATED)+ saved_metric_id = saved_metric_response.json()["id"]+ holdout_response = self.client.post(+ f"/api/projects/{self.team.id}/experiment_holdouts/",+ data={+ "name": "Activity holdout",+ "filters": [{"properties": [], "rollout_percentage": 20, "variant": "holdout"}],+ },+ format="json",+ )+ self.assertEqual(holdout_response.status_code, status.HTTP_201_CREATED)+ holdout_id = holdout_response.json()["id"]++ create_response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {+ "name": "Experiment with children",+ "feature_flag_key": "activity-endpoint-one",+ "holdout_id": holdout_id,+ "saved_metrics_ids": [{"id": saved_metric_id, "metadata": {"type": "secondary"}}],+ },+ )+ self.assertEqual(create_response.status_code, status.HTTP_201_CREATED)+ experiment_id = create_response.json()["id"]+ self.client.patch(f"/api/projects/{self.team.id}/experiments/{experiment_id}/", {"description": "Updated"})+ self.client.patch(+ f"/api/projects/{self.team.id}/experiment_holdouts/{holdout_id}/", {"name": "Renamed holdout"}+ )+ self.client.patch(+ f"/api/projects/{self.team.id}/experiment_saved_metrics/{saved_metric_id}/", {"name": "Renamed metric"}+ )++ other_response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {"name": "Unrelated experiment", "feature_flag_key": "activity-endpoint-two"},+ )+ other_experiment_id = other_response.json()["id"]+ self.client.patch(+ f"/api/projects/{self.team.id}/experiments/{other_experiment_id}/", {"description": "Unrelated update"}+ )+ # An unrelated shared metric whose pk collides with the experiment's id+ ActivityLog.objects.create(+ team_id=self.team.pk,+ organization_id=self.organization.id,+ scope="Experiment",+ item_id=str(experiment_id),+ activity="updated",+ detail={"type": "shared_metric", "name": "Colliding metric"},+ )++ response = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment_id}/activity?limit=50")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ results = response.json()["results"]++ item_ids = {entry["item_id"] for entry in results}+ self.assertNotIn(str(other_experiment_id), item_ids)+ self.assertLessEqual(item_ids, {str(experiment_id), str(holdout_id), str(saved_metric_id)})+ own_activities = [entry["activity"] for entry in results if entry["item_id"] == str(experiment_id)]+ self.assertIn("created", own_activities)+ self.assertIn("updated", own_activities)+ detail_types = {(entry["detail"] or {}).get("type") for entry in results}+ self.assertIn("holdout", detail_types)+ self.assertIn("shared_metric", detail_types)+ self.assertFalse(+ any(+ entry["item_id"] == str(experiment_id) and (entry["detail"] or {}).get("type") == "shared_metric"+ for entry in results+ )+ )+def test_web_experiment_activity_logging_excludes_parameters_through_main_endpoint(self):feature_flag = FeatureFlag.objects.create(team=self.team,diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 93ea9ab2b6b3..e5c401a4bb3d 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -1713,6 +1713,64 @@ export interface PatchedExperimentWriteApi {readonly user_access_level?: string | null}+export interface ChangeApi {+ readonly type: string+ readonly action: string+ readonly field: string+ readonly before: unknown+ readonly after: unknown+}++export interface MergeApi {+ readonly type: string+ readonly source: unknown+ readonly target: unknown+}++export interface TriggerApi {+ readonly job_type: string+ readonly job_id: string+ readonly payload: unknown+}++export interface DetailApi {+ readonly id: string+ changes?: ChangeApi[]+ merge?: MergeApi+ trigger?: TriggerApi+ readonly name: string+ readonly short_id: string+ readonly type: string+}++/**+ * @nullable+ */+export type ActivityLogEntryApiUser = { [key: string]: unknown } | null++export interface ActivityLogEntryApi {+ readonly id: string+ /** @nullable */+ readonly user: ActivityLogEntryApiUser+ readonly activity: string+ readonly scope: string+ readonly item_id: string+ detail?: DetailApi+ readonly created_at: string+}++/**+ * Response shape for paginated activity log endpoints.+ */+export interface ActivityLogPaginatedResponseApi {+ results: ActivityLogEntryApi[]+ /** @nullable */+ next: string | null+ /** @nullable */+ previous: string | null+ total_count: number+}+export interface ArchiveExperimentApi {/** When the linked feature flag is still enabled, also disable and archive it along with the experiment. Has no effect if the flag is already disabled (it is archived either way). */disable_feature_flag?: boolean@@ -2307,6 +2365,19 @@ export const ExperimentsListStatus = {Stopped: 'stopped',} as const+export type ExperimentsActivityRetrieveParams = {+ /**+ * Number of items per page+ * @minimum 1+ */+ limit?: number+ /**+ * Page number+ * @minimum 1+ */+ page?: number+}+export type ExperimentsTimeseriesResultsRetrieveParams = {/*** Fingerprint of the metric configuration. Available alongside metric_uuid on each metric in the experiment's metrics array.diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.tsindex c64bc9d141f4..53439da041e1 100644--- a/products/experiments/frontend/generated/api.ts+++ b/products/experiments/frontend/generated/api.ts@@ -9,6 +9,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ ActivityLogPaginatedResponseApi,ArchiveExperimentApi,CopyExperimentToProjectApi,CreateFromPromptInputApi,@@ -22,6 +23,7 @@ import type {ExperimentSavedMetricsListParams,ExperimentSessionContextResponseApi,ExperimentWriteApi,+ ExperimentsActivityRetrieveParams,ExperimentsListParams,ExperimentsPromptTemplatesRetrieve200Item,ExperimentsSessionContextRetrieveParams,@@ -403,6 +405,45 @@ export const experimentsDestroy = async (projectId: string, id: number, options?})}+export const getExperimentsActivityRetrieveUrl = (+ projectId: string,+ id: number,+ params?: ExperimentsActivityRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/experiments/${id}/activity/?${stringifiedParams}`+ : `/api/projects/${projectId}/experiments/${id}/activity/`+}++/**+ * Change history for this experiment.+ *+ * Returns a paginated audit trail of changes to the experiment and its holdouts+ * and shared metrics: who made each change, what changed (field-level before/after+ * values), and when. Ordered newest first.+ */+export const experimentsActivityRetrieve = async (+ projectId: string,+ id: number,+ params?: ExperimentsActivityRetrieveParams,+ options?: RequestInit+): Promise<ActivityLogPaginatedResponseApi> => {+ return apiMutator<ActivityLogPaginatedResponseApi>(getExperimentsActivityRetrieveUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}+export const getExperimentsArchiveCreateUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/experiments/${id}/archive/`}diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex e9e124a3d877..bd0046d7b5e7 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -19,6 +19,26 @@ ui_apps:type: detailview_prop: datatools:+ experiment-activity:+ operation: experiments_activity_retrieve+ enabled: true+ scopes:+ - activity_log:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get experiment change history+ description: >+ Get the audit trail for a specific experiment by ID. Returns a paginated list of changes to the experiment+ and its holdouts and shared metrics: who made each change, what was changed (field-level before/after+ values), and when, newest first. Lifecycle actions (launch, end, ship variant, etc.) appear as updates to+ the underlying fields (start_date, end_date, conclusion, ...). Use limit and page query params for+ pagination. Note: changes to the experiment's linked feature flag (rollout, targeting) are logged on the+ flag itself — use feature-flags-activity-retrieve with the flag's ID for those.+ param_overrides:+ id:+ cast: string-intexperiment-archive:operation: experiments_archive_createenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 30763ea9e50a..b9b785fba9f3 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3601,6 +3601,20 @@"readOnlyHint": true}},+ "experiment-activity": {+ "description": "Get the audit trail for a specific experiment by ID. Returns a paginated list of changes to the experiment and its holdouts and shared metrics: who made each change, what was changed (field-level before/after values), and when, newest first. Lifecycle actions (launch, end, ship variant, etc.) appear as updates to the underlying fields (start_date, end_date, conclusion, ...). Use limit and page query params for pagination. Note: changes to the experiment's linked feature flag (rollout, targeting) are logged on the flag itself — use feature-flags-activity-retrieve with the flag's ID for those.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "Get experiment change history",+ "title": "Get experiment change history",+ "required_scopes": ["activity_log:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"experiment-archive": {"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\nArchive a stopped experiment to hide it from the default list view. The experiment must be stopped (end_date set) — cannot archive draft or running experiments.\n\nReturns 400 if already archived (\"Experiment is already archived.\") or not yet stopped (\"Experiment must be ended before it can be archived.\").\n\nNo request body needed. Can be restored later via the unarchive tool.","category": "Experiments",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 8e47ef334924..b1e19e4d1a55 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -3770,6 +3770,20 @@"readOnlyHint": true}},+ "experiment-activity": {+ "description": "Get the audit trail for a specific experiment by ID. Returns a paginated list of changes to the experiment and its holdouts and shared metrics: who made each change, what was changed (field-level before/after values), and when, newest first. Lifecycle actions (launch, end, ship variant, etc.) appear as updates to the underlying fields (start_date, end_date, conclusion, ...). Use limit and page query params for pagination. Note: changes to the experiment's linked feature flag (rollout, targeting) are logged on the flag itself — use feature-flags-activity-retrieve with the flag's ID for those.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "Get experiment change history",+ "title": "Get experiment change history",+ "required_scopes": ["activity_log:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"experiment-archive": {"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\nArchive a stopped experiment to hide it from the default list view. The experiment must be stopped (end_date set) — cannot archive draft or running experiments.\n\nReturns 400 if already archived (\"Experiment is already archived.\") or not yet stopped (\"Experiment must be ended before it can be archived.\").\n\nNo request body needed. Can be restored later via the unarchive tool.","category": "Experiments",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d387343a3464..1e26656e3eeb 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -74768,6 +74768,19 @@ export namespace Schemas {Stopped: 'stopped',} as const;+ export type ExperimentsActivityRetrieveParams = {+ /**+ * Number of items per page+ * @minimum 1+ */+ limit?: number;+ /**+ * Page number+ * @minimum 1+ */+ page?: number;+ };+export type ExperimentsTimeseriesResultsRetrieveParams = {/*** Fingerprint of the metric configuration. Available alongside metric_uuid on each metric in the experiment's metrics array.diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.tsindex 077076897ca1..47bc8f07c34e 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 30 enabled ops+ * PostHog API - MCP 31 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -7982,6 +7982,35 @@ export const ExperimentsDestroyParams = /* @__PURE__ */ zod.object({),})+/**+ * Change history for this experiment.+ *+ * Returns a paginated audit trail of changes to the experiment and its holdouts+ * and shared metrics: who made each change, what changed (field-level before/after+ * values), and when. Ordered newest first.+ */+export const ExperimentsActivityRetrieveParams = /* @__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 experimentsActivityRetrieveQueryLimitDefault = 10++export const experimentsActivityRetrieveQueryPageDefault = 1++export const ExperimentsActivityRetrieveQueryParams = /* @__PURE__ */ zod.object({+ limit: zod+ .number()+ .min(1)+ .default(experimentsActivityRetrieveQueryLimitDefault)+ .describe('Number of items per page'),+ page: zod.number().min(1).default(experimentsActivityRetrieveQueryPageDefault).describe('Page number'),+})+/*** Archive an ended experiment.*diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.tsindex b146ca7e45f6..b0e517bb7ac6 100644--- a/services/mcp/src/tools/generated/experiments.ts+++ b/services/mcp/src/tools/generated/experiments.ts@@ -15,6 +15,8 @@ import {ExperimentSavedMetricsPartialUpdateBody,ExperimentSavedMetricsPartialUpdateParams,ExperimentSavedMetricsRetrieveParams,+ ExperimentsActivityRetrieveParams,+ ExperimentsActivityRetrieveQueryParams,ExperimentsArchiveCreateBody,ExperimentsArchiveCreateParams,ExperimentsCalculateRunningTimeCreateBody,@@ -48,6 +50,27 @@ import { castStringToInt } from '@/tools/cast-helpers'import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'+const ExperimentActivitySchema = ExperimentsActivityRetrieveParams.omit({ project_id: true })+ .extend(ExperimentsActivityRetrieveQueryParams.shape)+ .extend({ id: z.preprocess(castStringToInt, ExperimentsActivityRetrieveParams.shape['id']) })++const experimentActivity = (): ToolBase<typeof ExperimentActivitySchema, Schemas.ActivityLogPaginatedResponse> => ({+ name: 'experiment-activity',+ schema: ExperimentActivitySchema,+ handler: async (context: Context, params: z.infer<typeof ExperimentActivitySchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.ActivityLogPaginatedResponse>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/activity/`,+ query: {+ limit: params.limit,+ page: params.page,+ },+ })+ return result+ },+})+const ExperimentArchiveSchema = ExperimentsArchiveCreateParams.omit({ project_id: true }).extend(ExperimentsArchiveCreateBody.shape).extend({ id: z.preprocess(castStringToInt, ExperimentsArchiveCreateParams.shape['id']) })@@ -1043,6 +1066,7 @@ const experimentUpdate = (): ToolBase<typeof ExperimentUpdateSchema, WithPostHog})export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'experiment-activity': experimentActivity,'experiment-archive': experimentArchive,'experiment-calculate-running-time': experimentCalculateRunningTime,'experiment-copy-to-project': experimentCopyToProject,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-activity.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-activity.jsonnew file mode 100644index 000000000000..d908aa0723c3--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-activity.json@@ -0,0 +1,23 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A unique integer value identifying this experiment.",+ "type": "number"+ },+ "limit": {+ "default": 10,+ "description": "Number of items per page",+ "minimum": 1,+ "type": "number"+ },+ "page": {+ "default": 1,+ "description": "Page number",+ "minimum": 1,+ "type": "number"+ }+ },+ "required": ["id"],+ "type": "object"+}