: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(replay): expose session recording export to MCP, staff-gated (#64910)
Paul D'Ambra6de82832879f
diff --git a/posthog/admin/admins/team_admin.py b/posthog/admin/admins/team_admin.pyindex d146bdd53355..df0d6891c39d 100644--- a/posthog/admin/admins/team_admin.py+++ b/posthog/admin/admins/team_admin.py@@ -5,7 +5,6 @@ import uuidimport asyncioimport hashlibimport tempfile-import dataclassesfrom datetime import datetime, timedeltafrom decimal import Decimal, InvalidOperationfrom urllib import parse@@ -36,7 +35,7 @@ from posthog.admin.inlines.user_product_list_inline import UserProductListInlinefrom posthog.cloud_utils import is_cloudfrom posthog.llm.gateway_internal_client import AIGatewayInternalError, AIGatewayNotConfigured, add_credit, get_walletfrom posthog.models import Team-from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, log_activity+from posthog.models.activity_logging.activity_log import Detail, log_activityfrom posthog.models.remote_config import RemoteConfigfrom posthog.models.team.team import DEPRECATED_ATTRSfrom posthog.session_recordings.recordings import recording_s3_client@@ -51,10 +50,10 @@ from posthog.temporal.session_replay.delete_recordings.types import (RecordingsWithSessionIdsInput,RecordingsWithTeamInput,)-from posthog.temporal.session_replay.export_recording.types import ExportRecordingInputfrom posthog.temporal.session_replay.import_recording.types import ImportRecordingInputfrom products.replay.backend.models.exported_recording import ExportedRecording+from products.replay.backend.services.export_recording import ReplayActivityContext, trigger_recording_exportlogger = get_logger()@@ -62,11 +61,6 @@ logger = get_logger()MAX_CREDIT_USD = Decimal("1000000")[email protected](frozen=True)-class ReplayActivityContext(ActivityContextBase):- reason: str--class TeamAdminForm(ModelForm):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)@@ -804,45 +798,13 @@ class TeamAdmin(admin.ModelAdmin):triggered_by=request.user.email,)- export_record = ExportedRecording.objects.create(- team=team,- session_id=session_id,- reason=reason,- created_by=request.user,- )-try:- temporal = sync_connect()- workflow_input = ExportRecordingInput(exported_recording_id=export_record.id)- workflow_id = f"export-recording-{export_record.id}-{uuid.uuid4()}"-- asyncio.run(- temporal.start_workflow(- "export-recording",- workflow_input,- id=workflow_id,- task_queue=settings.SESSION_REPLAY_TASK_QUEUE,- retry_policy=common.RetryPolicy(- maximum_attempts=2,- initial_interval=timedelta(minutes=1),- ),- )- )-- log_activity(- organization_id=team.organization_id,- team_id=team.id,+ export_record = trigger_recording_export(+ team=team,+ session_id=session_id,+ reason=reason,user=request.user,was_impersonated=False,- item_id=session_id,- scope="Replay",- activity="exported",- detail=Detail(- name=f"Session replay {session_id}",- short_id=session_id,- type="admin_export",- context=ReplayActivityContext(reason=reason),- ),)messages.success(diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 63df1b3460f5..8cf9af73f13d 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -501,6 +501,7 @@ SPECTACULAR_SETTINGS = {"ScannerProviderEnum": "products.replay_vision.backend.models.replay_scanner.ScannerProvider","ObservationStatusEnum": "products.replay_vision.backend.models.replay_observation.ObservationStatus","ObservationTriggerEnum": "products.replay_vision.backend.models.replay_observation.ObservationTrigger",+ "ExportedRecordingStatusEnum": "products.replay.backend.models.exported_recording.ExportedRecording.Status","AutonomyPriorityEnum": "products.signals.backend.models.AutonomyPriority","UserInterviewSearchDocumentTypeEnum": "products.user_interviews.backend.facade.enums.SEARCH_DOCUMENT_TYPES","BatchExportRunStatusEnum": "products.batch_exports.backend.models.batch_export.BatchExportRun.Status",diff --git a/products/replay/backend/api/__init__.py b/products/replay/backend/api/__init__.pynew file mode 100644index 000000000000..7aa48eb9a928--- /dev/null+++ b/products/replay/backend/api/__init__.py@@ -0,0 +1,5 @@+from .session_recording_export import SessionRecordingExportViewSet++__all__ = [+ "SessionRecordingExportViewSet",+]diff --git a/products/replay/backend/api/session_recording_export.py b/products/replay/backend/api/session_recording_export.pynew file mode 100644index 000000000000..a04d723be33b--- /dev/null+++ b/products/replay/backend/api/session_recording_export.py@@ -0,0 +1,109 @@+from typing import cast++import structlog+from drf_spectacular.utils import OpenApiResponse+from loginas.utils import is_impersonated_session+from rest_framework import mixins, request, response, serializers, status, viewsets+from rest_framework.exceptions import APIException++from posthog.api.documentation import extend_schema+from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.shared import UserBasicSerializer+from posthog.models.user import User+from posthog.permissions import IsStaffUser++from products.replay.backend.models.exported_recording import ExportedRecording+from products.replay.backend.services.export_recording import trigger_recording_export++logger = structlog.get_logger(__name__)+++class ExportTriggerFailed(APIException):+ status_code = status.HTTP_502_BAD_GATEWAY+ default_detail = "Failed to start the export workflow; please retry."+ default_code = "export_trigger_failed"+++class ExportedRecordingSerializer(serializers.ModelSerializer):+ created_by = UserBasicSerializer(read_only=True, help_text="The user who triggered the export.")+ is_expired = serializers.BooleanField(+ read_only=True,+ help_text="True when the export is older than 7 days and its downloadable data may have been purged.",+ )++ class Meta:+ model = ExportedRecording+ fields = [+ "id",+ "session_id",+ "reason",+ "status",+ "export_location",+ "error_message",+ "created_at",+ "created_by",+ "is_expired",+ ]+ read_only_fields = fields+ extra_kwargs = {+ "id": {"help_text": "Unique identifier for this export job."},+ "session_id": {"help_text": "The `$session_id` of the recording being exported."},+ "reason": {"help_text": "Human-provided justification for the export, kept for audit purposes."},+ "status": {"help_text": "Lifecycle status of the export: pending, running, complete, or failed."},+ "export_location": {+ "help_text": "Storage location of the exported data once the job completes; null until status is complete."+ },+ "error_message": {"help_text": "Failure detail when status is failed; null otherwise."},+ "created_at": {"help_text": "When the export was requested."},+ }+++class ExportedRecordingCreateSerializer(serializers.Serializer):+ session_id = serializers.CharField(+ max_length=200,+ help_text="The `$session_id` of the recording to export.",+ )+ reason = serializers.CharField(+ help_text="Why this recording is being exported. Recorded for audit purposes.",+ )+++@extend_schema(tags=["replay"])+class SessionRecordingExportViewSet(+ TeamAndOrgViewSetMixin,+ mixins.ListModelMixin,+ mixins.RetrieveModelMixin,+ mixins.CreateModelMixin,+ viewsets.GenericViewSet,+):+ scope_object = "session_recording"+ permission_classes = [IsStaffUser]+ queryset = ExportedRecording.objects.all().select_related("created_by")+ serializer_class = ExportedRecordingSerializer++ @extend_schema(+ request=ExportedRecordingCreateSerializer,+ responses={+ 201: ExportedRecordingSerializer,+ 502: OpenApiResponse(description="The export was recorded but the export workflow failed to start."),+ },+ summary="Trigger a session recording export",+ )+ def create(self, request: request.Request, *args: object, **kwargs: object) -> response.Response:+ create_serializer = ExportedRecordingCreateSerializer(data=request.data)+ create_serializer.is_valid(raise_exception=True)++ try:+ export_record = trigger_recording_export(+ team=self.team,+ session_id=create_serializer.validated_data["session_id"],+ reason=create_serializer.validated_data["reason"],+ user=cast(User, request.user),+ was_impersonated=is_impersonated_session(request),+ )+ except Exception:+ logger.exception("session_recording_export_trigger_failed", team_id=self.team.id)+ raise ExportTriggerFailed++ output = ExportedRecordingSerializer(export_record, context=self.get_serializer_context())+ return response.Response(output.data, status=status.HTTP_201_CREATED)diff --git a/products/replay/backend/routes.py b/products/replay/backend/routes.pynew file mode 100644index 000000000000..c0bfc73ca42c--- /dev/null+++ b/products/replay/backend/routes.py@@ -0,0 +1,12 @@+from posthog.api.routing import RouterRegistry++from products.replay.backend.api import SessionRecordingExportViewSet+++def register_routes(routers: RouterRegistry) -> None:+ routers.projects.register(+ r"session_recording_exports",+ SessionRecordingExportViewSet,+ "session_recording_exports",+ ["team_id"],+ )diff --git a/products/replay/backend/services/__init__.py b/products/replay/backend/services/__init__.pynew file mode 100644index 000000000000..ad75f9b5e88e--- /dev/null+++ b/products/replay/backend/services/__init__.py@@ -0,0 +1,6 @@+from .export_recording import ReplayActivityContext, trigger_recording_export++__all__ = [+ "ReplayActivityContext",+ "trigger_recording_export",+]diff --git a/products/replay/backend/services/export_recording.py b/products/replay/backend/services/export_recording.pynew file mode 100644index 000000000000..76be6c0c7a31--- /dev/null+++ b/products/replay/backend/services/export_recording.py@@ -0,0 +1,86 @@+import uuid+import asyncio+import dataclasses+from datetime import timedelta++from django.conf import settings++import structlog+from temporalio import common++from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, log_activity+from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.temporal.common.client import sync_connect+from posthog.temporal.session_replay.export_recording.types import ExportRecordingInput++from products.replay.backend.models.exported_recording import ExportedRecording++logger = structlog.get_logger(__name__)++[email protected](frozen=True)+class ReplayActivityContext(ActivityContextBase):+ reason: str+++def trigger_recording_export(+ *,+ team: Team,+ session_id: str,+ reason: str,+ user: User,+ was_impersonated: bool,+) -> ExportedRecording:+ export_record = ExportedRecording.objects.create(+ team=team,+ session_id=session_id,+ reason=reason,+ created_by=user,+ )++ try:+ temporal = sync_connect()+ workflow_input = ExportRecordingInput(exported_recording_id=export_record.id)+ workflow_id = f"export-recording-{export_record.id}-{uuid.uuid4()}"++ asyncio.run(+ temporal.start_workflow(+ "export-recording",+ workflow_input,+ id=workflow_id,+ task_queue=settings.SESSION_REPLAY_TASK_QUEUE,+ retry_policy=common.RetryPolicy(+ maximum_attempts=2,+ initial_interval=timedelta(minutes=1),+ ),+ )+ )+ except Exception:+ export_record.status = ExportedRecording.Status.FAILED+ export_record.error_message = "Failed to start the export workflow"+ export_record.save(update_fields=["status", "error_message"])+ raise++ # The workflow has started; an audit-log write failure must not fail the export+ # (which would 502 and prompt a retry that starts a duplicate workflow).+ try:+ log_activity(+ organization_id=team.organization_id,+ team_id=team.id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=session_id,+ scope="Replay",+ activity="exported",+ detail=Detail(+ name=f"Session replay {session_id}",+ short_id=session_id,+ type="admin_export",+ context=ReplayActivityContext(reason=reason),+ ),+ )+ except Exception:+ logger.exception("export_recording_activity_log_failed", team_id=team.id, session_id=session_id)++ return export_recorddiff --git a/products/replay/backend/test/__init__.py b/products/replay/backend/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/replay/backend/test/test_export_recording_service.py b/products/replay/backend/test/test_export_recording_service.pynew file mode 100644index 000000000000..8bb0f2d389f3--- /dev/null+++ b/products/replay/backend/test/test_export_recording_service.py@@ -0,0 +1,94 @@+from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, MagicMock, patch++from products.replay.backend.models.exported_recording import ExportedRecording+from products.replay.backend.services.export_recording import trigger_recording_export++SERVICE = "products.replay.backend.services.export_recording"+++class TestTriggerRecordingExport(BaseTest):+ def _run(self, *, was_impersonated: bool = False) -> tuple[ExportedRecording, MagicMock, MagicMock]:+ mock_temporal = MagicMock()+ mock_temporal.start_workflow = AsyncMock(return_value=None)++ with (+ patch(f"{SERVICE}.sync_connect", return_value=mock_temporal),+ patch(f"{SERVICE}.log_activity") as mock_log_activity,+ ):+ record = trigger_recording_export(+ team=self.team,+ session_id="session-123",+ reason="debugging a customer issue",+ user=self.user,+ was_impersonated=was_impersonated,+ )+ return record, mock_temporal.start_workflow, mock_log_activity++ def test_creates_exported_recording_row(self) -> None:+ record, _, _ = self._run()++ persisted = ExportedRecording.objects.get(id=record.id)+ assert persisted.team == self.team+ assert persisted.session_id == "session-123"+ assert persisted.reason == "debugging a customer issue"+ assert persisted.created_by == self.user+ assert persisted.status == ExportedRecording.Status.PENDING++ def test_starts_export_workflow_for_the_new_record(self) -> None:+ record, start_workflow, _ = self._run()++ start_workflow.assert_called_once()+ args, kwargs = start_workflow.call_args+ assert args[0] == "export-recording"+ assert args[1].exported_recording_id == record.id+ assert kwargs["id"].startswith(f"export-recording-{record.id}-")++ def test_forwards_was_impersonated_to_activity_log(self) -> None:+ _, _, mock_log_activity = self._run(was_impersonated=True)++ mock_log_activity.assert_called_once()+ assert mock_log_activity.call_args.kwargs["was_impersonated"] is True+ assert mock_log_activity.call_args.kwargs["scope"] == "Replay"+ assert mock_log_activity.call_args.kwargs["activity"] == "exported"++ def test_marks_record_failed_when_workflow_start_fails(self) -> None:+ mock_temporal = MagicMock()+ mock_temporal.start_workflow = AsyncMock(side_effect=RuntimeError("temporal down"))++ with (+ patch(f"{SERVICE}.sync_connect", return_value=mock_temporal),+ patch(f"{SERVICE}.log_activity") as mock_log_activity,+ ):+ with self.assertRaises(RuntimeError):+ trigger_recording_export(+ team=self.team,+ session_id="session-456",+ reason="debugging",+ user=self.user,+ was_impersonated=False,+ )++ persisted = ExportedRecording.objects.get(team=self.team, session_id="session-456")+ assert persisted.status == ExportedRecording.Status.FAILED+ assert persisted.error_message == "Failed to start the export workflow"+ mock_log_activity.assert_not_called()++ def test_activity_log_failure_does_not_fail_the_export(self) -> None:+ mock_temporal = MagicMock()+ mock_temporal.start_workflow = AsyncMock(return_value=None)++ with (+ patch(f"{SERVICE}.sync_connect", return_value=mock_temporal),+ patch(f"{SERVICE}.log_activity", side_effect=RuntimeError("activity log down")),+ ):+ record = trigger_recording_export(+ team=self.team,+ session_id="session-789",+ reason="debugging",+ user=self.user,+ was_impersonated=False,+ )++ persisted = ExportedRecording.objects.get(id=record.id)+ assert persisted.status == ExportedRecording.Status.PENDINGdiff --git a/products/replay/backend/test/test_session_recording_export_api.py b/products/replay/backend/test/test_session_recording_export_api.pynew file mode 100644index 000000000000..b73b59747ac2--- /dev/null+++ b/products/replay/backend/test/test_session_recording_export_api.py@@ -0,0 +1,111 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized+from rest_framework import status++from posthog.models import Team++from products.replay.backend.models.exported_recording import ExportedRecording++VIEWSET = "products.replay.backend.api.session_recording_export"+++class TestSessionRecordingExportAPI(APIBaseTest):+ def _url(self, export_id: str | None = None) -> str:+ base = f"/api/projects/{self.team.id}/session_recording_exports/"+ return f"{base}{export_id}/" if export_id else base++ def _make_staff(self) -> None:+ self.user.is_staff = True+ self.user.save()++ def _export(self, team: Team | None = None, session_id: str = "session-1") -> ExportedRecording:+ return ExportedRecording.objects.create(+ team=team or self.team,+ session_id=session_id,+ reason="because",+ created_by=self.user,+ )++ def test_staff_create_triggers_export(self) -> None:+ self._make_staff()++ def fake_trigger(*, team: Team, session_id: str, reason: str, **_: object) -> ExportedRecording:+ return self._export(team=team, session_id=session_id)++ with patch(f"{VIEWSET}.trigger_recording_export", side_effect=fake_trigger) as mock_trigger:+ response = self.client.post(+ self._url(),+ {"session_id": "session-abc", "reason": "investigating a bug"},+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert ExportedRecording.objects.filter(team=self.team).count() == 1+ mock_trigger.assert_called_once()+ kwargs = mock_trigger.call_args.kwargs+ assert kwargs["team"] == self.team+ assert kwargs["session_id"] == "session-abc"+ assert kwargs["reason"] == "investigating a bug"+ assert kwargs["user"] == self.user+ assert kwargs["was_impersonated"] is False++ @parameterized.expand(["create", "list", "retrieve"])+ def test_non_staff_is_forbidden(self, action: str) -> None:+ export = self._export()++ if action == "create":+ response = self.client.post(self._url(), {"session_id": "s", "reason": "r"})+ elif action == "list":+ response = self.client.get(self._url())+ else:+ response = self.client.get(self._url(str(export.id)))++ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_staff_can_list_and_retrieve(self) -> None:+ self._make_staff()+ export = self._export(session_id="session-xyz")++ list_response = self.client.get(self._url())+ assert list_response.status_code == status.HTTP_200_OK+ results = list_response.json()["results"]+ assert len(results) == 1+ assert results[0]["session_id"] == "session-xyz"+ assert results[0]["status"] == ExportedRecording.Status.PENDING+ assert results[0]["created_by"]["id"] == self.user.id++ detail_response = self.client.get(self._url(str(export.id)))+ assert detail_response.status_code == status.HTTP_200_OK+ assert detail_response.json()["id"] == str(export.id)++ def test_team_isolation(self) -> None:+ self._make_staff()+ other_team = Team.objects.create(organization=self.organization)+ other_export = self._export(team=other_team, session_id="other-team-session")++ list_response = self.client.get(self._url())+ assert list_response.status_code == status.HTTP_200_OK+ assert list_response.json()["results"] == []++ detail_response = self.client.get(self._url(str(other_export.id)))+ assert detail_response.status_code == status.HTTP_404_NOT_FOUND++ @parameterized.expand([("session_id", {"reason": "r"}), ("reason", {"session_id": "s"})])+ def test_missing_required_field_is_rejected(self, _name: str, body: dict[str, str]) -> None:+ self._make_staff()++ response = self.client.post(self._url(), body)++ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_workflow_start_failure_surfaces_error(self) -> None:+ self._make_staff()++ with patch(f"{VIEWSET}.trigger_recording_export", side_effect=RuntimeError("temporal down")):+ response = self.client.post(+ self._url(),+ {"session_id": "session-abc", "reason": "investigating a bug"},+ )++ assert response.status_code == status.HTTP_502_BAD_GATEWAYdiff --git a/products/replay/frontend/generated/api.schemas.ts b/products/replay/frontend/generated/api.schemas.tsindex f5d65a1c1979..10242009c283 100644--- a/products/replay/frontend/generated/api.schemas.ts+++ b/products/replay/frontend/generated/api.schemas.ts@@ -7,6 +7,22 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+/**+ * * `pending` - Pending+ * * `running` - Running+ * * `complete` - Complete+ * * `failed` - Failed+ */+export type ExportedRecordingStatusEnumApi =+ (typeof ExportedRecordingStatusEnumApi)[keyof typeof ExportedRecordingStatusEnumApi]++export const ExportedRecordingStatusEnumApi = {+ Pending: 'pending',+ Running: 'running',+ Complete: 'complete',+ Failed: 'failed',+} as const+/*** * `engineering` - Engineering* * `data` - Data@@ -62,6 +78,57 @@ export interface UserBasicApi {role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null}+export interface ExportedRecordingApi {+ /** Unique identifier for this export job. */+ readonly id: string+ /** The `$session_id` of the recording being exported. */+ readonly session_id: string+ /** Human-provided justification for the export, kept for audit purposes. */+ readonly reason: string+ /** Lifecycle status of the export: pending, running, complete, or failed.+ *+ * * `pending` - Pending+ * * `running` - Running+ * * `complete` - Complete+ * * `failed` - Failed */+ readonly status: ExportedRecordingStatusEnumApi+ /**+ * Storage location of the exported data once the job completes; null until status is complete.+ * @nullable+ */+ readonly export_location: string | null+ /**+ * Failure detail when status is failed; null otherwise.+ * @nullable+ */+ readonly error_message: string | null+ /** When the export was requested. */+ readonly created_at: string+ /** The user who triggered the export. */+ readonly created_by: UserBasicApi+ /** True when the export is older than 7 days and its downloadable data may have been purged. */+ readonly is_expired: boolean+}++export interface PaginatedExportedRecordingListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: ExportedRecordingApi[]+}++export interface ExportedRecordingCreateApi {+ /**+ * The `$session_id` of the recording to export.+ * @maxLength 200+ */+ session_id: string+ /** Why this recording is being exported. Recorded for audit purposes. */+ reason: string+}+/*** * `collection` - Collection* * `filters` - Filters@@ -457,6 +524,17 @@ export interface SingleSessionSummaryApi {readonly created_by: UserBasicApi | null}+export type SessionRecordingExportsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}+export type SessionRecordingPlaylistsListParams = {created_by?: number/**diff --git a/products/replay/frontend/generated/api.ts b/products/replay/frontend/generated/api.tsindex ef9a202826af..827f6ae64fd3 100644--- a/products/replay/frontend/generated/api.ts+++ b/products/replay/frontend/generated/api.ts@@ -9,12 +9,16 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ ExportedRecordingApi,+ ExportedRecordingCreateApi,+ PaginatedExportedRecordingListApi,PaginatedSessionRecordingListApi,PaginatedSessionRecordingPlaylistListApi,PaginatedSingleSessionSummaryMinimalListApi,PatchedSessionRecordingApi,PatchedSessionRecordingPlaylistApi,SessionRecordingApi,+ SessionRecordingExportsListParams,SessionRecordingPlaylistApi,SessionRecordingPlaylistsListParams,SessionRecordingsListParams,@@ -40,6 +44,68 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>+export const getSessionRecordingExportsListUrl = (projectId: string, params?: SessionRecordingExportsListParams) => {+ 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}/session_recording_exports/?${stringifiedParams}`+ : `/api/projects/${projectId}/session_recording_exports/`+}++export const sessionRecordingExportsList = async (+ projectId: string,+ params?: SessionRecordingExportsListParams,+ options?: RequestInit+): Promise<PaginatedExportedRecordingListApi> => {+ return apiMutator<PaginatedExportedRecordingListApi>(getSessionRecordingExportsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getSessionRecordingExportsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/session_recording_exports/`+}++/**+ * @summary Trigger a session recording export+ */+export const sessionRecordingExportsCreate = async (+ projectId: string,+ exportedRecordingCreateApi: ExportedRecordingCreateApi,+ options?: RequestInit+): Promise<ExportedRecordingApi> => {+ return apiMutator<ExportedRecordingApi>(getSessionRecordingExportsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(exportedRecordingCreateApi),+ })+}++export const getSessionRecordingExportsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/session_recording_exports/${id}/`+}++export const sessionRecordingExportsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ExportedRecordingApi> => {+ return apiMutator<ExportedRecordingApi>(getSessionRecordingExportsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+export const getSessionRecordingPlaylistsListUrl = (projectId: string,params?: SessionRecordingPlaylistsListParamsdiff --git a/products/replay/frontend/generated/api.zod.ts b/products/replay/frontend/generated/api.zod.tsindex ff22bf1e2c1e..4ca09f9b0195 100644--- a/products/replay/frontend/generated/api.zod.ts+++ b/products/replay/frontend/generated/api.zod.ts@@ -9,6 +9,19 @@*/import * as zod from 'zod'+/**+ * @summary Trigger a session recording export+ */+export const sessionRecordingExportsCreateBodySessionIdMax = 200++export const SessionRecordingExportsCreateBody = /* @__PURE__ */ zod.object({+ session_id: zod+ .string()+ .max(sessionRecordingExportsCreateBodySessionIdMax)+ .describe('The `$session_id` of the recording to export.'),+ reason: zod.string().describe('Why this recording is being exported. Recorded for audit purposes.'),+})+export const sessionRecordingPlaylistsCreateBodyNameMax = 400export const sessionRecordingPlaylistsCreateBodyDerivedNameMax = 400diff --git a/products/replay/mcp/tools.yaml b/products/replay/mcp/tools.yamlindex d505e52916f2..da79be6d015b 100644--- a/products/replay/mcp/tools.yaml+++ b/products/replay/mcp/tools.yaml@@ -31,6 +31,55 @@ tools:description: >Delete a session recording by ID. This permanently removes the recording data. Use for privacy or complianceworkflows.+ session-recording-export-create:+ operation: session_recording_exports_create+ enabled: true+ scopes:+ - session_recording:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Export session recording+ description: >+ Trigger an export of a single session recording's data to a downloadable archive. Requires staff access.+ Provide the `session_id` and a `reason` (recorded for audit). Returns an export job whose `status` starts as+ `pending`; poll `session-recording-export-get` with the returned `id` until `status` is `complete`, then+ read `export_location` for the archive's storage path. The export gathers recording blocks plus related+ ClickHouse metadata, so completion is not instant.+ feature_flag: replay-admin-export+ session-recording-export-get:+ operation: session_recording_exports_retrieve+ enabled: true+ scopes:+ - session_recording:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ enrich_url: '{id}'+ title: Get session recording export+ description: >+ Get a single session recording export job by `id`. Requires staff access. Returns its `status`+ (pending/running/complete/failed), `export_location` (the archive's storage path, populated once `status` is+ `complete`), any `error_message`, and `is_expired` (exports older than 7 days may have been purged). Use+ after `session-recording-export-create` to poll for completion.+ feature_flag: replay-admin-export+ session-recording-exports-list:+ operation: session_recording_exports_list+ enabled: true+ scopes:+ - session_recording:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List session recording exports+ description: >+ List past session recording export jobs for the project, newest first. Requires staff access. Use to find an+ export's `id` and `status` before reading its download location via `session-recording-export-get`.+ feature_flag: replay-admin-exportsession-recording-get:operation: session_recordings_retrieveenabled: truediff --git a/products/replay/package.json b/products/replay/package.jsonindex 58ebdedd00e9..a633124d00f9 100644--- a/products/replay/package.json+++ b/products/replay/package.json@@ -1,7 +1,7 @@{"name": "@posthog/products-replay","scripts": {- "backend:test": "echo 'No backend tests'"+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/test -v --tb=short"},"dependencies": {"kea": "catalog:",diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex a1e9b750e5e6..9797c717566f 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -5877,6 +5877,51 @@"readOnlyHint": false}},+ "session-recording-export-create": {+ "description": "Trigger an export of a single session recording's data to a downloadable archive. Requires staff access. Provide the `session_id` and a `reason` (recorded for audit). Returns an export job whose `status` starts as `pending`; poll `session-recording-export-get` with the returned `id` until `status` is `complete`, then read `export_location` for the archive's storage path. The export gathers recording blocks plus related ClickHouse metadata, so completion is not instant.",+ "category": "Session replays",+ "feature": "replay",+ "summary": "Export session recording",+ "title": "Export session recording",+ "required_scopes": ["session_recording:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "replay-admin-export"+ },+ "session-recording-export-get": {+ "description": "Get a single session recording export job by `id`. Requires staff access. Returns its `status` (pending/running/complete/failed), `export_location` (the archive's storage path, populated once `status` is `complete`), any `error_message`, and `is_expired` (exports older than 7 days may have been purged). Use after `session-recording-export-create` to poll for completion.",+ "category": "Session replays",+ "feature": "replay",+ "summary": "Get session recording export",+ "title": "Get session recording export",+ "required_scopes": ["session_recording:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "replay-admin-export"+ },+ "session-recording-exports-list": {+ "description": "List past session recording export jobs for the project, newest first. Requires staff access. Use to find an export's `id` and `status` before reading its download location via `session-recording-export-get`.",+ "category": "Session replays",+ "feature": "replay",+ "summary": "List session recording exports",+ "title": "List session recording exports",+ "required_scopes": ["session_recording:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "replay-admin-export"+ },"session-recording-get": {"description": "Get a specific session recording by ID. Returns full recording metadata including duration, interaction counts, console log counts, person info, and viewing status. Session recordings are reachable from events, errors, and persons via the `$session_id` property on events. Any `$session_id` value from an event can be passed as the `id` parameter to this tool. Note: a `$session_id` on an event does not guarantee a recording exists — session replay may not be enabled for that project or session. A 404 means no recording was captured. If the user wants to understand what happened without watching the recording, check `vision-observations-list` for an existing Replay Vision AI summary, or run a summarizer scanner via `vision-scanners-scan-session` (see the investigating-replay skill; scanning is slow). If a recording is missing (404) or the user asks why recordings aren't being captured, diagnose with `execute-sql`: query `$recording_status`, `$session_recording_start_reason`, `$replay_sample_rate`, and `$sdk_debug_recording_script_not_loaded` from the events table (filter by `$session_id` for a specific session, or sample recent events for project-wide issues).","category": "Session replays",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex aa03148ea65c..0a3bf336abcd 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -6356,6 +6356,51 @@"readOnlyHint": false}},+ "session-recording-export-create": {+ "description": "Trigger an export of a single session recording's data to a downloadable archive. Requires staff access. Provide the `session_id` and a `reason` (recorded for audit). Returns an export job whose `status` starts as `pending`; poll `session-recording-export-get` with the returned `id` until `status` is `complete`, then read `export_location` for the archive's storage path. The export gathers recording blocks plus related ClickHouse metadata, so completion is not instant.",+ "category": "Session replays",+ "feature": "replay",+ "summary": "Export session recording",+ "title": "Export session recording",+ "required_scopes": ["session_recording:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "replay-admin-export"+ },+ "session-recording-export-get": {+ "description": "Get a single session recording export job by `id`. Requires staff access. Returns its `status` (pending/running/complete/failed), `export_location` (the archive's storage path, populated once `status` is `complete`), any `error_message`, and `is_expired` (exports older than 7 days may have been purged). Use after `session-recording-export-create` to poll for completion.",+ "category": "Session replays",+ "feature": "replay",+ "summary": "Get session recording export",+ "title": "Get session recording export",+ "required_scopes": ["session_recording:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "replay-admin-export"+ },+ "session-recording-exports-list": {+ "description": "List past session recording export jobs for the project, newest first. Requires staff access. Use to find an export's `id` and `status` before reading its download location via `session-recording-export-get`.",+ "category": "Session replays",+ "feature": "replay",+ "summary": "List session recording exports",+ "title": "List session recording exports",+ "required_scopes": ["session_recording:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "replay-admin-export"+ },"session-recording-get": {"description": "Get a specific session recording by ID. Returns full recording metadata including duration, interaction counts, console log counts, person info, and viewing status. Session recordings are reachable from events, errors, and persons via the `$session_id` property on events. Any `$session_id` value from an event can be passed as the `id` parameter to this tool. Note: a `$session_id` on an event does not guarantee a recording exists — session replay may not be enabled for that project or session. A 404 means no recording was captured. If the user wants to understand what happened without watching the recording, check `vision-observations-list` for an existing Replay Vision AI summary, or run a summarizer scanner via `vision-scanners-scan-session` (see the investigating-replay skill; scanning is slow). If a recording is missing (404) or the user asks why recordings aren't being captured, diagnose with `execute-sql`: query `$recording_status`, `$session_recording_start_reason`, `$replay_sample_rate`, and `$sdk_debug_recording_script_not_loaded` from the events table (filter by `$session_id` for a specific session, or sample recent events for project-wide issues).","category": "Session replays",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4e5811389656..dd556ca4fc96 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -20990,6 +20990,64 @@ export namespace Schemas {readonly exception: string | null;}+ /**+ * * `pending` - Pending+ * * `running` - Running+ * * `complete` - Complete+ * * `failed` - Failed+ */+ export type ExportedRecordingStatusEnum = typeof ExportedRecordingStatusEnum[keyof typeof ExportedRecordingStatusEnum];+++ export const ExportedRecordingStatusEnum = {+ Pending: 'pending',+ Running: 'running',+ Complete: 'complete',+ Failed: 'failed',+ } as const;++ export interface ExportedRecording {+ /** Unique identifier for this export job. */+ readonly id: string;+ /** The `$session_id` of the recording being exported. */+ readonly session_id: string;+ /** Human-provided justification for the export, kept for audit purposes. */+ readonly reason: string;+ /** Lifecycle status of the export: pending, running, complete, or failed.+ *+ * * `pending` - Pending+ * * `running` - Running+ * * `complete` - Complete+ * * `failed` - Failed */+ readonly status: ExportedRecordingStatusEnum;+ /**+ * Storage location of the exported data once the job completes; null until status is complete.+ * @nullable+ */+ readonly export_location: string | null;+ /**+ * Failure detail when status is failed; null otherwise.+ * @nullable+ */+ readonly error_message: string | null;+ /** When the export was requested. */+ readonly created_at: string;+ /** The user who triggered the export. */+ readonly created_by: UserBasic;+ /** True when the export is older than 7 days and its downloadable data may have been purged. */+ readonly is_expired: boolean;+ }++ export interface ExportedRecordingCreate {+ /**+ * The `$session_id` of the recording to export.+ * @maxLength 200+ */+ session_id: string;+ /** Why this recording is being exported. Recorded for audit purposes. */+ reason: string;+ }+/*** @nullable*/@@ -29679,6 +29737,15 @@ export namespace Schemas {results: ExportedAsset[];}+ export interface PaginatedExportedRecordingList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: ExportedRecording[];+ }+export interface PaginatedExternalDataSchemaList {count: number;/** @nullable */@@ -60971,6 +61038,17 @@ export namespace Schemas {offset?: number;};+ export type SessionRecordingExportsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type SessionRecordingExternalReferencesListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/generated/replay/api.ts b/services/mcp/src/generated/replay/api.tsindex 14198c416695..da105d811839 100644--- a/services/mcp/src/generated/replay/api.ts+++ b/services/mcp/src/generated/replay/api.ts@@ -3,11 +3,54 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 8 enabled ops+ * PostHog API - MCP 11 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'+export const SessionRecordingExportsListParams = /* @__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 SessionRecordingExportsListQueryParams = /* @__PURE__ */ zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+})++/**+ * @summary Trigger a session recording export+ */+export const SessionRecordingExportsCreateParams = /* @__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 sessionRecordingExportsCreateBodySessionIdMax = 200++export const SessionRecordingExportsCreateBody = /* @__PURE__ */ zod.object({+ session_id: zod+ .string()+ .max(sessionRecordingExportsCreateBodySessionIdMax)+ .describe('The `$session_id` of the recording to export.'),+ reason: zod.string().describe('Why this recording is being exported. Recorded for audit purposes.'),+})++export const SessionRecordingExportsRetrieveParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this exported recording.'),+ 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/."+ ),+})+/*** Override list to include synthetic playlists.*diff --git a/services/mcp/src/tools/generated/replay.ts b/services/mcp/src/tools/generated/replay.tsindex 798242ab3e93..aea615cbd608 100644--- a/services/mcp/src/tools/generated/replay.ts+++ b/services/mcp/src/tools/generated/replay.ts@@ -3,6 +3,9 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import {+ SessionRecordingExportsCreateBody,+ SessionRecordingExportsListQueryParams,+ SessionRecordingExportsRetrieveParams,SessionRecordingPlaylistsCreateBody,SessionRecordingPlaylistsListQueryParams,SessionRecordingPlaylistsPartialUpdateBody,@@ -33,6 +36,72 @@ const sessionRecordingDelete = (): ToolBase<typeof SessionRecordingDeleteSchema,},})+const SessionRecordingExportCreateSchema = SessionRecordingExportsCreateBody++const sessionRecordingExportCreate = (): ToolBase<+ typeof SessionRecordingExportCreateSchema,+ Schemas.ExportedRecording+> => ({+ name: 'session-recording-export-create',+ schema: SessionRecordingExportCreateSchema,+ handler: async (context: Context, params: z.infer<typeof SessionRecordingExportCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.session_id !== undefined) {+ body['session_id'] = params.session_id+ }+ if (params.reason !== undefined) {+ body['reason'] = params.reason+ }+ const result = await context.api.request<Schemas.ExportedRecording>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/session_recording_exports/`,+ body,+ })+ return result+ },+})++const SessionRecordingExportGetSchema = SessionRecordingExportsRetrieveParams.omit({ project_id: true })++const sessionRecordingExportGet = (): ToolBase<+ typeof SessionRecordingExportGetSchema,+ WithPostHogUrl<Schemas.ExportedRecording>+> => ({+ name: 'session-recording-export-get',+ schema: SessionRecordingExportGetSchema,+ handler: async (context: Context, params: z.infer<typeof SessionRecordingExportGetSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.ExportedRecording>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/session_recording_exports/${encodeURIComponent(String(params.id))}/`,+ })+ return await withPostHogUrl(context, result, `/replay/${result.id}`)+ },+})++const SessionRecordingExportsListSchema = SessionRecordingExportsListQueryParams++const sessionRecordingExportsList = (): ToolBase<+ typeof SessionRecordingExportsListSchema,+ WithPostHogUrl<Schemas.PaginatedExportedRecordingList>+> => ({+ name: 'session-recording-exports-list',+ schema: SessionRecordingExportsListSchema,+ handler: async (context: Context, params: z.infer<typeof SessionRecordingExportsListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedExportedRecordingList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/session_recording_exports/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ return await withPostHogUrl(context, result, '/replay')+ },+})+const SessionRecordingGetSchema = SessionRecordingsRetrieveParams.omit({ project_id: true })const sessionRecordingGet = (): ToolBase<typeof SessionRecordingGetSchema, WithPostHogUrl<Schemas.SessionRecording>> =>@@ -664,6 +733,9 @@ const AssistantRecordingsQuery = z.object({export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'session-recording-delete': sessionRecordingDelete,+ 'session-recording-export-create': sessionRecordingExportCreate,+ 'session-recording-export-get': sessionRecordingExportGet,+ 'session-recording-exports-list': sessionRecordingExportsList,'session-recording-get': sessionRecordingGet,'session-recording-playlist-create': sessionRecordingPlaylistCreate,'session-recording-playlist-get': sessionRecordingPlaylistGet,diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex f76b8fc37e81..5e9077e32d31 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -751,9 +751,10 @@ describe('Tool Filtering - Feature Flags', () => {'field-notes','mcp-analytics','metrics',+ 'replay-admin-export',]))- expect(flags).toHaveLength(19)+ expect(flags).toHaveLength(20)})// Exercise the real predicate (toolPassesFlagGate) over hand-rolled entries