Skip to content

: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.

feat(replay): expose stored session summaries via API and MCP tools (#60197)

Andrew Maguire0dca5cce0d9f
diff --git a/ee/api/session_summaries.py b/ee/api/session_summaries.py
index 00d805c83bb6..51da05dae004 100644
--- a/ee/api/session_summaries.py
+++ b/ee/api/session_summaries.py
@@ -1,6 +1,7 @@
import os
import re
import json
+import uuid
import asyncio
from collections.abc import AsyncGenerator
from datetime import datetime
@@ -8,12 +9,14 @@ from typing import Any, cast
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
-from django.db.models import Func, IntegerField, QuerySet
+from django.db.models import Func, IntegerField, QuerySet, Subquery
+from django.db.models.fields.json import KeyTransform
from django.http import StreamingHttpResponse
import structlog
from asgiref.sync import async_to_sync
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field
from loginas.utils import is_impersonated_session
from rest_framework import exceptions, serializers, status, viewsets
from rest_framework.decorators import action
@@ -34,6 +37,7 @@ from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.utils import UUID
from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle
from posthog.renderers import ServerSentEventRenderer
+from posthog.session_recordings.models.session_recording import SessionRecording
from posthog.temporal.session_replay.session_summary.workflow import execute_summarize_session
from posthog.temporal.session_replay.session_summary_group.types import FailedSessionInfo, SessionSummaryStreamUpdate
from posthog.temporal.session_replay.session_summary_group.workflow import execute_summarize_session_group
@@ -54,7 +58,7 @@ from ee.hogai.session_summaries.tracking import (
)
from ee.hogai.session_summaries.utils import logging_session_ids
from ee.hogai.utils.aio import async_to_sync as async_generator_to_sync
-from ee.models.session_summaries import SessionGroupSummary
+from ee.models.session_summaries import SessionGroupSummary, SingleSessionSummary
from ee.models.team_session_summaries_config import (
CUSTOM_TAG_DESCRIPTION_MAX_LENGTH,
CUSTOM_TAG_NAME_MAX_LENGTH,
@@ -81,6 +85,30 @@ class SessionSummariesSerializer(serializers.Serializer):
_PRODUCT_CONTEXT_WRAPPER_TAG_RE = re.compile(r"</?\s*product_context\b[^>]*>", re.IGNORECASE)
_CUSTOM_TAG_NAME_RE = re.compile(rf"^[a-z0-9_]{{1,{CUSTOM_TAG_NAME_MAX_LENGTH}}}$")
_WHITESPACE_RUN_RE = re.compile(r"\s+")
+# Relative-date shorthand accepted by `relative_date_parse` (e.g. `-7d`, `-1dStart`). Its own regex is
+# loose enough that free text like `yesterday` matches on a stray `y` and silently parses to a wrong
+# instant, so the list endpoint validates against this stricter anchored form before parsing.
+_RELATIVE_DATE_RE = re.compile(r"^-?\d+[hdwmqsy](?:Start|End)?$", re.IGNORECASE)
+
+
+def _validate_date_param(field: str, value: str) -> None:
+ """Reject values `relative_date_parse` can't meaningfully parse, so a bad query param is a 400
+ rather than a silently-wrong (or empty) page. Accepts strict relative shorthand or an ISO date."""
+ if _RELATIVE_DATE_RE.match(value):
+ return
+ try:
+ datetime.fromisoformat(value.replace("Z", "+00:00"))
+ return
+ except ValueError:
+ pass
+ try:
+ datetime.strptime(value, "%Y-%m-%d") # unpadded ISO, e.g. 2021-1-1
+ return
+ except ValueError:
+ pass
+ raise exceptions.ValidationError(
+ {field: f"Invalid date value '{value}'. Use an ISO date (YYYY-MM-DD) or relative shorthand like `-7d`."}
+ )
def _sanitize_custom_tag_description(value: str) -> str:
@@ -732,3 +760,410 @@ class SessionGroupSummaryViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
was_impersonated=is_impersonated_session(self.request),
)
super().perform_destroy(instance)
+
+
+@extend_schema_field(OpenApiTypes.OBJECT)
+class SessionSummaryContentField(serializers.JSONField):
+ """Full LLM-generated summary JSON (`SessionSummarySerializer` schema): segments,
+ key_actions, segment_outcomes, session_outcome, optional sentiment."""
+
+
+@extend_schema_field(
+ {
+ "type": "object",
+ "nullable": True,
+ "properties": {
+ "focus_area": {"type": "string"},
+ },
+ }
+)
+class ExtraSummaryContextField(serializers.JSONField):
+ """Optional `ExtraSummaryContext` dict — `focus_area` keyword used when generating the summary."""
+
+
+@extend_schema_field({"type": "object", "nullable": True})
+class RunMetadataField(serializers.JSONField):
+ """`SessionSummaryRunMeta` dict — `model_used`, `visual_confirmation`, and (for video runs)
+ `visual_confirmation_results` plus any `failed_sessions` entries. Null on legacy rows that
+ predate run metadata."""
+
+
+_SESSION_OUTCOME_SCHEMA = {
+ "type": "object",
+ "nullable": True,
+ "properties": {
+ "success": {"type": "boolean"},
+ "description": {"type": "string"},
+ },
+}
+
+_OUTCOME_CHOICES = (
+ ("success", "Session outcome marked successful by the summary"),
+ ("failure", "Session outcome marked unsuccessful by the summary"),
+ ("unknown", "Summary did not record an outcome"),
+)
+
+
+class SingleSessionSummaryMinimalSerializer(serializers.ModelSerializer):
+ """Lightweight projection for list endpoints — omits the full `summary` JSON (~50 KB per row)."""
+
+ created_by = UserBasicSerializer(read_only=True, allow_null=True)
+ session_outcome = serializers.SerializerMethodField(
+ help_text=(
+ "Headline outcome from the summary: `{success: bool, description: string}` or null if the "
+ "summary did not record one. Useful for quickly classifying a session as success/failure."
+ ),
+ )
+ exception_count = serializers.SerializerMethodField(
+ help_text="Number of exception event IDs surfaced by this summary (capped at 100).",
+ )
+ has_exceptions = serializers.SerializerMethodField(
+ help_text="True if the summary surfaced any exception events.",
+ )
+ model_used = serializers.SerializerMethodField(
+ help_text="LLM model identifier that generated this summary, if recorded in run metadata.",
+ )
+ visual_confirmation = serializers.SerializerMethodField(
+ help_text="True if the summary was produced with video-based visual confirmation (the rasterized-recording path).",
+ )
+ extra_summary_context = ExtraSummaryContextField(
+ read_only=True,
+ help_text="Optional context passed to the summary at generation time (e.g. `focus_area`).",
+ )
+
+ class Meta:
+ model = SingleSessionSummary
+ fields = [
+ "id",
+ "session_id",
+ "distinct_id",
+ "session_start_time",
+ "session_duration",
+ "session_outcome",
+ "exception_count",
+ "has_exceptions",
+ "model_used",
+ "visual_confirmation",
+ "extra_summary_context",
+ "created_at",
+ "created_by",
+ ]
+ read_only_fields = fields
+
+ @extend_schema_field(_SESSION_OUTCOME_SCHEMA)
+ def get_session_outcome(self, obj: SingleSessionSummary) -> dict | None:
+ # The list queryset annotates `session_outcome_json` and defers the heavy `summary`
+ # column, so a page of rows never hydrates the full ~50 KB summary JSON just to read
+ # the outcome. Fall back to the in-memory column for any non-list/deferred-free path.
+ outcome = getattr(obj, "session_outcome_json", None)
+ if outcome is None and "summary" not in obj.get_deferred_fields() and isinstance(obj.summary, dict):
+ outcome = obj.summary.get("session_outcome")
+ return outcome if isinstance(outcome, dict) else None
+
+ @extend_schema_field(OpenApiTypes.INT)
+ def get_exception_count(self, obj: SingleSessionSummary) -> int:
+ return len(obj.exception_event_ids or [])
+
+ @extend_schema_field(OpenApiTypes.BOOL)
+ def get_has_exceptions(self, obj: SingleSessionSummary) -> bool:
+ return bool(obj.exception_event_ids)
+
+ @extend_schema_field({"type": "string", "nullable": True})
+ def get_model_used(self, obj: SingleSessionSummary) -> str | None:
+ meta = obj.run_metadata or {}
+ return meta.get("model_used") if isinstance(meta, dict) else None
+
+ @extend_schema_field(OpenApiTypes.BOOL)
+ def get_visual_confirmation(self, obj: SingleSessionSummary) -> bool:
+ meta = obj.run_metadata or {}
+ return bool(meta.get("visual_confirmation")) if isinstance(meta, dict) else False
+
+
+class SingleSessionSummarySerializer(serializers.ModelSerializer):
+ """Full session summary, including the generated `summary` JSON content."""
+
+ created_by = UserBasicSerializer(read_only=True, allow_null=True)
+ summary = SessionSummaryContentField(
+ read_only=True,
+ help_text=(
+ "Full LLM-generated summary JSON. Contains `segments` (chronological journey segments), "
+ "`key_actions` (per-segment events with `abandonment` / `confusion` / `exception` flags — "
+ "the structured source of session-level problems), `segment_outcomes`, and `session_outcome`. "
+ "Video-based runs additionally include a `sentiment` block."
+ ),
+ )
+ exception_event_ids = serializers.ListField(
+ child=serializers.CharField(),
+ read_only=True,
+ help_text="Event IDs (capped at 100) where exceptions occurred during the session — extracted from the summary for searchability.",
+ )
+ extra_summary_context = ExtraSummaryContextField(
+ read_only=True,
+ help_text="Optional context passed to the summary at generation time (e.g. `focus_area`).",
+ )
+ run_metadata = RunMetadataField(
+ read_only=True,
+ help_text="`SessionSummaryRunMeta` — model used, whether video-based visual confirmation was applied, and visual-confirmation event-to-asset mappings.",
+ )
+
+ class Meta:
+ model = SingleSessionSummary
+ fields = [
+ "id",
+ "session_id",
+ "distinct_id",
+ "session_start_time",
+ "session_duration",
+ "summary",
+ "exception_event_ids",
+ "extra_summary_context",
+ "run_metadata",
+ "created_at",
+ "created_by",
+ ]
+ read_only_fields = fields
+
+
+@extend_schema(
+ description=(
+ "Read stored AI-generated session summaries (the `ee_single_session_summary` table). "
+ "Returns whatever was persisted by the summarization workflow — does NOT trigger generation. "
+ "For generating new summaries, see the `/session_summaries/stream_batch/` action."
+ ),
+)
+class SingleSessionSummaryViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelViewSet):
+ scope_object = "session_recording"
+ queryset = SingleSessionSummary.objects.all()
+ lookup_field = "session_id"
+ lookup_value_regex = r"[^/]+" # session IDs are typically UUIDs but allow any non-slash identifier
+
+ def get_serializer_class(self) -> type[BaseSerializer]:
+ return SingleSessionSummaryMinimalSerializer if self.action == "list" else SingleSessionSummarySerializer
+
+ def safely_get_object(self, queryset: QuerySet) -> SingleSessionSummary:
+ """Return the latest stored *default-context* summary for a `session_id`, matching
+ `SingleSessionSummaryManager.get_summary(..., extra_summary_context=None)` — a focused
+ (`focus_area`) summary must not shadow the default one."""
+ obj = (
+ queryset.filter(session_id=self.kwargs[self.lookup_field], extra_summary_context__isnull=True)
+ .order_by("-created_at")
+ .first()
+ )
+ if obj is None:
+ raise exceptions.NotFound("No stored summary found for this session.")
+ # `SingleSessionSummary` is not a mapped access-control resource, so the resource-level
+ # `scope_object` check admits users who only hold object-level grants to *some* recording.
+ # Gate on the underlying recording so summary access mirrors `SessionRecordingViewSet`.
+ recording = SessionRecording.get_or_build(session_id=obj.session_id, team=self.team)
+ if recording.deleted:
+ raise exceptions.NotFound("The recording for this summary has been deleted.")
+ if not self.user_access_control.check_access_level_for_object(recording, required_level="viewer"):
+ raise exceptions.PermissionDenied("You do not have access to this recording.")
+ return obj
+
+ # Ordering is forwarded straight to `.order_by()`, so it must be allowlisted: an arbitrary value
+ # would raise an unhandled `FieldError` (500), and a related-field path would add a silent JOIN.
+ ALLOWED_ORDER_FIELDS = frozenset(
+ f"{prefix}{field}" for field in ("created_at", "session_start_time", "session_duration") for prefix in ("", "-")
+ )
+
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ queryset = queryset.filter(team=self.team).select_related("created_by", "team")
+ if self.action != "list":
+ return queryset
+
+ # Scope filters (which sessions) run *before* the latest-per-session dedupe; state filters
+ # (the latest summary's outcome / exception / visual flags) run *after*, so the list never
+ # surfaces a session whose latest summary no longer matches — keeping list and retrieve in sync.
+ queryset = self._filter_list_request(self.request, queryset)
+ # The latest-per-session subquery has to use `ORDER BY session_id, -created_at` to be valid
+ # with `DISTINCT ON (session_id)`.
+ latest_ids = queryset.order_by("session_id", "-created_at").distinct("session_id").values("id")
+ # Defer the heavy `summary` column and project just `session_outcome` so a page of rows doesn't
+ # pull the full ~50 KB summary JSON per row (see `SingleSessionSummaryMinimalSerializer`).
+ deduped = (
+ SingleSessionSummary.objects.filter(team=self.team, id__in=Subquery(latest_ids))
+ .select_related("created_by", "team")
+ .defer("summary")
+ .annotate(session_outcome_json=KeyTransform("session_outcome", "summary"))
+ )
+ deduped = self._apply_state_filters(self.request, deduped)
+ deduped = self._restrict_to_accessible_recordings(deduped)
+ deduped = self._exclude_deleted_recordings(deduped)
+
+ order = self.request.GET.get("order") or "-created_at"
+ if order not in self.ALLOWED_ORDER_FIELDS:
+ raise exceptions.ValidationError(
+ {"order": f"Invalid order field. Allowed values: {', '.join(sorted(self.ALLOWED_ORDER_FIELDS))}."}
+ )
+ return deduped.order_by(order)
+
+ def _restrict_to_accessible_recordings(self, queryset: QuerySet) -> QuerySet:
+ """Mirror `SessionRecordingViewSet` object-level access for the list path, entirely in SQL.
+
+ Most recordings live only in ClickHouse and have no Postgres `SessionRecording` row, so we must
+ never blanket-restrict to recordings that exist here. Two modes:
+ - no team-wide recording access (admitted via object grants only) → restrict to granted sessions;
+ - team-wide access → keep everything (incl. ClickHouse-only sessions) but drop explicit denies.
+ Filtering uses subqueries so the database applies the predicate before pagination.
+ """
+ uac = self.user_access_control
+ team_recordings = SessionRecording.objects.filter(team=self.team)
+ accessible = uac.filter_queryset_by_access_level(team_recordings)
+ if not uac.check_access_level_for_resource("session_recording", required_level="viewer"):
+ return queryset.filter(session_id__in=Subquery(accessible.values("session_id")))
+ blocked = team_recordings.exclude(id__in=accessible.values("id")).values("session_id")
+ return queryset.exclude(session_id__in=Subquery(blocked))
+
+ def _exclude_deleted_recordings(self, queryset: QuerySet) -> QuerySet:
+ """Don't surface summaries whose recording was soft-deleted in Postgres (e.g. crypto-shredded).
+ ClickHouse-side retention/TTL expiry is not enforced here — that needs the recordings query and
+ is tracked as a follow-up."""
+ deleted = SessionRecording.objects.filter(team=self.team, deleted=True).values("session_id")
+ return queryset.exclude(session_id__in=Subquery(deleted))
+
+ def _filter_list_request(self, request: Request, queryset: QuerySet) -> QuerySet:
+ """Scope filters — narrow *which sessions* are considered, before the latest-per-session dedupe."""
+ params = request.GET
+ # Only the default (null-context) summaries, matching the retrieve path's `get_summary` semantics —
+ # otherwise the list could surface a focused (`focus_area`) row that retrieve doesn't return.
+ queryset = queryset.filter(extra_summary_context__isnull=True)
+ if date_from := params.get("date_from"):
+ _validate_date_param("date_from", date_from)
+ queryset = queryset.filter(created_at__gte=relative_date_parse(date_from, self.team.timezone_info))
+ if date_to := params.get("date_to"):
+ _validate_date_param("date_to", date_to)
+ queryset = queryset.filter(created_at__lte=relative_date_parse(date_to, self.team.timezone_info))
+ if distinct_id := params.get("distinct_id"):
+ queryset = queryset.filter(distinct_id=distinct_id)
+ if created_by := params.get("created_by"):
+ try:
+ uuid.UUID(created_by)
+ except (ValueError, TypeError):
+ raise exceptions.ValidationError({"created_by": "Must be a valid UUID."})
+ queryset = queryset.filter(created_by__uuid=created_by)
+ # Multi-value filter: agents typically arrive with a list of session IDs from `query-session-recordings-list`
+ # and want the persisted summaries for that exact set.
+ session_ids_raw = params.get("session_ids")
+ if session_ids_raw:
+ session_ids = [sid.strip() for sid in session_ids_raw.split(",") if sid.strip()]
+ if session_ids:
+ queryset = queryset.filter(session_id__in=session_ids)
+ return queryset
+
+ def _apply_state_filters(self, request: Request, queryset: QuerySet) -> QuerySet:
+ """State filters — applied to the deduped latest-per-session rows, so a match reflects each
+ session's *latest* summary (consistent with what the retrieve endpoint returns)."""
+ params = request.GET
+ outcome = params.get("outcome")
+ if outcome == "success":
+ queryset = queryset.filter(summary__session_outcome__success=True)
+ elif outcome == "failure":
+ queryset = queryset.filter(summary__session_outcome__success=False)
+ elif outcome == "unknown":
+ queryset = queryset.filter(summary__session_outcome__isnull=True)
+ if (has_exceptions := params.get("has_exceptions")) is not None:
+ if has_exceptions.lower() == "true":
+ queryset = queryset.filter(exception_event_ids__len__gt=0)
+ elif has_exceptions.lower() == "false":
+ queryset = queryset.filter(exception_event_ids__len=0)
+ if (has_visual := params.get("has_visual_confirmation")) is not None:
+ if has_visual.lower() == "true":
+ queryset = queryset.filter(run_metadata__visual_confirmation=True)
+ elif has_visual.lower() == "false":
+ queryset = queryset.exclude(run_metadata__visual_confirmation=True)
+ return queryset
+
+ @extend_schema(
+ operation_id="single_session_summaries_list",
+ extensions={"x-product": "replay"},
+ description=(
+ "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."
+ ),
+ parameters=[
+ OpenApiParameter(
+ name="session_ids",
+ type=str,
+ required=False,
+ description="Comma-separated list of session IDs to restrict the result to (uses the `(team, session_id)` index).",
+ ),
+ OpenApiParameter(
+ name="distinct_id",
+ type=str,
+ required=False,
+ description="Filter to summaries for a single user (the session's `distinct_id`).",
+ ),
+ OpenApiParameter(
+ name="outcome",
+ type=str,
+ required=False,
+ enum=[c[0] for c in _OUTCOME_CHOICES],
+ description=(
+ "Filter by the summary's recorded `session_outcome.success` field. `success` for true, "
+ "`failure` for false, `unknown` for summaries without an outcome."
+ ),
+ ),
+ OpenApiParameter(
+ name="has_exceptions",
+ type=bool,
+ required=False,
+ description="When true, only summaries that surfaced one or more exception events; when false, only summaries without exceptions.",
+ ),
+ OpenApiParameter(
+ name="has_visual_confirmation",
+ type=bool,
+ required=False,
+ description="When true, only summaries produced via the video-based visual-confirmation workflow.",
+ ),
+ OpenApiParameter(
+ name="created_by",
+ type=str,
+ required=False,
+ description="Filter to summaries triggered by a specific user, identified by `User.uuid`.",
+ ),
+ OpenApiParameter(
+ name="date_from",
+ type=str,
+ required=False,
+ description="Inclusive lower bound on `created_at`, accepts relative shorthand like `-7d`.",
+ ),
+ OpenApiParameter(
+ name="date_to",
+ type=str,
+ required=False,
+ description="Inclusive upper bound on `created_at`, accepts relative shorthand like `-1d`.",
+ ),
+ OpenApiParameter(
+ name="order",
+ type=str,
+ required=False,
+ enum=sorted(ALLOWED_ORDER_FIELDS),
+ description=(
+ "Ordering field, defaults to `-created_at` (most recent first). Allowed: "
+ "`created_at`, `session_start_time`, `session_duration` (prefix with `-` for descending)."
+ ),
+ ),
+ ],
+ )
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ return super().list(request, *args, **kwargs)
+
+ @extend_schema(
+ operation_id="single_session_summaries_retrieve",
+ extensions={"x-product": "replay"},
+ description=(
+ "Get the latest stored AI summary for a single session by `session_id`. Returns the full "
+ "`summary` JSON (segments with named timeline, per-action `abandonment` / `confusion` / "
+ "`exception` flags, segment outcomes, headline `session_outcome`, optional `sentiment`), the "
+ "`exception_event_ids` array, the `extra_summary_context` (e.g. `focus_area`) used at "
+ "generation time, and the `run_metadata` (LLM model used, whether visual confirmation was "
+ "applied). 404 if no summary has been generated for this session yet — to trigger generation, "
+ "use the existing `session-recording-summarize` flow rather than this endpoint."
+ ),
+ )
+ def retrieve(self, request: Request, *args, **kwargs) -> Response:
+ return super().retrieve(request, *args, **kwargs)
diff --git a/ee/api/test/test_single_session_summary_viewset.py b/ee/api/test/test_single_session_summary_viewset.py
new file mode 100644
index 000000000000..628ce86668c6
--- /dev/null
+++ b/ee/api/test/test_single_session_summary_viewset.py
@@ -0,0 +1,481 @@
+import copy
+from datetime import UTC, datetime
+
+import pytest
+from posthog.test.base import APIBaseTest
+
+from posthog.constants import AvailableFeature
+from posthog.models import Organization, OrganizationMembership, Team, User
+from posthog.session_recordings.models.session_recording import SessionRecording
+
+from ee.hogai.session_summaries.session.output_data import SessionSummarySerializer
+from ee.hogai.session_summaries.tests.conftest import get_mock_enriched_llm_json_response
+from ee.models.rbac.access_control import AccessControl
+from ee.models.session_summaries import SessionSummaryRunMeta, SingleSessionSummary
+
+
+class TestSingleSessionSummaryViewSet(APIBaseTest):
+ def _url(self, session_id: str | None = None) -> str:
+ base = f"/api/projects/{self.team.id}/single_session_summaries/"
+ return base if session_id is None else f"{base}{session_id}/"
+
+ def _make_summary(
+ self,
+ session_id: str,
+ *,
+ team: Team | None = None,
+ success: bool | None = True,
+ exception_event_ids: list[str] | None = None,
+ focus_area: str | None = None,
+ visual_confirmation: bool = False,
+ model_used: str = "gpt-4o",
+ distinct_id: str | None = "user-1",
+ session_duration: int | None = 120,
+ session_start_time: datetime | None = None,
+ ) -> SingleSessionSummary:
+ team = team or self.team
+ summary = copy.deepcopy(get_mock_enriched_llm_json_response(session_id))
+ if success is None:
+ summary.pop("session_outcome", None)
+ else:
+ summary["session_outcome"]["success"] = success
+ return SingleSessionSummary.objects.create(
+ team=team,
+ session_id=session_id,
+ summary=summary,
+ exception_event_ids=exception_event_ids or [],
+ extra_summary_context={"focus_area": focus_area} if focus_area else None,
+ run_metadata={
+ "model_used": model_used,
+ "visual_confirmation": visual_confirmation,
+ "visual_confirmation_results": None,
+ "failed_sessions": [],
+ },
+ distinct_id=distinct_id,
+ session_duration=session_duration,
+ session_start_time=session_start_time or datetime(2026, 1, 1, tzinfo=UTC),
+ created_by=self.user,
+ )
+
+ def test_list_returns_only_team_summaries(self) -> None:
+ self._make_summary("session-a")
+ self._make_summary("session-b")
+ other_team = Organization.objects.bootstrap(None)[2]
+ self._make_summary("other-team-session", team=other_team)
+
+ response = self.client.get(self._url())
+
+ self.assertEqual(response.status_code, 200)
+ body = response.json()
+ session_ids = {row["session_id"] for row in body["results"]}
+ self.assertEqual(session_ids, {"session-a", "session-b"})
+
+ def test_list_dedupes_to_latest_per_session(self) -> None:
+ first = self._make_summary("session-a", model_used="gpt-old")
+ first.created_at = datetime(2026, 1, 1, tzinfo=UTC)
+ first.save(update_fields=["created_at"])
+ self._make_summary("session-a", model_used="gpt-new")
+
+ response = self.client.get(self._url())
+
+ self.assertEqual(response.status_code, 200)
+ results = response.json()["results"]
+ self.assertEqual(len(results), 1)
+ self.assertEqual(results[0]["model_used"], "gpt-new")
+
+ def test_list_returns_lightweight_shape(self) -> None:
+ self._make_summary(
+ "session-a",
+ exception_event_ids=["evt-1", "evt-2"],
+ visual_confirmation=True,
+ )
+
+ response = self.client.get(self._url())
+
+ self.assertEqual(response.status_code, 200)
+ row = response.json()["results"][0]
+ self.assertEqual(row["session_id"], "session-a")
+ self.assertEqual(row["distinct_id"], "user-1")
+ self.assertEqual(row["exception_count"], 2)
+ self.assertTrue(row["has_exceptions"])
+ self.assertTrue(row["visual_confirmation"])
+ self.assertEqual(row["model_used"], "gpt-4o")
+ self.assertIsNone(row["extra_summary_context"])
+ self.assertEqual(row["session_outcome"]["success"], True)
+ # The full summary JSON must not leak into the list shape.
+ self.assertNotIn("summary", row)
+ self.assertNotIn("exception_event_ids", row)
+
+ def test_list_filter_session_ids_csv(self) -> None:
+ self._make_summary("session-a")
+ self._make_summary("session-b")
+ self._make_summary("session-c")
+
+ response = self.client.get(self._url(), {"session_ids": "session-a,session-c"})
+
+ self.assertEqual(response.status_code, 200)
+ session_ids = {row["session_id"] for row in response.json()["results"]}
+ self.assertEqual(session_ids, {"session-a", "session-c"})
+
+ def test_list_filter_outcome_success(self) -> None:
+ self._make_summary("session-success", success=True)
+ self._make_summary("session-failure", success=False)
+ self._make_summary("session-unknown", success=None)
+
+ response = self.client.get(self._url(), {"outcome": "success"})
+ ids = {row["session_id"] for row in response.json()["results"]}
+ self.assertEqual(ids, {"session-success"})
+
+ response = self.client.get(self._url(), {"outcome": "failure"})
+ ids = {row["session_id"] for row in response.json()["results"]}
+ self.assertEqual(ids, {"session-failure"})
+
+ def test_list_filter_has_exceptions(self) -> None:
+ self._make_summary("session-with-exc", exception_event_ids=["evt-1"])
+ self._make_summary("session-no-exc", exception_event_ids=[])
+
+ response = self.client.get(self._url(), {"has_exceptions": "true"})
+ ids = {row["session_id"] for row in response.json()["results"]}
+ self.assertEqual(ids, {"session-with-exc"})
+
+ response = self.client.get(self._url(), {"has_exceptions": "false"})
+ ids = {row["session_id"] for row in response.json()["results"]}
+ self.assertEqual(ids, {"session-no-exc"})
+
+ def test_list_filter_has_visual_confirmation(self) -> None:
+ self._make_summary("session-video", visual_confirmation=True)
+ self._make_summary("session-event-only", visual_confirmation=False)
+
+ response = self.client.get(self._url(), {"has_visual_confirmation": "true"})
+ ids = {row["session_id"] for row in response.json()["results"]}
+ self.assertEqual(ids, {"session-video"})
+
+ def test_list_filter_distinct_id(self) -> None:
+ self._make_summary("session-a", distinct_id="alice")
+ self._make_summary("session-b", distinct_id="bob")
+
+ response = self.client.get(self._url(), {"distinct_id": "alice"})
+ ids = {row["session_id"] for row in response.json()["results"]}
+ self.assertEqual(ids, {"session-a"})
+
+ def test_list_date_bounds_are_inclusive(self) -> None:
+ boundary = self._make_summary("session-boundary")
+ boundary.created_at = datetime(2026, 3, 1, tzinfo=UTC)
+ boundary.save(update_fields=["created_at"])
+ earlier = self._make_summary("session-earlier")
+ earlier.created_at = datetime(2026, 2, 1, tzinfo=UTC)
+ earlier.save(update_fields=["created_at"])
+
+ # date_from equal to the boundary timestamp must include that row (inclusive lower bound).
+ response = self.client.get(self._url(), {"date_from": "2026-03-01"})
+ ids = {row["session_id"] for row in response.json()["results"]}
+ self.assertIn("session-boundary", ids)
+ self.assertNotIn("session-earlier", ids)
+
+ # date_to equal to the boundary timestamp must include that row (inclusive upper bound).
+ response = self.client.get(self._url(), {"date_to": "2026-03-01"})
+ ids = {row["session_id"] for row in response.json()["results"]}
+ self.assertIn("session-boundary", ids)
+ self.assertIn("session-earlier", ids)
+
+ def test_list_orders_by_allowed_field(self) -> None:
+ short = self._make_summary("session-short", session_duration=10)
+ long = self._make_summary("session-long", session_duration=999)
+
+ response = self.client.get(self._url(), {"order": "-session_duration"})
+
+ self.assertEqual(response.status_code, 200)
+ ordered_ids = [row["session_id"] for row in response.json()["results"]]
+ self.assertEqual(ordered_ids, [long.session_id, short.session_id])
+
+ def test_list_rejects_unknown_order_field(self) -> None:
+ self._make_summary("session-a")
+
+ response = self.client.get(self._url(), {"order": "created_by__email"})
+
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.json()["attr"], "order")
+
+ def test_list_rejects_invalid_created_by(self) -> None:
+ self._make_summary("session-a")
+ response = self.client.get(self._url(), {"created_by": "not-a-uuid"})
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.json()["attr"], "created_by")
+
+ def test_list_rejects_unparseable_date(self) -> None:
+ self._make_summary("session-a")
+ response = self.client.get(self._url(), {"date_from": "yesterday"})
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.json()["attr"], "date_from")
+
+ def test_list_accepts_relative_date_shorthand(self) -> None:
+ self._make_summary("session-a")
+ response = self.client.get(self._url(), {"date_from": "-30d"})
+ self.assertEqual(response.status_code, 200)
+
+ def test_list_state_filter_reflects_latest_summary(self) -> None:
+ # A session whose older summary failed but latest succeeded must NOT appear under
+ # outcome=failure (list stays consistent with what retrieve returns — the latest).
+ older = self._make_summary("sess-flip", success=False)
+ older.created_at = datetime(2026, 1, 1, tzinfo=UTC)
+ older.save(update_fields=["created_at"])
+ self._make_summary("sess-flip", success=True)
+
+ failure = self.client.get(self._url(), {"outcome": "failure"})
+ self.assertEqual([row["session_id"] for row in failure.json()["results"]], [])
+
+ success = self.client.get(self._url(), {"outcome": "success"})
+ self.assertEqual({row["session_id"] for row in success.json()["results"]}, {"sess-flip"})
+
+ def test_list_and_retrieve_exclude_deleted_recordings(self) -> None:
+ self._make_summary("live-rec")
+ self._make_summary("deleted-rec")
+ SessionRecording.objects.create(team=self.team, session_id="deleted-rec", deleted=True)
+
+ ids = {row["session_id"] for row in self.client.get(self._url()).json()["results"]}
+ self.assertIn("live-rec", ids)
+ self.assertNotIn("deleted-rec", ids)
+
+ self.assertEqual(self.client.get(self._url("deleted-rec")).status_code, 404)
+
+ def test_retrieve_returns_full_summary(self) -> None:
+ self._make_summary(
+ "session-a",
+ exception_event_ids=["evt-1"],
+ visual_confirmation=True,
+ )
+
+ response = self.client.get(self._url("session-a"))
+
+ self.assertEqual(response.status_code, 200)
+ body = response.json()
+ self.assertEqual(body["session_id"], "session-a")
+ self.assertIn("segments", body["summary"])
+ self.assertIn("key_actions", body["summary"])
+ self.assertIn("session_outcome", body["summary"])
+ self.assertEqual(body["exception_event_ids"], ["evt-1"])
+ self.assertIsNone(body["extra_summary_context"])
+ self.assertEqual(body["run_metadata"]["model_used"], "gpt-4o")
+ self.assertEqual(body["run_metadata"]["visual_confirmation"], True)
+
+ def test_retrieve_returns_default_context_over_newer_focused_summary(self) -> None:
+ # The retrieve path matches `get_summary(..., extra_summary_context=None)`: a focused
+ # (`focus_area`) summary must not shadow the default one, even if it's newer.
+ default = self._make_summary("sess-ctx", model_used="default-model")
+ default.created_at = datetime(2026, 1, 1, tzinfo=UTC)
+ default.save(update_fields=["created_at"])
+ self._make_summary("sess-ctx", model_used="focused-model", focus_area="checkout")
+
+ response = self.client.get(self._url("sess-ctx"))
+
+ self.assertEqual(response.status_code, 200)
+ self.assertIsNone(response.json()["extra_summary_context"])
+ self.assertEqual(response.json()["run_metadata"]["model_used"], "default-model")
+
+ def test_retrieve_404_when_only_focused_context_exists(self) -> None:
+ self._make_summary("sess-focused-only", focus_area="checkout")
+ response = self.client.get(self._url("sess-focused-only"))
+ self.assertEqual(response.status_code, 404)
+
+ def test_list_only_returns_default_context_summaries(self) -> None:
+ # List keys on the default (null-context) summary, like retrieve — a focused-only session
+ # does not appear, and a session with both shows its default row (even if focused is newer).
+ self._make_summary("sess-default-only")
+ self._make_summary("sess-focused-only", focus_area="checkout")
+ default = self._make_summary("sess-both")
+ default.created_at = datetime(2026, 1, 1, tzinfo=UTC)
+ default.save(update_fields=["created_at"])
+ self._make_summary("sess-both", focus_area="checkout")
+
+ results = {row["session_id"]: row for row in self.client.get(self._url()).json()["results"]}
+ self.assertIn("sess-default-only", results)
+ self.assertNotIn("sess-focused-only", results)
+ self.assertIsNone(results["sess-both"]["extra_summary_context"])
+
+ def test_retrieve_returns_latest_summary_when_multiple_exist(self) -> None:
+ older = self._make_summary("session-a", model_used="gpt-old")
+ older.created_at = datetime(2026, 1, 1, tzinfo=UTC)
+ older.save(update_fields=["created_at"])
+ self._make_summary("session-a", model_used="gpt-new")
+
+ response = self.client.get(self._url("session-a"))
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.json()["run_metadata"]["model_used"], "gpt-new")
+
+ def test_retrieve_returns_404_when_missing(self) -> None:
+ response = self.client.get(self._url("nonexistent-session"))
+ self.assertEqual(response.status_code, 404)
+
+ def test_retrieve_other_team_summary_is_404(self) -> None:
+ other_team = Organization.objects.bootstrap(None)[2]
+ self._make_summary("cross-team", team=other_team)
+
+ response = self.client.get(self._url("cross-team"))
+ self.assertEqual(response.status_code, 404)
+
+ def test_list_unauthenticated(self) -> None:
+ self.client.logout()
+ response = self.client.get(self._url())
+ self.assertEqual(response.status_code, 401)
+
+ def test_create_is_not_allowed(self) -> None:
+ response = self.client.post(self._url(), {"session_id": "x"}, format="json")
+ self.assertIn(response.status_code, (403, 405))
+
+ def test_delete_is_not_allowed(self) -> None:
+ self._make_summary("session-a")
+ response = self.client.delete(self._url("session-a"))
+ self.assertIn(response.status_code, (403, 405))
+
+ def test_run_metadata_fields_handle_none(self) -> None:
+ # Older rows may have written before run_metadata was added; the API should not crash on them.
+ SingleSessionSummary.objects.create(
+ team=self.team,
+ session_id="legacy-session",
+ summary=get_mock_enriched_llm_json_response("legacy-session"),
+ exception_event_ids=[],
+ run_metadata=None,
+ session_start_time=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+
+ response = self.client.get(self._url())
+ self.assertEqual(response.status_code, 200)
+ row = next(r for r in response.json()["results"] if r["session_id"] == "legacy-session")
+ self.assertIsNone(row["model_used"])
+ self.assertFalse(row["visual_confirmation"])
+
+ # Retrieve serializes the null run_metadata without crashing (schema marks it nullable).
+ retrieve = self.client.get(self._url("legacy-session"))
+ self.assertEqual(retrieve.status_code, 200)
+ self.assertIsNone(retrieve.json()["run_metadata"])
+
+ def test_dataclass_round_trip_via_manager(self) -> None:
+ # Sanity check that the serializer produces what the manager writes via the production code path.
+ summary_data = get_mock_enriched_llm_json_response("session-a")
+ serializer = SessionSummarySerializer(data=summary_data)
+ serializer.is_valid(raise_exception=True)
+ SingleSessionSummary.objects.add_summary(
+ team_id=self.team.id,
+ session_id="session-a",
+ summary=serializer,
+ exception_event_ids=["evt-1"],
+ extra_summary_context=None,
+ run_metadata=SessionSummaryRunMeta(model_used="gpt-4o", visual_confirmation=False),
+ created_by=self.user,
+ )
+
+ response = self.client.get(self._url("session-a"))
+
+ self.assertEqual(response.status_code, 200)
+ body = response.json()
+ self.assertEqual(body["session_id"], "session-a")
+ self.assertIn("segments", body["summary"])
+ self.assertIsNone(body["extra_summary_context"])
+
+
+class TestSingleSessionSummaryViewSetAccessControl(APIBaseTest):
+ """A summary's access must follow the underlying recording's, even though `SingleSessionSummary`
+ is not itself a mapped access-control resource. Without per-recording gating, a user with object-level
+ access to one recording could read summaries for every recording in the team."""
+
+ def _url(self, session_id: str | None = None) -> str:
+ base = f"/api/projects/{self.team.id}/single_session_summaries/"
+ return base if session_id is None else f"{base}{session_id}/"
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+
+ self.viewer_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+
+ # Two recordings + their persisted summaries, created by the admin (not the viewer).
+ self.recording_allowed = SessionRecording.objects.create(
+ team=self.team, session_id="rec-allowed", distinct_id="u1", deleted=False
+ )
+ self.recording_denied = SessionRecording.objects.create(
+ team=self.team, session_id="rec-denied", distinct_id="u2", deleted=False
+ )
+ for session_id in ("rec-allowed", "rec-denied"):
+ SingleSessionSummary.objects.create(
+ team=self.team,
+ session_id=session_id,
+ summary=copy.deepcopy(get_mock_enriched_llm_json_response(session_id)),
+ exception_event_ids=[],
+ run_metadata={"model_used": "gpt-4o", "visual_confirmation": False},
+ session_start_time=datetime(2026, 1, 1, tzinfo=UTC),
+ created_by=self.user,
+ )
+
+ # Viewer can see only `rec-allowed`: object-level grant + resource-level "none".
+ membership = OrganizationMembership.objects.get(user=self.viewer_user, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="session_recording",
+ resource_id=str(self.recording_allowed.id),
+ access_level="viewer",
+ organization_member=membership,
+ )
+ AccessControl.objects.create(
+ team=self.team,
+ resource="session_recording",
+ resource_id=None,
+ access_level="none",
+ organization_member=membership,
+ )
+ self.client.force_login(self.viewer_user)
+
+ def test_list_only_returns_summaries_for_accessible_recordings(self) -> None:
+ response = self.client.get(self._url())
+
+ self.assertEqual(response.status_code, 200)
+ session_ids = {row["session_id"] for row in response.json()["results"]}
+ self.assertEqual(session_ids, {"rec-allowed"})
+
+ def test_retrieve_accessible_recording_summary_succeeds(self) -> None:
+ response = self.client.get(self._url("rec-allowed"))
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.json()["session_id"], "rec-allowed")
+
+ def test_retrieve_inaccessible_recording_summary_is_forbidden(self) -> None:
+ response = self.client.get(self._url("rec-denied"))
+ self.assertEqual(response.status_code, 403)
+
+ def test_full_recording_access_sees_all_summaries(self) -> None:
+ # A user with team-wide viewer access takes the fast path (no per-recording filtering).
+ membership = OrganizationMembership.objects.get(user=self.viewer_user, organization=self.organization)
+ AccessControl.objects.filter(team=self.team, organization_member=membership, resource_id=None).update(
+ access_level="viewer"
+ )
+
+ response = self.client.get(self._url())
+
+ self.assertEqual(response.status_code, 200)
+ session_ids = {row["session_id"] for row in response.json()["results"]}
+ self.assertEqual(session_ids, {"rec-allowed", "rec-denied"})
+
+ def test_list_honors_object_level_deny_with_team_access(self) -> None:
+ # Team-wide viewer access, but one recording explicitly denied: the list must exclude it
+ # (the fast path can't blanket-skip filtering when per-recording denies exist).
+ membership = OrganizationMembership.objects.get(user=self.viewer_user, organization=self.organization)
+ AccessControl.objects.filter(team=self.team, organization_member=membership, resource_id=None).update(
+ access_level="viewer"
+ )
+ AccessControl.objects.create(
+ team=self.team,
+ resource="session_recording",
+ resource_id=str(self.recording_denied.id),
+ access_level="none",
+ organization_member=membership,
+ )
+
+ response = self.client.get(self._url())
+
+ self.assertEqual(response.status_code, 200)
+ session_ids = {row["session_id"] for row in response.json()["results"]}
+ self.assertEqual(session_ids, {"rec-allowed"})
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index 404824455eff..80f471195259 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -30,7 +30,7 @@ from products.exports.backend.api import exports
from products.notebooks.backend.api.notebook import NotebookViewSet
from ee.api.quota_limits import QuotaLimitsViewSet
-from ee.api.session_summaries import SessionGroupSummaryViewSet
+from ee.api.session_summaries import SessionGroupSummaryViewSet, SingleSessionSummaryViewSet
from ee.api.vercel import vercel_installation, vercel_product, vercel_proxy, vercel_resource
from ..session_recordings.session_recording_api import SessionRecordingViewSet
@@ -667,6 +667,12 @@ projects_router.register(
["project_id"],
)
+projects_router.register(
+ r"single_session_summaries",
+ SingleSessionSummaryViewSet,
+ "project_single_session_summaries",
+ ["project_id"],
+)
register_legacy_dual_route_team_nested_viewset(
r"quick_filters",
diff --git a/products/replay/frontend/generated/api.schemas.ts b/products/replay/frontend/generated/api.schemas.ts
index f6b9b6f9f8d0..293d8900f67f 100644
--- a/products/replay/frontend/generated/api.schemas.ts
+++ b/products/replay/frontend/generated/api.schemas.ts
@@ -321,6 +321,138 @@ export interface PatchedSessionRecordingApi {
readonly external_references?: readonly PatchedSessionRecordingApiExternalReferencesItem[]
}
+/**
+ * Headline outcome from the summary: `{success: bool, description: string}` or null if the summary did not record one. Useful for quickly classifying a session as success/failure.
+ * @nullable
+ */
+export type SingleSessionSummaryMinimalApiSessionOutcome = {
+ readonly success?: boolean
+ readonly description?: string
+} | null
+
+/**
+ * Optional context passed to the summary at generation time (e.g. `focus_area`).
+ * @nullable
+ */
+export type SingleSessionSummaryMinimalApiExtraSummaryContext = {
+ readonly focus_area?: string
+} | null
+
+/**
+ * Lightweight projection for list endpoints — omits the full `summary` JSON (~50 KB per row).
+ */
+export interface SingleSessionSummaryMinimalApi {
+ readonly id: string
+ /** Session replay ID */
+ readonly session_id: string
+ /**
+ * Distinct ID of the session's user
+ * @nullable
+ */
+ readonly distinct_id: string | null
+ /**
+ * Session start time
+ * @nullable
+ */
+ readonly session_start_time: string | null
+ /**
+ * Session duration in seconds
+ * @nullable
+ */
+ readonly session_duration: number | null
+ /**
+ * Headline outcome from the summary: `{success: bool, description: string}` or null if the summary did not record one. Useful for quickly classifying a session as success/failure.
+ * @nullable
+ */
+ readonly session_outcome: SingleSessionSummaryMinimalApiSessionOutcome
+ /** Number of exception event IDs surfaced by this summary (capped at 100). */
+ readonly exception_count: number
+ /** True if the summary surfaced any exception events. */
+ readonly has_exceptions: boolean
+ /**
+ * LLM model identifier that generated this summary, if recorded in run metadata.
+ * @nullable
+ */
+ readonly model_used: string | null
+ /** True if the summary was produced with video-based visual confirmation (the rasterized-recording path). */
+ readonly visual_confirmation: boolean
+ /**
+ * Optional context passed to the summary at generation time (e.g. `focus_area`).
+ * @nullable
+ */
+ readonly extra_summary_context: SingleSessionSummaryMinimalApiExtraSummaryContext
+ readonly created_at: string
+ readonly created_by: UserBasicApi | null
+}
+
+export interface PaginatedSingleSessionSummaryMinimalListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: SingleSessionSummaryMinimalApi[]
+}
+
+/**
+ * Full LLM-generated summary JSON. Contains `segments` (chronological journey segments), `key_actions` (per-segment events with `abandonment` / `confusion` / `exception` flags — the structured source of session-level problems), `segment_outcomes`, and `session_outcome`. Video-based runs additionally include a `sentiment` block.
+ */
+export type SingleSessionSummaryApiSummary = { [key: string]: unknown }
+
+/**
+ * Optional context passed to the summary at generation time (e.g. `focus_area`).
+ * @nullable
+ */
+export type SingleSessionSummaryApiExtraSummaryContext = {
+ readonly focus_area?: string
+} | null
+
+/**
+ * `SessionSummaryRunMeta` — model used, whether video-based visual confirmation was applied, and visual-confirmation event-to-asset mappings.
+ * @nullable
+ */
+export type SingleSessionSummaryApiRunMetadata = { [key: string]: unknown } | null
+
+/**
+ * Full session summary, including the generated `summary` JSON content.
+ */
+export interface SingleSessionSummaryApi {
+ readonly id: string
+ /** Session replay ID */
+ readonly session_id: string
+ /**
+ * Distinct ID of the session's user
+ * @nullable
+ */
+ readonly distinct_id: string | null
+ /**
+ * Session start time
+ * @nullable
+ */
+ readonly session_start_time: string | null
+ /**
+ * Session duration in seconds
+ * @nullable
+ */
+ readonly session_duration: number | null
+ /** Full LLM-generated summary JSON. Contains `segments` (chronological journey segments), `key_actions` (per-segment events with `abandonment` / `confusion` / `exception` flags — the structured source of session-level problems), `segment_outcomes`, and `session_outcome`. Video-based runs additionally include a `sentiment` block. */
+ readonly summary: SingleSessionSummaryApiSummary
+ /** Event IDs (capped at 100) where exceptions occurred during the session — extracted from the summary for searchability. */
+ readonly exception_event_ids: readonly string[]
+ /**
+ * Optional context passed to the summary at generation time (e.g. `focus_area`).
+ * @nullable
+ */
+ readonly extra_summary_context: SingleSessionSummaryApiExtraSummaryContext
+ /**
+ * `SessionSummaryRunMeta` — model used, whether video-based visual confirmation was applied, and visual-confirmation event-to-asset mappings.
+ * @nullable
+ */
+ readonly run_metadata: SingleSessionSummaryApiRunMetadata
+ readonly created_at: string
+ readonly created_by: UserBasicApi | null
+}
+
export type SessionRecordingPlaylistsListParams = {
created_by?: number
/**
@@ -344,3 +476,59 @@ export type SessionRecordingsListParams = {
*/
offset?: number
}
+
+export type SingleSessionSummariesListParams = {
+ /**
+ * Filter to summaries triggered by a specific user, identified by `User.uuid`.
+ */
+ created_by?: string
+ /**
+ * Inclusive lower bound on `created_at`, accepts relative shorthand like `-7d`.
+ */
+ date_from?: string
+ /**
+ * Inclusive upper bound on `created_at`, accepts relative shorthand like `-1d`.
+ */
+ date_to?: string
+ /**
+ * Filter to summaries for a single user (the session's `distinct_id`).
+ */
+ distinct_id?: string
+ /**
+ * When true, only summaries that surfaced one or more exception events; when false, only summaries without exceptions.
+ */
+ has_exceptions?: boolean
+ /**
+ * When true, only summaries produced via the video-based visual-confirmation workflow.
+ */
+ has_visual_confirmation?: boolean
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+ /**
+ * Ordering field, defaults to `-created_at` (most recent first). Allowed: `created_at`, `session_start_time`, `session_duration` (prefix with `-` for descending).
+ */
+ order?: string
+ /**
+ * Filter by the summary's recorded `session_outcome.success` field. `success` for true, `failure` for false, `unknown` for summaries without an outcome.
+ */
+ outcome?: SingleSessionSummariesListOutcome
+ /**
+ * Comma-separated list of session IDs to restrict the result to (uses the `(team, session_id)` index).
+ */
+ session_ids?: string
+}
+
+export type SingleSessionSummariesListOutcome =
+ (typeof SingleSessionSummariesListOutcome)[keyof typeof SingleSessionSummariesListOutcome]
+
+export const SingleSessionSummariesListOutcome = {
+ Failure: 'failure',
+ Success: 'success',
+ Unknown: 'unknown',
+} as const
diff --git a/products/replay/frontend/generated/api.ts b/products/replay/frontend/generated/api.ts
index c08e80c64f5c..e0ddb300f55b 100644
--- a/products/replay/frontend/generated/api.ts
+++ b/products/replay/frontend/generated/api.ts
@@ -11,6 +11,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
PaginatedSessionRecordingListApi,
PaginatedSessionRecordingPlaylistListApi,
+ PaginatedSingleSessionSummaryMinimalListApi,
PatchedSessionRecordingApi,
PatchedSessionRecordingPlaylistApi,
SessionRecordingApi,
@@ -18,6 +19,8 @@ import type {
SessionRecordingPlaylistsListParams,
SessionRecordingsListParams,
SessionSummariesApi,
+ SingleSessionSummariesListParams,
+ SingleSessionSummaryApi,
} from './api.schemas'
// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
@@ -325,3 +328,54 @@ export const sessionRecordingsDestroy = async (projectId: string, id: string, op
method: 'DELETE',
})
}
+
+export const getSingleSessionSummariesListUrl = (projectId: string, params?: SingleSessionSummariesListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/single_session_summaries/?${stringifiedParams}`
+ : `/api/projects/${projectId}/single_session_summaries/`
+}
+
+/**
+ * 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.
+ */
+export const singleSessionSummariesList = async (
+ projectId: string,
+ params?: SingleSessionSummariesListParams,
+ options?: RequestInit
+): Promise<PaginatedSingleSessionSummaryMinimalListApi> => {
+ return apiMutator<PaginatedSingleSessionSummaryMinimalListApi>(
+ getSingleSessionSummariesListUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getSingleSessionSummariesRetrieveUrl = (projectId: string, sessionId: string) => {
+ return `/api/projects/${projectId}/single_session_summaries/${sessionId}/`
+}
+
+/**
+ * Get the latest stored AI summary for a single session by `session_id`. Returns the full `summary` JSON (segments with named timeline, per-action `abandonment` / `confusion` / `exception` flags, segment outcomes, headline `session_outcome`, optional `sentiment`), the `exception_event_ids` array, the `extra_summary_context` (e.g. `focus_area`) used at generation time, and the `run_metadata` (LLM model used, whether visual confirmation was applied). 404 if no summary has been generated for this session yet — to trigger generation, use the existing `session-recording-summarize` flow rather than this endpoint.
+ */
+export const singleSessionSummariesRetrieve = async (
+ projectId: string,
+ sessionId: string,
+ options?: RequestInit
+): Promise<SingleSessionSummaryApi> => {
+ return apiMutator<SingleSessionSummaryApi>(getSingleSessionSummariesRetrieveUrl(projectId, sessionId), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/replay/mcp/tools.yaml b/products/replay/mcp/tools.yaml
index 949546bbef3a..eecf14dd261a 100644
--- a/products/replay/mcp/tools.yaml
+++ b/products/replay/mcp/tools.yaml
@@ -143,6 +143,42 @@ tools:
session-recording-playlists-update:
operation: session_recording_playlists_update
enabled: false
+ session-recording-summaries-list:
+ operation: single_session_summaries_list
+ enabled: true
+ scopes:
+ - session_recording:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List session summaries
+ description: >
+ List stored AI-generated session summaries for the project, one row per session (latest summary kept). Use
+ to discover which sessions have already been summarized and to filter for sessions with specific problems —
+ `has_exceptions=true`, `outcome=failure`, or a `session_ids` narrowing (e.g. the IDs returned by
+ `query-session-recordings-list`). Returns lightweight rows without the full summary JSON — use
+ `session-recording-summary-get` for the per-segment / per-action detail. This reads persisted summaries
+ only; it does not trigger generation, so a session with no stored summary simply won't appear.
+ session-recording-summary-get:
+ operation: single_session_summaries_retrieve
+ enabled: true
+ scopes:
+ - session_recording:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ enrich_url: '{session_id}'
+ title: Get session summary
+ description: >
+ Get the latest stored AI summary for a single session by `session_id` (any `$session_id` from an event).
+ Returns the full summary JSON — segments with a named timeline, per-action abandonment / confusion /
+ exception flags, segment outcomes, the headline `session_outcome`, and optional sentiment — plus
+ `exception_event_ids`, the `extra_summary_context` used at generation time, and `run_metadata` (LLM model,
+ whether visual confirmation was applied). 404 if no summary has been generated for the session yet — to
+ create one, use `session-recording-summarize` (slow, ~5 min) rather than this read endpoint.
session-recordings-list:
operation: session_recordings_list
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 307dea8d2222..a45e8c0fbd4e 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -4689,6 +4689,34 @@
"readOnlyHint": true
}
},
+ "session-recording-summaries-list": {
+ "description": "List stored AI-generated session summaries for the project, one row per session (latest summary kept). Use to discover which sessions have already been summarized and to filter for sessions with specific problems — `has_exceptions=true`, `outcome=failure`, or a `session_ids` narrowing (e.g. the IDs returned by `query-session-recordings-list`). Returns lightweight rows without the full summary JSON — use `session-recording-summary-get` for the per-segment / per-action detail. This reads persisted summaries only; it does not trigger generation, so a session with no stored summary simply won't appear.",
+ "category": "Session replays",
+ "feature": "replay",
+ "summary": "List session summaries",
+ "title": "List session summaries",
+ "required_scopes": ["session_recording:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "session-recording-summary-get": {
+ "description": "Get the latest stored AI summary for a single session by `session_id` (any `$session_id` from an event). Returns the full summary JSON — segments with a named timeline, per-action abandonment / confusion / exception flags, segment outcomes, the headline `session_outcome`, and optional sentiment — plus `exception_event_ids`, the `extra_summary_context` used at generation time, and `run_metadata` (LLM model, whether visual confirmation was applied). 404 if no summary has been generated for the session yet — to create one, use `session-recording-summarize` (slow, ~5 min) rather than this read endpoint.",
+ "category": "Session replays",
+ "feature": "replay",
+ "summary": "Get session summary",
+ "title": "Get session summary",
+ "required_scopes": ["session_recording:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"signals-scout-config-list": {
"description": "List the per-scout configs for this project — one row per `signals-scout-*` skill, each with its schedule (`run_interval_minutes`), `enabled` flag, and `emit` (dry-run) posture. Use this to see which scouts run, how often, and whether they emit findings to the inbox. Pair with `signals-scout-config-update` to tune them.",
"category": "Signals",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 404476ed7a31..7f7aa05ac11c 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -5000,6 +5000,20 @@
"readOnlyHint": true
}
},
+ "session-recording-summaries-list": {
+ "description": "List stored AI-generated session summaries for the project, one row per session (latest summary kept). Use to discover which sessions have already been summarized and to filter for sessions with specific problems — `has_exceptions=true`, `outcome=failure`, or a `session_ids` narrowing (e.g. the IDs returned by `query-session-recordings-list`). Returns lightweight rows without the full summary JSON — use `session-recording-summary-get` for the per-segment / per-action detail. This reads persisted summaries only; it does not trigger generation, so a session with no stored summary simply won't appear.",
+ "category": "Session replays",
+ "feature": "replay",
+ "summary": "List session summaries",
+ "title": "List session summaries",
+ "required_scopes": ["session_recording:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"session-recording-summarize": {
"description": "Generate an AI-powered summary of one or more session recordings. Returns structured analysis including user journey segments, key actions, segment outcomes, overall session outcome, and sentiment analysis (frustration score, rage clicks, confusion signals). Use this instead of asking users to watch full recordings — it provides the key insights in seconds. Accepts up to 300 session IDs and an optional focus_area to guide the summary toward a specific aspect (e.g., \"checkout flow\" or \"error handling\"). The response is a dict keyed by session ID. Successful entries contain the summary fields; failed entries contain an `error` (e.g. `no_events_or_too_short`, `summary_failed`) and an `error_message` so callers can distinguish \"skipped on purpose\" from \"tool broke\". A bad session ID in the batch is reported as a per-session error and does not fail the whole request. WARNING: First-time summaries call an AI model and are very slow — expect around 5 minutes on average. Previously generated summaries are cached and return instantly. Warn the user about the wait before calling this tool.\n\nDEEP LINKS: Key actions include `session_id` and `milliseconds_since_start`. Build deep links as `{posthog_base_url}/replay/{session_id}?t={milliseconds_since_start / 1000}` (the `?t=` parameter is in seconds). Example: 45000ms in session abc123 → `/replay/abc123?t=45`. Always include these links for key actions and frustration signals.",
"category": "Session replays",
@@ -5016,6 +5030,20 @@
"readOnlyHint": true
}
},
+ "session-recording-summary-get": {
+ "description": "Get the latest stored AI summary for a single session by `session_id` (any `$session_id` from an event). Returns the full summary JSON — segments with a named timeline, per-action abandonment / confusion / exception flags, segment outcomes, the headline `session_outcome`, and optional sentiment — plus `exception_event_ids`, the `extra_summary_context` used at generation time, and `run_metadata` (LLM model, whether visual confirmation was applied). 404 if no summary has been generated for the session yet — to create one, use `session-recording-summarize` (slow, ~5 min) rather than this read endpoint.",
+ "category": "Session replays",
+ "feature": "replay",
+ "summary": "Get session summary",
+ "title": "Get session summary",
+ "required_scopes": ["session_recording:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"signals-scout-config-list": {
"description": "List the per-scout configs for this project — one row per `signals-scout-*` skill, each with its schedule (`run_interval_minutes`), `enabled` flag, and `emit` (dry-run) posture. Use this to see which scouts run, how often, and whether they emit findings to the inbox. Pair with `signals-scout-config-update` to tune them.",
"category": "Signals",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5a8e6710115f..6c2a6b2caf7b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25271,6 +25271,79 @@ export namespace Schemas {
results: SignalSourceConfig[];
}
+ /**
+ * Headline outcome from the summary: `{success: bool, description: string}` or null if the summary did not record one. Useful for quickly classifying a session as success/failure.
+ * @nullable
+ */
+ export type SingleSessionSummaryMinimalSessionOutcome = {
+ readonly success?: boolean;
+ readonly description?: string;
+ } | null;
+
+ /**
+ * Optional context passed to the summary at generation time (e.g. `focus_area`).
+ * @nullable
+ */
+ export type SingleSessionSummaryMinimalExtraSummaryContext = {
+ readonly focus_area?: string;
+ } | null;
+
+ /**
+ * Lightweight projection for list endpoints — omits the full `summary` JSON (~50 KB per row).
+ */
+ export interface SingleSessionSummaryMinimal {
+ readonly id: string;
+ /** Session replay ID */
+ readonly session_id: string;
+ /**
+ * Distinct ID of the session's user
+ * @nullable
+ */
+ readonly distinct_id: string | null;
+ /**
+ * Session start time
+ * @nullable
+ */
+ readonly session_start_time: string | null;
+ /**
+ * Session duration in seconds
+ * @nullable
+ */
+ readonly session_duration: number | null;
+ /**
+ * Headline outcome from the summary: `{success: bool, description: string}` or null if the summary did not record one. Useful for quickly classifying a session as success/failure.
+ * @nullable
+ */
+ readonly session_outcome: SingleSessionSummaryMinimalSessionOutcome;
+ /** Number of exception event IDs surfaced by this summary (capped at 100). */
+ readonly exception_count: number;
+ /** True if the summary surfaced any exception events. */
+ readonly has_exceptions: boolean;
+ /**
+ * LLM model identifier that generated this summary, if recorded in run metadata.
+ * @nullable
+ */
+ readonly model_used: string | null;
+ /** True if the summary was produced with video-based visual confirmation (the rasterized-recording path). */
+ readonly visual_confirmation: boolean;
+ /**
+ * Optional context passed to the summary at generation time (e.g. `focus_area`).
+ * @nullable
+ */
+ readonly extra_summary_context: SingleSessionSummaryMinimalExtraSummaryContext;
+ readonly created_at: string;
+ readonly created_by: UserBasic | null;
+ }
+
+ export interface PaginatedSingleSessionSummaryMinimalList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: SingleSessionSummaryMinimal[];
+ }
+
export interface SnapshotHistoryEntry {
current_artifact?: Artifact | null;
run_id: string;
@@ -37897,6 +37970,65 @@ export namespace Schemas {
readonly updated_at: string;
}
+ /**
+ * Full LLM-generated summary JSON. Contains `segments` (chronological journey segments), `key_actions` (per-segment events with `abandonment` / `confusion` / `exception` flags — the structured source of session-level problems), `segment_outcomes`, and `session_outcome`. Video-based runs additionally include a `sentiment` block.
+ */
+ export type SingleSessionSummarySummary = { [key: string]: unknown };
+
+ /**
+ * Optional context passed to the summary at generation time (e.g. `focus_area`).
+ * @nullable
+ */
+ export type SingleSessionSummaryExtraSummaryContext = {
+ readonly focus_area?: string;
+ } | null;
+
+ /**
+ * `SessionSummaryRunMeta` — model used, whether video-based visual confirmation was applied, and visual-confirmation event-to-asset mappings.
+ * @nullable
+ */
+ export type SingleSessionSummaryRunMetadata = { [key: string]: unknown } | null;
+
+ /**
+ * Full session summary, including the generated `summary` JSON content.
+ */
+ export interface SingleSessionSummary {
+ readonly id: string;
+ /** Session replay ID */
+ readonly session_id: string;
+ /**
+ * Distinct ID of the session's user
+ * @nullable
+ */
+ readonly distinct_id: string | null;
+ /**
+ * Session start time
+ * @nullable
+ */
+ readonly session_start_time: string | null;
+ /**
+ * Session duration in seconds
+ * @nullable
+ */
+ readonly session_duration: number | null;
+ /** Full LLM-generated summary JSON. Contains `segments` (chronological journey segments), `key_actions` (per-segment events with `abandonment` / `confusion` / `exception` flags — the structured source of session-level problems), `segment_outcomes`, and `session_outcome`. Video-based runs additionally include a `sentiment` block. */
+ readonly summary: SingleSessionSummarySummary;
+ /** Event IDs (capped at 100) where exceptions occurred during the session — extracted from the summary for searchability. */
+ readonly exception_event_ids: readonly string[];
+ /**
+ * Optional context passed to the summary at generation time (e.g. `focus_area`).
+ * @nullable
+ */
+ readonly extra_summary_context: SingleSessionSummaryExtraSummaryContext;
+ /**
+ * `SessionSummaryRunMeta` — model used, whether video-based visual confirmation was applied, and visual-confirmation event-to-asset mappings.
+ * @nullable
+ */
+ readonly run_metadata: SingleSessionSummaryRunMetadata;
+ readonly created_at: string;
+ readonly created_by: UserBasic | null;
+ }
+
export interface SlackChannel {
/** Slack channel ID (e.g. C0123ABC) — pass to cdp-functions inputs.channel. */
id: string;
@@ -50416,6 +50548,62 @@ export namespace Schemas {
offset?: number;
};
+ export type SingleSessionSummariesListParams = {
+ /**
+ * Filter to summaries triggered by a specific user, identified by `User.uuid`.
+ */
+ created_by?: string;
+ /**
+ * Inclusive lower bound on `created_at`, accepts relative shorthand like `-7d`.
+ */
+ date_from?: string;
+ /**
+ * Inclusive upper bound on `created_at`, accepts relative shorthand like `-1d`.
+ */
+ date_to?: string;
+ /**
+ * Filter to summaries for a single user (the session's `distinct_id`).
+ */
+ distinct_id?: string;
+ /**
+ * When true, only summaries that surfaced one or more exception events; when false, only summaries without exceptions.
+ */
+ has_exceptions?: boolean;
+ /**
+ * When true, only summaries produced via the video-based visual-confirmation workflow.
+ */
+ has_visual_confirmation?: boolean;
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ /**
+ * Ordering field, defaults to `-created_at` (most recent first). Allowed: `created_at`, `session_start_time`, `session_duration` (prefix with `-` for descending).
+ */
+ order?: string;
+ /**
+ * Filter by the summary's recorded `session_outcome.success` field. `success` for true, `failure` for false, `unknown` for summaries without an outcome.
+ */
+ outcome?: SingleSessionSummariesListOutcome;
+ /**
+ * Comma-separated list of session IDs to restrict the result to (uses the `(team, session_id)` index).
+ */
+ session_ids?: string;
+ };
+
+ export type SingleSessionSummariesListOutcome = typeof SingleSessionSummariesListOutcome[keyof typeof SingleSessionSummariesListOutcome];
+
+
+ export const SingleSessionSummariesListOutcome = {
+ Failure: 'failure',
+ Success: 'success',
+ Unknown: 'unknown',
+ } as const;
+
export type SubscriptionsListParams = {
/**
* Filter by creator user UUID.
diff --git a/services/mcp/src/generated/replay/api.ts b/services/mcp/src/generated/replay/api.ts
index 2420e3263ac6..f9830860f83d 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 6 enabled ops
+ * PostHog API - MCP 8 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -122,3 +122,77 @@ export const SessionRecordingsDestroyParams = /* @__PURE__ */ zod.object({
"Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
),
})
+
+/**
+ * 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.
+ */
+export const SingleSessionSummariesListParams = /* @__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 SingleSessionSummariesListQueryParams = /* @__PURE__ */ zod.object({
+ created_by: zod
+ .string()
+ .optional()
+ .describe('Filter to summaries triggered by a specific user, identified by `User.uuid`.'),
+ date_from: zod
+ .string()
+ .optional()
+ .describe('Inclusive lower bound on `created_at`, accepts relative shorthand like `-7d`.'),
+ date_to: zod
+ .string()
+ .optional()
+ .describe('Inclusive upper bound on `created_at`, accepts relative shorthand like `-1d`.'),
+ distinct_id: zod
+ .string()
+ .optional()
+ .describe("Filter to summaries for a single user (the session's `distinct_id`)."),
+ has_exceptions: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'When true, only summaries that surfaced one or more exception events; when false, only summaries without exceptions.'
+ ),
+ has_visual_confirmation: zod
+ .boolean()
+ .optional()
+ .describe('When true, only summaries produced via the video-based visual-confirmation workflow.'),
+ 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.'),
+ order: zod
+ .string()
+ .optional()
+ .describe(
+ 'Ordering field, defaults to `-created_at` (most recent first). Allowed: `created_at`, `session_start_time`, `session_duration` (prefix with `-` for descending).'
+ ),
+ outcome: zod
+ .enum(['failure', 'success', 'unknown'])
+ .optional()
+ .describe(
+ "Filter by the summary's recorded `session_outcome.success` field. `success` for true, `failure` for false, `unknown` for summaries without an outcome."
+ ),
+ session_ids: zod
+ .string()
+ .optional()
+ .describe(
+ 'Comma-separated list of session IDs to restrict the result to (uses the `(team, session_id)` index).'
+ ),
+})
+
+/**
+ * Get the latest stored AI summary for a single session by `session_id`. Returns the full `summary` JSON (segments with named timeline, per-action `abandonment` / `confusion` / `exception` flags, segment outcomes, headline `session_outcome`, optional `sentiment`), the `exception_event_ids` array, the `extra_summary_context` (e.g. `focus_area`) used at generation time, and the `run_metadata` (LLM model used, whether visual confirmation was applied). 404 if no summary has been generated for this session yet — to trigger generation, use the existing `session-recording-summarize` flow rather than this endpoint.
+ */
+export const singleSessionSummariesRetrievePathSessionIdRegExp = new RegExp('^[^/]+$')
+
+export const SingleSessionSummariesRetrieveParams = /* @__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/."
+ ),
+ session_id: zod.string().regex(singleSessionSummariesRetrievePathSessionIdRegExp),
+})
diff --git a/services/mcp/src/tools/generated/replay.ts b/services/mcp/src/tools/generated/replay.ts
index 0fd6fc5aa6c8..b78e3e63b1c7 100644
--- a/services/mcp/src/tools/generated/replay.ts
+++ b/services/mcp/src/tools/generated/replay.ts
@@ -10,6 +10,8 @@ import {
SessionRecordingPlaylistsRetrieveParams,
SessionRecordingsDestroyParams,
SessionRecordingsRetrieveParams,
+ SingleSessionSummariesListQueryParams,
+ SingleSessionSummariesRetrieveParams,
} from '@/generated/replay/api'
import { withUiApp } from '@/resources/ui-apps'
import { createQueryWrapper } from '@/tools/query-wrapper-factory'
@@ -170,6 +172,55 @@ const sessionRecordingPlaylistsList = (): ToolBase<
},
})
+const SessionRecordingSummariesListSchema = SingleSessionSummariesListQueryParams
+
+const sessionRecordingSummariesList = (): ToolBase<
+ typeof SessionRecordingSummariesListSchema,
+ WithPostHogUrl<Schemas.PaginatedSingleSessionSummaryMinimalList>
+> => ({
+ name: 'session-recording-summaries-list',
+ schema: SessionRecordingSummariesListSchema,
+ handler: async (context: Context, params: z.infer<typeof SessionRecordingSummariesListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedSingleSessionSummaryMinimalList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/single_session_summaries/`,
+ query: {
+ created_by: params.created_by,
+ date_from: params.date_from,
+ date_to: params.date_to,
+ distinct_id: params.distinct_id,
+ has_exceptions: params.has_exceptions,
+ has_visual_confirmation: params.has_visual_confirmation,
+ limit: params.limit,
+ offset: params.offset,
+ order: params.order,
+ outcome: params.outcome,
+ session_ids: params.session_ids,
+ },
+ })
+ return await withPostHogUrl(context, result, '/replay')
+ },
+})
+
+const SessionRecordingSummaryGetSchema = SingleSessionSummariesRetrieveParams.omit({ project_id: true })
+
+const sessionRecordingSummaryGet = (): ToolBase<
+ typeof SessionRecordingSummaryGetSchema,
+ WithPostHogUrl<Schemas.SingleSessionSummary>
+> => ({
+ name: 'session-recording-summary-get',
+ schema: SessionRecordingSummaryGetSchema,
+ handler: async (context: Context, params: z.infer<typeof SessionRecordingSummaryGetSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.SingleSessionSummary>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/single_session_summaries/${encodeURIComponent(String(params.session_id))}/`,
+ })
+ return await withPostHogUrl(context, result, `/replay/${result.session_id}`)
+ },
+})
+
// --- Query wrapper schemas from schema.json ---
const integer = z.coerce.number().int()
@@ -617,6 +668,8 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'session-recording-playlist-get': sessionRecordingPlaylistGet,
'session-recording-playlist-update': sessionRecordingPlaylistUpdate,
'session-recording-playlists-list': sessionRecordingPlaylistsList,
+ 'session-recording-summaries-list': sessionRecordingSummariesList,
+ 'session-recording-summary-get': sessionRecordingSummaryGet,
'query-session-recordings-list': createQueryWrapper({
name: 'query-session-recordings-list',
schema: AssistantRecordingsQuery,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/session-recording-summaries-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/session-recording-summaries-list.json
new file mode 100644
index 000000000000..4417f2a99e9e
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/session-recording-summaries-list.json
@@ -0,0 +1,51 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "created_by": {
+ "description": "Filter to summaries triggered by a specific user, identified by `User.uuid`.",
+ "type": "string"
+ },
+ "date_from": {
+ "description": "Inclusive lower bound on `created_at`, accepts relative shorthand like `-7d`.",
+ "type": "string"
+ },
+ "date_to": {
+ "description": "Inclusive upper bound on `created_at`, accepts relative shorthand like `-1d`.",
+ "type": "string"
+ },
+ "distinct_id": {
+ "description": "Filter to summaries for a single user (the session's `distinct_id`).",
+ "type": "string"
+ },
+ "has_exceptions": {
+ "description": "When true, only summaries that surfaced one or more exception events; when false, only summaries without exceptions.",
+ "type": "boolean"
+ },
+ "has_visual_confirmation": {
+ "description": "When true, only summaries produced via the video-based visual-confirmation workflow.",
+ "type": "boolean"
+ },
+ "limit": {
+ "description": "Number of results to return per page.",
+ "type": "number"
+ },
+ "offset": {
+ "description": "The initial index from which to return the results.",
+ "type": "number"
+ },
+ "order": {
+ "description": "Ordering field, defaults to `-created_at` (most recent first). Allowed: `created_at`, `session_start_time`, `session_duration` (prefix with `-` for descending).",
+ "type": "string"
+ },
+ "outcome": {
+ "description": "Filter by the summary's recorded `session_outcome.success` field. `success` for true, `failure` for false, `unknown` for summaries without an outcome.",
+ "enum": ["failure", "success", "unknown"],
+ "type": "string"
+ },
+ "session_ids": {
+ "description": "Comma-separated list of session IDs to restrict the result to (uses the `(team, session_id)` index).",
+ "type": "string"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/session-recording-summary-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/session-recording-summary-get.json
new file mode 100644
index 000000000000..8a45a57b235c
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/session-recording-summary-get.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "session_id": {
+ "pattern": "^[^/]+$",
+ "type": "string"
+ }
+ },
+ "required": ["session_id"],
+ "type": "object"
+}