: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 bulk delete as an MCP tool (#68469)
Tue Haulundc5ba8d40cfc9
diff --git a/nodejs/src/session-replay/recording-api/schemas.ts b/nodejs/src/session-replay/recording-api/schemas.tsindex ba17b9fee28c..910df3e413aa 100644--- a/nodejs/src/session-replay/recording-api/schemas.ts+++ b/nodejs/src/session-replay/recording-api/schemas.ts@@ -27,6 +27,7 @@ export const TeamParamsSchema = z.object({team_id: positiveIntString('team_id'),})+// Mirrored by MAX_RECORDINGS_PER_BULK_DELETE in posthog/session_recordings/session_recording_api.py — keep in sync.const MAX_DELETE_SESSION_IDS = 100// Body schema for delete requestsdiff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.pyindex 077f3ced94be..4cd0ab26712c 100644--- a/posthog/session_recordings/session_recording_api.py+++ b/posthog/session_recordings/session_recording_api.py@@ -135,6 +135,8 @@ from .queries.combine_session_ids_for_filtering import combine_session_id_filterfrom .queries.sub_queries.events_subquery import ReplayFiltersEventsSubQueryMAX_RECORDINGS_PER_BULK_ACTION = 20+# Matches recording-api's MAX_DELETE_SESSION_IDS — one downstream call per delete batch.+MAX_RECORDINGS_PER_BULK_DELETE = 100SNAPSHOTS_BY_PERSONAL_API_KEY_COUNTER = Counter("snapshots_personal_api_key_counter",@@ -541,6 +543,36 @@ class SessionRecordingSnapshotsRequestSerializer(serializers.Serializer):return data+# Schema-only; enforcement stays in the view to preserve the pre-existing error contract.+class SessionRecordingBulkDeleteRequestSerializer(serializers.Serializer):+ session_recording_ids = serializers.ListField(+ child=serializers.CharField(),+ min_length=1,+ max_length=MAX_RECORDINGS_PER_BULK_DELETE,+ help_text=f"Session IDs of the recordings to delete (max {MAX_RECORDINGS_PER_BULK_DELETE} per call).",+ )+ date_from = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Earliest start time of the recordings, as an ISO date or a relative offset like '-30d'. "+ "Providing this narrows the lookup and speeds up the request; defaults to the project's "+ "recording retention period.",+ )+++class SessionRecordingBulkDeleteResponseSerializer(serializers.Serializer):+ success = serializers.BooleanField(+ help_text="True when no deletion attempt failed. IDs that were not found, or that the caller lacks edit "+ "access to, are skipped rather than failed — compare deleted_count to total_requested to detect skips."+ )+ deleted_count = serializers.IntegerField(help_text="Number of recordings that were deleted.")+ total_requested = serializers.IntegerField(help_text="Number of session recording IDs in the request.")+ failed_ids = serializers.ListField(+ child=serializers.CharField(),+ help_text="Session IDs that were found but could not be deleted. These can be retried.",+ )++def list_recordings_response(listing_result: tuple[list[SessionRecording], bool, str, str | None], context: dict[str, Any]) -> Response:@@ -1101,14 +1133,16 @@ class SessionRecordingViewSet(return Response(status=204)- @extend_schema(exclude=True)+ @extend_schema(+ description="Delete a batch of session recordings by session ID. Deletion is permanent and cannot be undone. "+ "IDs that don't match an existing recording are skipped and counted in `total_requested` but not "+ "`deleted_count`.",+ request=SessionRecordingBulkDeleteRequestSerializer,+ responses={200: SessionRecordingBulkDeleteResponseSerializer},+ )@action(methods=["POST"], detail=False, url_path="bulk_delete")def bulk_delete(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:- """Bulk delete recordings via recording-api (crypto-shredding).-- Accepts optional date_from parameter to optimize ClickHouse query performance by limiting the search range.- If not provided, defaults to the team's retention period to ensure all recordings can be found.- """+ """Bulk delete recordings via recording-api (crypto-shredding)."""session_recording_ids = request.data.get("session_recording_ids", [])date_from = request.data.get("date_from", None)@@ -1116,9 +1150,9 @@ class SessionRecordingViewSet(if not session_recording_ids or not isinstance(session_recording_ids, list):raise exceptions.ValidationError("session_recording_ids must be provided as a non-empty array")- if len(session_recording_ids) > MAX_RECORDINGS_PER_BULK_ACTION:+ if len(session_recording_ids) > MAX_RECORDINGS_PER_BULK_DELETE:raise exceptions.ValidationError(- f"Cannot process more than {MAX_RECORDINGS_PER_BULK_ACTION} recordings at once"+ f"Cannot process more than {MAX_RECORDINGS_PER_BULK_DELETE} recordings at once")if not date_from:@@ -1130,6 +1164,8 @@ class SessionRecordingViewSet("date_from": date_from,"date_to": None,"kind": "RecordingsQuery",+ # Without an explicit limit the query defaults to 50 rows, silently truncating larger batches.+ "limit": len(session_recording_ids),}query = RecordingsQuery.model_validate(query_data)recordings, _, _, _ = list_recordings_from_query(query, None, self.team)diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.pyindex 2fefc40b8760..12b0d9b0a749 100644--- a/posthog/session_recordings/test/test_session_recordings.py+++ b/posthog/session_recordings/test/test_session_recordings.py@@ -1454,8 +1454,8 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)),("too_many_recordings",- {"session_recording_ids": [f"bulk_delete_test_{i}" for i in range(21)]},- "Cannot process more than 20 recordings at once",+ {"session_recording_ids": [f"bulk_delete_test_{i}" for i in range(101)]},+ "Cannot process more than 100 recordings at once",),])@@ -1500,6 +1500,29 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)called_ids = sorted(mock_delete_via_recording_api.call_args[0][0])assert called_ids == sorted(session_ids)+ @patch(+ "posthog.session_recordings.session_recording_api.SessionRecordingViewSet._delete_via_recording_api",+ return_value=[],+ )+ def test_bulk_delete_batch_larger_than_default_query_limit(self, mock_delete_via_recording_api):+ create_person(team=self.team, distinct_ids=["user1"], properties={"email": "[email protected]"})++ base_time = now() - relativedelta(days=1)++ # More than the recordings query's default 50-row limit, to catch silent truncation+ session_ids = [f"bulk_delete_large_{i}" for i in range(51)]+ for session_id in session_ids:+ self.produce_replay_summary("user1", session_id, base_time)++ response = self.client.post(+ f"/api/projects/{self.team.id}/session_recordings/bulk_delete",+ {"session_recording_ids": session_ids},+ )++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["deleted_count"] == 51+ assert sorted(mock_delete_via_recording_api.call_args[0][0]) == sorted(session_ids)+def test_bulk_delete_nonexistent_recordings(self):session_ids = ["nonexistent_1", "nonexistent_2"]diff --git a/products/replay/frontend/generated/api.schemas.ts b/products/replay/frontend/generated/api.schemas.tsindex f5d65a1c1979..5b056f619663 100644--- a/products/replay/frontend/generated/api.schemas.ts+++ b/products/replay/frontend/generated/api.schemas.ts@@ -311,6 +311,31 @@ export interface PatchedSessionRecordingApi {readonly matches_filters?: boolean}+export interface SessionRecordingBulkDeleteRequestApi {+ /**+ * Session IDs of the recordings to delete (max 100 per call).+ * @minItems 1+ * @maxItems 100+ */+ session_recording_ids: string[]+ /**+ * Earliest start time of the recordings, as an ISO date or a relative offset like '-30d'. Providing this narrows the lookup and speeds up the request; defaults to the project's recording retention period.+ * @nullable+ */+ date_from?: string | null+}++export interface SessionRecordingBulkDeleteResponseApi {+ /** True when no deletion attempt failed. IDs that were not found, or that the caller lacks edit access to, are skipped rather than failed — compare deleted_count to total_requested to detect skips. */+ success: boolean+ /** Number of recordings that were deleted. */+ deleted_count: number+ /** Number of session recording IDs in the request. */+ total_requested: number+ /** Session IDs that were found but could not be deleted. These can be retried. */+ failed_ids: string[]+}+export interface SessionSummariesApi {/*** List of session IDs to summarize (max 300)diff --git a/products/replay/frontend/generated/api.ts b/products/replay/frontend/generated/api.tsindex ef9a202826af..846d86ff63a9 100644--- a/products/replay/frontend/generated/api.ts+++ b/products/replay/frontend/generated/api.ts@@ -15,6 +15,8 @@ import type {PatchedSessionRecordingApi,PatchedSessionRecordingPlaylistApi,SessionRecordingApi,+ SessionRecordingBulkDeleteRequestApi,+ SessionRecordingBulkDeleteResponseApi,SessionRecordingPlaylistApi,SessionRecordingPlaylistsListParams,SessionRecordingsListParams,@@ -315,6 +317,26 @@ export const sessionRecordingsDestroy = async (projectId: string, id: string, op})}+export const getSessionRecordingsBulkDeleteCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/session_recordings/bulk_delete/`+}++/**+ * Delete a batch of session recordings by session ID. Deletion is permanent and cannot be undone. IDs that don't match an existing recording are skipped and counted in `total_requested` but not `deleted_count`.+ */+export const sessionRecordingsBulkDeleteCreate = async (+ projectId: string,+ sessionRecordingBulkDeleteRequestApi: SessionRecordingBulkDeleteRequestApi,+ options?: RequestInit+): Promise<SessionRecordingBulkDeleteResponseApi> => {+ return apiMutator<SessionRecordingBulkDeleteResponseApi>(getSessionRecordingsBulkDeleteCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(sessionRecordingBulkDeleteRequestApi),+ })+}+export const getCreateSessionSummariesIndividuallyUrl = (projectId: string) => {return `/api/projects/${projectId}/session_summaries/create_session_summaries_individually/`}diff --git a/products/replay/frontend/generated/api.zod.ts b/products/replay/frontend/generated/api.zod.tsindex ff22bf1e2c1e..f49b36f03fb7 100644--- a/products/replay/frontend/generated/api.zod.ts+++ b/products/replay/frontend/generated/api.zod.ts@@ -177,6 +177,25 @@ export const SessionRecordingsPartialUpdateBody = /* @__PURE__ */ zod.object({.optional(),})+/**+ * Delete a batch of session recordings by session ID. Deletion is permanent and cannot be undone. IDs that don't match an existing recording are skipped and counted in `total_requested` but not `deleted_count`.+ */+export const sessionRecordingsBulkDeleteCreateBodySessionRecordingIdsMax = 100++export const SessionRecordingsBulkDeleteCreateBody = /* @__PURE__ */ zod.object({+ session_recording_ids: zod+ .array(zod.string())+ .min(1)+ .max(sessionRecordingsBulkDeleteCreateBodySessionRecordingIdsMax)+ .describe('Session IDs of the recordings to delete (max 100 per call).'),+ date_from: zod+ .string()+ .nullish()+ .describe(+ "Earliest start time of the recordings, as an ISO date or a relative offset like '-30d'. Providing this narrows the lookup and speeds up the request; defaults to the project's recording retention period."+ ),+})+/*** Generate AI individual summary for each session, without grouping.*/diff --git a/products/replay/mcp/tools.yaml b/products/replay/mcp/tools.yamlindex d505e52916f2..e27d85b2ace4 100644--- a/products/replay/mcp/tools.yaml+++ b/products/replay/mcp/tools.yaml@@ -18,6 +18,23 @@ tools:create-session-summaries-individually:operation: create_session_summaries_individuallyenabled: false+ session-recording-bulk-delete:+ operation: session_recordings_bulk_delete_create+ enabled: true+ scopes:+ - session_recording:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Bulk delete session recordings+ description: >+ Delete a batch of session recordings by session ID, up to 100 per call. Deletion is permanent and cannot be+ undone — confirm with the user before deleting. Prefer this over `session-recording-delete` whenever more+ than one recording needs deleting: find the target IDs with `query-session-recordings-list`, then delete in+ batches. Pass `date_from` (e.g. '-30d') when the recordings' age is known — it makes the lookup much faster.+ IDs with no matching recording are skipped, so a `deleted_count` below `total_requested` is normal when some+ recordings were already deleted or never existed.session-recording-delete:operation: session_recordings_destroyenabled: true@@ -30,7 +47,8 @@ tools:title: Delete session recordingdescription: >Delete a session recording by ID. This permanently removes the recording data. Use for privacy or compliance- workflows.+ workflows. To delete more than one recording, use `session-recording-bulk-delete` instead of calling this+ repeatedly.session-recording-get:operation: session_recordings_retrieveenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 9ce18040a09e..4f42ebafb1e2 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -6734,8 +6734,22 @@"readOnlyHint": false}},+ "session-recording-bulk-delete": {+ "description": "Delete a batch of session recordings by session ID, up to 100 per call. Deletion is permanent and cannot be undone — confirm with the user before deleting. Prefer this over `session-recording-delete` whenever more than one recording needs deleting: find the target IDs with `query-session-recordings-list`, then delete in batches. Pass `date_from` (e.g. '-30d') when the recordings' age is known — it makes the lookup much faster. IDs with no matching recording are skipped, so a `deleted_count` below `total_requested` is normal when some recordings were already deleted or never existed.",+ "category": "Session replays",+ "feature": "replay",+ "summary": "Bulk delete session recordings",+ "title": "Bulk delete session recordings",+ "required_scopes": ["session_recording:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"session-recording-delete": {- "description": "Delete a session recording by ID. This permanently removes the recording data. Use for privacy or compliance workflows.",+ "description": "Delete a session recording by ID. This permanently removes the recording data. Use for privacy or compliance workflows. To delete more than one recording, use `session-recording-bulk-delete` instead of calling this repeatedly.","category": "Session replays","feature": "replay","summary": "Delete session recording",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 3c3cfe269249..0846429971bc 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -7229,8 +7229,22 @@"readOnlyHint": false}},+ "session-recording-bulk-delete": {+ "description": "Delete a batch of session recordings by session ID, up to 100 per call. Deletion is permanent and cannot be undone — confirm with the user before deleting. Prefer this over `session-recording-delete` whenever more than one recording needs deleting: find the target IDs with `query-session-recordings-list`, then delete in batches. Pass `date_from` (e.g. '-30d') when the recordings' age is known — it makes the lookup much faster. IDs with no matching recording are skipped, so a `deleted_count` below `total_requested` is normal when some recordings were already deleted or never existed.",+ "category": "Session replays",+ "feature": "replay",+ "summary": "Bulk delete session recordings",+ "title": "Bulk delete session recordings",+ "required_scopes": ["session_recording:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"session-recording-delete": {- "description": "Delete a session recording by ID. This permanently removes the recording data. Use for privacy or compliance workflows.",+ "description": "Delete a session recording by ID. This permanently removes the recording data. Use for privacy or compliance workflows. To delete more than one recording, use `session-recording-bulk-delete` instead of calling this repeatedly.","category": "Session replays","feature": "replay","summary": "Delete session recording",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 02f89f808b7f..239c1100c1b5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -48540,6 +48540,31 @@ export namespace Schemas {readonly team: number;}+ export interface SessionRecordingBulkDeleteRequest {+ /**+ * Session IDs of the recordings to delete (max 100 per call).+ * @minItems 1+ * @maxItems 100+ */+ session_recording_ids: string[];+ /**+ * Earliest start time of the recordings, as an ISO date or a relative offset like '-30d'. Providing this narrows the lookup and speeds up the request; defaults to the project's recording retention period.+ * @nullable+ */+ date_from?: string | null;+ }++ export interface SessionRecordingBulkDeleteResponse {+ /** True when no deletion attempt failed. IDs that were not found, or that the caller lacks edit access to, are skipped rather than failed — compare deleted_count to total_requested to detect skips. */+ success: boolean;+ /** Number of recordings that were deleted. */+ deleted_count: number;+ /** Number of session recording IDs in the request. */+ total_requested: number;+ /** Session IDs that were found but could not be deleted. These can be retried. */+ failed_ids: string[];+ }+export type SessionReplayListWidgetCatalogEntryOpenApiWidgetType = typeof SessionReplayListWidgetCatalogEntryOpenApiWidgetType[keyof typeof SessionReplayListWidgetCatalogEntryOpenApiWidgetType];diff --git a/services/mcp/src/generated/replay/api.ts b/services/mcp/src/generated/replay/api.tsindex 14198c416695..a66ab6223a6d 100644--- a/services/mcp/src/generated/replay/api.ts+++ b/services/mcp/src/generated/replay/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 8 enabled ops+ * PostHog API - MCP 9 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -129,6 +129,33 @@ export const SessionRecordingsDestroyParams = /* @__PURE__ */ zod.object({),})+/**+ * Delete a batch of session recordings by session ID. Deletion is permanent and cannot be undone. IDs that don't match an existing recording are skipped and counted in `total_requested` but not `deleted_count`.+ */+export const SessionRecordingsBulkDeleteCreateParams = /* @__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 sessionRecordingsBulkDeleteCreateBodySessionRecordingIdsMax = 100++export const SessionRecordingsBulkDeleteCreateBody = /* @__PURE__ */ zod.object({+ session_recording_ids: zod+ .array(zod.string())+ .min(1)+ .max(sessionRecordingsBulkDeleteCreateBodySessionRecordingIdsMax)+ .describe('Session IDs of the recordings to delete (max 100 per call).'),+ date_from: zod+ .string()+ .nullish()+ .describe(+ "Earliest start time of the recordings, as an ISO date or a relative offset like '-30d'. Providing this narrows the lookup and speeds up the request; defaults to the project's recording retention period."+ ),+})+/*** List stored AI-generated session summaries for the team, one row per session (latest summary kept). Use to discover which sessions have been summarized and to filter for sessions with specific problems — `has_exceptions=true`, `outcome=failure`, or a custom `session_ids` narrowing. Returns lightweight rows without the full summary JSON; use the retrieve endpoint for the per-segment / per-action detail.*/diff --git a/services/mcp/src/tools/generated/replay.ts b/services/mcp/src/tools/generated/replay.tsindex 798242ab3e93..cb0363b9fa7a 100644--- a/services/mcp/src/tools/generated/replay.ts+++ b/services/mcp/src/tools/generated/replay.ts@@ -8,6 +8,7 @@ import {SessionRecordingPlaylistsPartialUpdateBody,SessionRecordingPlaylistsPartialUpdateParams,SessionRecordingPlaylistsRetrieveParams,+ SessionRecordingsBulkDeleteCreateBody,SessionRecordingsDestroyParams,SessionRecordingsRetrieveParams,SingleSessionSummariesListQueryParams,@@ -18,6 +19,32 @@ import { createQueryWrapper } from '@/tools/query-wrapper-factory'import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'+const SessionRecordingBulkDeleteSchema = SessionRecordingsBulkDeleteCreateBody++const sessionRecordingBulkDelete = (): ToolBase<+ typeof SessionRecordingBulkDeleteSchema,+ Schemas.SessionRecordingBulkDeleteResponse+> => ({+ name: 'session-recording-bulk-delete',+ schema: SessionRecordingBulkDeleteSchema,+ handler: async (context: Context, params: z.infer<typeof SessionRecordingBulkDeleteSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.session_recording_ids !== undefined) {+ body['session_recording_ids'] = params.session_recording_ids+ }+ if (params.date_from !== undefined) {+ body['date_from'] = params.date_from+ }+ const result = await context.api.request<Schemas.SessionRecordingBulkDeleteResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/session_recordings/bulk_delete/`,+ body,+ })+ return result+ },+})+const SessionRecordingDeleteSchema = SessionRecordingsDestroyParams.omit({ project_id: true })const sessionRecordingDelete = (): ToolBase<typeof SessionRecordingDeleteSchema, unknown> => ({@@ -663,6 +690,7 @@ const AssistantRecordingsQuery = z.object({})export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'session-recording-bulk-delete': sessionRecordingBulkDelete,'session-recording-delete': sessionRecordingDelete,'session-recording-get': sessionRecordingGet,'session-recording-playlist-create': sessionRecordingPlaylistCreate,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/session-recording-bulk-delete.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/session-recording-bulk-delete.jsonnew file mode 100644index 000000000000..45816400e0c7--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/session-recording-bulk-delete.json@@ -0,0 +1,27 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "date_from": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Earliest start time of the recordings, as an ISO date or a relative offset like '-30d'. Providing this narrows the lookup and speeds up the request; defaults to the project's recording retention period."+ },+ "session_recording_ids": {+ "description": "Session IDs of the recordings to delete (max 100 per call).",+ "items": {+ "type": "string"+ },+ "maxItems": 100,+ "minItems": 1,+ "type": "array"+ }+ },+ "required": ["session_recording_ids"],+ "type": "object"+}