: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): add console log reader for session recordings (#124493)
posthog[bot]7988d3dc1767
diff --git a/posthog/session_recordings/queries/console_logs.py b/posthog/session_recordings/queries/console_logs.pynew file mode 100644index 000000000000..67c04a660307--- /dev/null+++ b/posthog/session_recordings/queries/console_logs.py@@ -0,0 +1,122 @@+from datetime import datetime, timedelta++from django.db import models++from posthog.hogql import ast+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.log_entries import LOG_ENTRIES_TTL_DAYS+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.clickhouse.workload import Workload+from posthog.dataclasses import frozen+from posthog.models import Team, User++# Console log timestamps come from the client clock, so allow some slack around the recording's own bounds.+CONSOLE_LOG_WINDOW_SLACK = timedelta(seconds=100)+# Ingestion caps each console argument at 2999 characters, but a call with many arguments joins them all.+MAX_CONSOLE_MESSAGE_LENGTH = 3000+MAX_CONSOLE_LOGS_PAGE_SIZE = 500+++class ConsoleLogLevel(models.TextChoices):+ INFO = "info", "Info"+ WARN = "warn", "Warn"+ ERROR = "error", "Error"+++@frozen+class ConsoleLogEntry:+ timestamp: datetime+ level: str+ message: str+ truncated: bool+++@frozen+class ConsoleLogsPage:+ results: list[ConsoleLogEntry]+ has_more: bool+ logs_expired: bool+++def console_logs_expired(recording_start: datetime, now: datetime) -> bool:+ return recording_start < now - timedelta(days=LOG_ENTRIES_TTL_DAYS)+++def get_console_logs(+ *,+ team: Team,+ user: User | None,+ session_id: str,+ recording_start: datetime,+ recording_end: datetime,+ now: datetime,+ level: str | None = None,+ after: datetime | None = None,+ before: datetime | None = None,+ limit: int = 100,+ offset: int = 0,+) -> ConsoleLogsPage:+ date_from = recording_start - CONSOLE_LOG_WINDOW_SLACK+ date_to = recording_end + CONSOLE_LOG_WINDOW_SLACK+ if after is not None:+ date_from = max(date_from, after)+ if before is not None:+ date_to = min(date_to, before)++ expired = console_logs_expired(recording_start, now)+ if date_from > date_to:+ return ConsoleLogsPage(results=[], has_more=False, logs_expired=expired)++ level_filter: ast.Expr = ast.Constant(value=True)+ if level is not None:+ level_filter = ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["level"]),+ right=ast.Constant(value=level),+ )++ query = parse_select(+ """+ SELECT+ timestamp,+ level,+ left(message, {max_message_length}),+ lengthUTF8(message) > {max_message_length}+ FROM console_logs_log_entries+ WHERE log_source_id = {session_id}+ AND timestamp >= {date_from}+ AND timestamp <= {date_to}+ AND {level_filter}+ ORDER BY timestamp ASC, level ASC, message ASC+ LIMIT {limit}+ OFFSET {offset}+ """,+ placeholders={+ "session_id": ast.Constant(value=session_id),+ "date_from": ast.Constant(value=date_from),+ "date_to": ast.Constant(value=date_to),+ "level_filter": level_filter,+ "max_message_length": ast.Constant(value=MAX_CONSOLE_MESSAGE_LENGTH),+ # One extra row tells us whether another page exists.+ "limit": ast.Constant(value=limit + 1),+ "offset": ast.Constant(value=offset),+ },+ )++ tag_queries(product=Product.REPLAY, feature=Feature.QUERY, team_id=team.pk)+ response = execute_hogql_query(+ query=query,+ team=team,+ user=user,+ query_type="SessionRecordingConsoleLogs",+ workload=Workload.ONLINE,+ )++ rows = response.results or []+ entries = [+ ConsoleLogEntry(timestamp=timestamp, level=row_level, message=message, truncated=bool(truncated))+ for timestamp, row_level, message, truncated in rows[:limit]+ ]+ return ConsoleLogsPage(results=entries, has_more=len(rows) > limit, logs_expired=expired)diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.pyindex 7476e0c52f44..7acaaca00e0b 100644--- a/posthog/session_recordings/session_recording_api.py+++ b/posthog/session_recordings/session_recording_api.py@@ -16,6 +16,7 @@ from django.conf import settingsfrom django.contrib.auth.models import AnonymousUserfrom django.core.cache import cachefrom django.http import HttpResponse, JsonResponse+from django.utils import timezoneimport requestsimport structlog@@ -56,6 +57,7 @@ from posthog.schema import (from posthog.hogql.errors import ExposedHogQLError+from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.person import MinimalPersonSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import ServerTimingsGathered, action, safe_clickhouse_string@@ -94,6 +96,12 @@ from posthog.session_recordings.ai_data.ai_regex_schema import AiRegexSchemafrom posthog.session_recordings.models.session_recording import SessionRecordingfrom posthog.session_recordings.models.session_recording_event import SessionRecordingViewedfrom posthog.session_recordings.openai_client import get_openai_client+from posthog.session_recordings.queries.console_logs import (+ MAX_CONSOLE_LOGS_PAGE_SIZE,+ MAX_CONSOLE_MESSAGE_LENGTH,+ ConsoleLogLevel,+ get_console_logs,+)from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQueryfrom posthog.session_recordings.queries.session_replay_events import (SessionReplayEvents,@@ -560,6 +568,63 @@ class SessionRecordingBulkDeleteResponseSerializer(serializers.Serializer):)+class SessionRecordingConsoleLogsRequestSerializer(serializers.Serializer):+ level = serializers.ChoiceField(+ choices=ConsoleLogLevel.choices,+ required=False,+ help_text="Only return entries at this level. Omit to return every level.",+ )+ after = serializers.DateTimeField(+ required=False,+ help_text="Only return entries at or after this ISO 8601 timestamp. "+ "The results never extend outside the recording's own start and end time.",+ )+ before = serializers.DateTimeField(+ required=False,+ help_text="Only return entries at or before this ISO 8601 timestamp. "+ "The results never extend outside the recording's own start and end time.",+ )+ limit = serializers.IntegerField(+ required=False,+ default=100,+ min_value=1,+ max_value=MAX_CONSOLE_LOGS_PAGE_SIZE,+ help_text=f"Maximum number of entries to return (1-{MAX_CONSOLE_LOGS_PAGE_SIZE}, default 100).",+ )+ offset = serializers.IntegerField(+ required=False,+ default=0,+ min_value=0,+ help_text="Number of entries to skip. Use with `limit` to page through a long recording.",+ )+++class SessionRecordingConsoleLogEntrySerializer(serializers.Serializer):+ timestamp = serializers.DateTimeField(help_text="When the browser logged the message.")+ level = serializers.ChoiceField(choices=ConsoleLogLevel.choices, help_text="Console level of the message.")+ message = serializers.CharField(+ help_text=f"The logged text. String arguments are joined with spaces, and non-string arguments are left out. "+ f"Cut to {MAX_CONSOLE_MESSAGE_LENGTH} characters."+ )+ truncated = serializers.BooleanField(help_text="True when the message was cut to fit the length limit.")+++class SessionRecordingConsoleLogsResponseSerializer(serializers.Serializer):+ results = SessionRecordingConsoleLogEntrySerializer(+ many=True, help_text="Console log entries in chronological order."+ )+ has_more = serializers.BooleanField(help_text="True when more entries exist after this page.")+ console_log_capture_enabled = serializers.BooleanField(+ help_text="Whether the project captures console logs now. When false, an empty result means that nothing "+ "was captured, not that the session had no console output."+ )+ logs_expired = serializers.BooleanField(+ help_text="True when the recording started longer ago than the console log retention period. "+ "The recording can still exist after its console log entries are deleted. Entries expire one at a time, "+ "so a recording close to the retention period can already miss its earliest entries while this is false."+ )++@frozenclass RecordingsListingResult:recordings: list[SessionRecording]@@ -885,7 +950,7 @@ class SessionRecordingViewSet(authentication_classes = [ExportRendererAuthentication]permission_classes = [ExportRendererRecordingPermission]scope_object = "session_recording"- scope_object_read_actions = ["list", "retrieve", "snapshots"]+ scope_object_read_actions = ["list", "retrieve", "snapshots", "console_logs"]throttle_classes = [ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle]serializer_class = SessionRecordingSerializer# We don't use this@@ -1080,6 +1145,43 @@ class SessionRecordingViewSet(properties = Nonereturn Response({"properties": properties})+ @validated_request(+ query_serializer=SessionRecordingConsoleLogsRequestSerializer,+ responses={200: SessionRecordingConsoleLogsResponseSerializer},+ summary="List console logs of a session recording",+ description="Returns the browser console messages captured during a recording, oldest first.",+ )+ @action(methods=["GET"], detail=True, url_path="console_logs", pagination_class=None)+ def console_logs(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:+ tag_queries(product=Product.REPLAY, feature=Feature.QUERY)+ recording = self.get_object()+ if not recording.load_metadata() or recording.start_time is None or recording.end_time is None:+ raise exceptions.NotFound("Recording not found")++ params = request.validated_query_data+ page = get_console_logs(+ team=self.team,+ user=request.user if isinstance(request.user, User) else None,+ session_id=str(recording.session_id),+ recording_start=recording.start_time,+ recording_end=recording.end_time,+ now=timezone.now(),+ level=params.get("level"),+ after=params.get("after"),+ before=params.get("before"),+ limit=params["limit"],+ offset=params["offset"],+ )+ serializer = SessionRecordingConsoleLogsResponseSerializer(+ {+ "results": page.results,+ "has_more": page.has_more,+ "console_log_capture_enabled": bool(self.team.capture_console_log_opt_in),+ "logs_expired": page.logs_expired,+ }+ )+ return Response(serializer.data)+# Returns metadata about the recordingdef retrieve(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:tag_queries(product=Product.REPLAY, feature=Feature.QUERY)diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.pyindex 92651b5d6c19..9555a949b7ee 100644--- a/posthog/session_recordings/test/test_session_recordings.py+++ b/posthog/session_recordings/test/test_session_recordings.py@@ -28,11 +28,14 @@ from posthog.schema import LogEntryPropertyFilter, RecordingsQueryfrom posthog.hogql.errors import QueryError+from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.log_entries import INSERT_LOG_ENTRY_SQLfrom posthog.errors import wrap_clickhouse_query_errorfrom posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded-from posthog.models import Organization, SessionRecording, User+from posthog.models import Organization, PersonalAPIKey, SessionRecording, User+from posthog.models.event.util import format_clickhouse_timestampfrom posthog.models.team import Team-from posthog.models.utils import uuid7+from posthog.models.utils import generate_random_token_personal, hash_key_value, uuid7from posthog.session_recordings.models.session_recording_event import SessionRecordingViewedfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.session_recordings.session_recording_api import RecordingsListingResult@@ -895,6 +898,127 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)"other_viewers": 0,}+ def _insert_console_log(self, session_id: str, timestamp: datetime, level: str, message: str, team_id=None):+ sync_execute(+ INSERT_LOG_ENTRY_SQL,+ {+ "team_id": team_id or self.team.pk,+ "log_source": "session_replay",+ "log_source_id": session_id,+ "instance_id": "",+ "timestamp": format_clickhouse_timestamp(timestamp),+ "level": level,+ "message": message,+ },+ )++ @parameterized.expand(+ [+ ("all_levels", {}, None, ["first", "second", "third", "fourth"], False),+ ("level_filter", {"level": "error"}, None, ["second", "fourth"], False),+ ("first_page", {"limit": 2}, None, ["first", "second"], True),+ ("last_page", {"limit": 2, "offset": 2}, None, ["third", "fourth"], False),+ ("after_offset", {}, {"after": 15}, ["third", "fourth"], False),+ ("before_offset", {}, {"before": 15}, ["first", "second"], False),+ ("after_past_recording_end", {}, {"after": 3600}, [], False),+ ]+ )+ def test_console_logs(+ self,+ _name: str,+ params: dict,+ offsets_seconds: dict[str, int] | None,+ expected_messages: list[str],+ expected_has_more: bool,+ ):+ session_id = str(uuid7())+ base_time = (now() - relativedelta(days=1)).replace(microsecond=0)+ produce_replay_summary(+ session_id=session_id,+ team_id=self.team.pk,+ first_timestamp=base_time,+ last_timestamp=base_time + relativedelta(seconds=30),+ distinct_id="d1",+ ensure_analytics_event_in_session=False,+ retention_period_days=30,+ )+ self._insert_console_log(session_id, base_time + relativedelta(seconds=20), "info", "third")+ self._insert_console_log(session_id, base_time + relativedelta(seconds=1), "info", "first")+ self._insert_console_log(session_id, base_time + relativedelta(seconds=10), "error", "second")+ self._insert_console_log(session_id, base_time + relativedelta(seconds=25), "error", "fourth")+ self._insert_console_log("other-session", base_time + relativedelta(seconds=5), "error", "other session")+ other_team = Team.objects.create(organization=self.organization)+ self._insert_console_log(session_id, base_time + relativedelta(seconds=5), "error", "other team", other_team.pk)+ self._insert_console_log(session_id, base_time - relativedelta(hours=2), "error", "outside recording")++ for key, seconds in (offsets_seconds or {}).items():+ params = {**params, key: (base_time + relativedelta(seconds=seconds)).isoformat()}+ response = self.client.get(+ f"/api/projects/{self.team.id}/session_recordings/{session_id}/console_logs?{urlencode(params)}"+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ body = response.json()+ assert [entry["message"] for entry in body["results"]] == expected_messages+ assert body["has_more"] is expected_has_more+ assert body["logs_expired"] is False++ def test_console_logs_truncates_long_messages(self):+ session_id = str(uuid7())+ base_time = (now() - relativedelta(days=1)).replace(microsecond=0)+ produce_replay_summary(+ session_id=session_id,+ team_id=self.team.pk,+ first_timestamp=base_time,+ last_timestamp=base_time + relativedelta(seconds=30),+ distinct_id="d1",+ ensure_analytics_event_in_session=False,+ retention_period_days=30,+ )+ self._insert_console_log(session_id, base_time + relativedelta(seconds=1), "info", "é" * 3000)+ self._insert_console_log(session_id, base_time + relativedelta(seconds=2), "info", "é" * 3001)++ response = self.client.get(f"/api/projects/{self.team.id}/session_recordings/{session_id}/console_logs")++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert [(entry["message"], entry["truncated"]) for entry in response.json()["results"]] == [+ ("é" * 3000, False),+ ("é" * 3000, True),+ ]++ def test_console_logs_404s_for_missing_recording(self):+ response = self.client.get(f"/api/projects/{self.team.id}/session_recordings/{uuid7()}/console_logs")+ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_console_logs_accepts_read_scoped_personal_api_key(self):+ session_id = str(uuid7())+ base_time = (now() - relativedelta(days=1)).replace(microsecond=0)+ produce_replay_summary(+ session_id=session_id,+ team_id=self.team.pk,+ first_timestamp=base_time,+ last_timestamp=base_time + relativedelta(seconds=30),+ distinct_id="d1",+ ensure_analytics_event_in_session=False,+ retention_period_days=30,+ )+ personal_api_key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="Test Key",+ user=self.user,+ secure_value=hash_key_value(personal_api_key),+ scopes=["session_recording:read"],+ scoped_teams=[self.team.pk],+ )+ self.client.logout()++ response = self.client.get(+ f"/api/projects/{self.team.id}/session_recordings/{session_id}/console_logs",+ HTTP_AUTHORIZATION=f"Bearer {personal_api_key}",+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+def test_capture_diagnostics_degrades_gracefully_on_clickhouse_error(self):session_recording_id = "session_1"produce_replay_summary(session_id=session_recording_id, team_id=self.team.pk, distinct_id="d1")diff --git a/products/replay/frontend/generated/api.schemas.ts b/products/replay/frontend/generated/api.schemas.tsindex 7fc4a6408435..554e0b7a4056 100644--- a/products/replay/frontend/generated/api.schemas.ts+++ b/products/replay/frontend/generated/api.schemas.ts@@ -341,6 +341,45 @@ export interface PatchedSessionRecordingApi {readonly event_count?: number | null}+/**+ * * `info` - Info+ * * `warn` - Warn+ * * `error` - Error+ */+export type ConsoleLogLevelEnumApi = (typeof ConsoleLogLevelEnumApi)[keyof typeof ConsoleLogLevelEnumApi]++export const ConsoleLogLevelEnumApi = {+ Info: 'info',+ Warn: 'warn',+ Error: 'error',+} as const++export interface SessionRecordingConsoleLogEntryApi {+ /** When the browser logged the message. */+ timestamp: string+ /** Console level of the message.+ *+ * * `info` - Info+ * * `warn` - Warn+ * * `error` - Error */+ level: ConsoleLogLevelEnumApi+ /** The logged text. String arguments are joined with spaces, and non-string arguments are left out. Cut to 3000 characters. */+ message: string+ /** True when the message was cut to fit the length limit. */+ truncated: boolean+}++export interface SessionRecordingConsoleLogsResponseApi {+ /** Console log entries in chronological order. */+ results: SessionRecordingConsoleLogEntryApi[]+ /** True when more entries exist after this page. */+ has_more: boolean+ /** Whether the project captures console logs now. When false, an empty result means that nothing was captured, not that the session had no console output. */+ console_log_capture_enabled: boolean+ /** True when the recording started longer ago than the console log retention period. The recording can still exist after its console log entries are deleted. Entries expire one at a time, so a recording close to the retention period can already miss its earliest entries while this is false. */+ logs_expired: boolean+}+export interface SessionRecordingBulkDeleteRequestApi {/*** Session IDs of the recordings to delete (max 100 per call).@@ -389,3 +428,43 @@ export type SessionRecordingsListParams = {*/offset?: number}++export type SessionRecordingsConsoleLogsRetrieveParams = {+ /**+ * Only return entries at or after this ISO 8601 timestamp. The results never extend outside the recording's own start and end time.+ */+ after?: string+ /**+ * Only return entries at or before this ISO 8601 timestamp. The results never extend outside the recording's own start and end time.+ */+ before?: string+ /**+ * Only return entries at this level. Omit to return every level.+ *+ * * `info` - Info+ * * `warn` - Warn+ * * `error` - Error+ * @minLength 1+ */+ level?: SessionRecordingsConsoleLogsRetrieveLevel+ /**+ * Maximum number of entries to return (1-500, default 100).+ * @minimum 1+ * @maximum 500+ */+ limit?: number+ /**+ * Number of entries to skip. Use with `limit` to page through a long recording.+ * @minimum 0+ */+ offset?: number+}++export type SessionRecordingsConsoleLogsRetrieveLevel =+ (typeof SessionRecordingsConsoleLogsRetrieveLevel)[keyof typeof SessionRecordingsConsoleLogsRetrieveLevel]++export const SessionRecordingsConsoleLogsRetrieveLevel = {+ Info: 'info',+ Warn: 'warn',+ Error: 'error',+} as constdiff --git a/products/replay/frontend/generated/api.ts b/products/replay/frontend/generated/api.tsindex 547a7ce84150..28bb8ac8a3ec 100644--- a/products/replay/frontend/generated/api.ts+++ b/products/replay/frontend/generated/api.ts@@ -16,8 +16,10 @@ import type {SessionRecordingApi,SessionRecordingBulkDeleteRequestApi,SessionRecordingBulkDeleteResponseApi,+ SessionRecordingConsoleLogsResponseApi,SessionRecordingPlaylistApi,SessionRecordingPlaylistsListParams,+ SessionRecordingsConsoleLogsRetrieveParams,SessionRecordingsListParams,} from './api.schemas'@@ -313,6 +315,45 @@ export const sessionRecordingsDestroy = async (projectId: string, id: string, op})}+export const getSessionRecordingsConsoleLogsRetrieveUrl = (+ projectId: string,+ id: string,+ params?: SessionRecordingsConsoleLogsRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/session_recordings/${id}/console_logs/?${stringifiedParams}`+ : `/api/projects/${projectId}/session_recordings/${id}/console_logs/`+}++/**+ * Returns the browser console messages captured during a recording, oldest first.+ * @summary List console logs of a session recording+ */+export const sessionRecordingsConsoleLogsRetrieve = async (+ projectId: string,+ id: string,+ params?: SessionRecordingsConsoleLogsRetrieveParams,+ options?: RequestInit+): Promise<SessionRecordingConsoleLogsResponseApi> => {+ return apiMutator<SessionRecordingConsoleLogsResponseApi>(+ getSessionRecordingsConsoleLogsRetrieveUrl(projectId, id, params),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getSessionRecordingsBulkDeleteCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/session_recordings/bulk_delete/`}diff --git a/products/replay/mcp/tools.yaml b/products/replay/mcp/tools.yamlindex 83fa08863709..c336d9a0fc0c 100644--- a/products/replay/mcp/tools.yaml+++ b/products/replay/mcp/tools.yaml@@ -27,6 +27,30 @@ tools: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 somerecordings were already deleted or never existed.+ session-recording-console-logs-list:+ operation: session_recordings_console_logs_retrieve+ enabled: true+ scopes:+ - session_recording:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List session recording console logs+ description: >+ List the browser console messages captured during a session recording, oldest first. Use this after+ `session-recording-get` reports console log, warning, or error counts and you need the actual text, for+ example to tell a JavaScript exception apart from a failed network or resource load. Filter with `level`+ (`info`, `warn`, or `error`), narrow the time range with `after` and `before`, and page with `limit` and+ `offset` while `has_more` is true. Results never extend outside the recording's own start and end time.+ Identical messages logged close together can be collapsed into one entry, so the number of entries can be+ lower than the counts on the recording. Entries carry only the message text: there are no stack traces here.+ For an exception's stack trace, look up `$exception` events with the same `$session_id` through the error+ tracking tools. An empty `results` list does not always mean the session logged nothing: check+ `console_log_capture_enabled` (false means the project does not capture console logs) and `logs_expired`+ (true means the recording is older than the console log retention period).+ feature_flag: mcp-session-recording-console-logs+ reads_ingested_data: eventssession-recording-delete:operation: session_recordings_destroyenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 1d9ec1db1f63..abc7256d47f7 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -13276,6 +13276,23 @@"readOnlyHint": false}},+ "session-recording-console-logs-list": {+ "description": "List the browser console messages captured during a session recording, oldest first. Use this after `session-recording-get` reports console log, warning, or error counts and you need the actual text, for example to tell a JavaScript exception apart from a failed network or resource load. Filter with `level` (`info`, `warn`, or `error`), narrow the time range with `after` and `before`, and page with `limit` and `offset` while `has_more` is true. Results never extend outside the recording's own start and end time. Identical messages logged close together can be collapsed into one entry, so the number of entries can be lower than the counts on the recording. Entries carry only the message text: there are no stack traces here. For an exception's stack trace, look up `$exception` events with the same `$session_id` through the error tracking tools. An empty `results` list does not always mean the session logged nothing: check `console_log_capture_enabled` (false means the project does not capture console logs) and `logs_expired` (true means the recording is older than the console log retention period).",+ "category": "Session replays",+ "feature": "replay",+ "summary": "List session recording console logs",+ "title": "List session recording console logs",+ "required_scopes": ["session_recording:read"],+ "api_operations": ["GET /api/projects/{project_id}/session_recordings/{id}/console_logs/"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "mcp-session-recording-console-logs",+ "reads_ingested_data": "events"+ },"session-recording-delete": {"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",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 38674dbb8acf..84be830a0379 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -13979,6 +13979,23 @@"readOnlyHint": false}},+ "session-recording-console-logs-list": {+ "description": "List the browser console messages captured during a session recording, oldest first. Use this after `session-recording-get` reports console log, warning, or error counts and you need the actual text, for example to tell a JavaScript exception apart from a failed network or resource load. Filter with `level` (`info`, `warn`, or `error`), narrow the time range with `after` and `before`, and page with `limit` and `offset` while `has_more` is true. Results never extend outside the recording's own start and end time. Identical messages logged close together can be collapsed into one entry, so the number of entries can be lower than the counts on the recording. Entries carry only the message text: there are no stack traces here. For an exception's stack trace, look up `$exception` events with the same `$session_id` through the error tracking tools. An empty `results` list does not always mean the session logged nothing: check `console_log_capture_enabled` (false means the project does not capture console logs) and `logs_expired` (true means the recording is older than the console log retention period).",+ "category": "Session replays",+ "feature": "replay",+ "summary": "List session recording console logs",+ "title": "List session recording console logs",+ "required_scopes": ["session_recording:read"],+ "api_operations": ["GET /api/projects/{project_id}/session_recordings/{id}/console_logs/"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "mcp-session-recording-console-logs",+ "reads_ingested_data": "events"+ },"session-recording-delete": {"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",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex afc1f904d8c6..2a11741e4680 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -26124,6 +26124,20 @@ export namespace Schemas {token: string;}+ /**+ * * `info` - Info+ * * `warn` - Warn+ * * `error` - Error+ */+ export type ConsoleLogLevelEnum = typeof ConsoleLogLevelEnum[keyof typeof ConsoleLogLevelEnum];+++ export const ConsoleLogLevelEnum = {+ Info: 'info',+ Warn: 'warn',+ Error: 'error',+ } as const;+export interface ContentAutopilotBriefCompetitor {/** Product to compare against. */name: string;@@ -109774,6 +109788,32 @@ export namespace Schemas {failed_ids: string[];}+ export interface SessionRecordingConsoleLogEntry {+ /** When the browser logged the message. */+ timestamp: string;+ /** Console level of the message.+ *+ * * `info` - Info+ * * `warn` - Warn+ * * `error` - Error */+ level: ConsoleLogLevelEnum;+ /** The logged text. String arguments are joined with spaces, and non-string arguments are left out. Cut to 3000 characters. */+ message: string;+ /** True when the message was cut to fit the length limit. */+ truncated: boolean;+ }++ export interface SessionRecordingConsoleLogsResponse {+ /** Console log entries in chronological order. */+ results: SessionRecordingConsoleLogEntry[];+ /** True when more entries exist after this page. */+ has_more: boolean;+ /** Whether the project captures console logs now. When false, an empty result means that nothing was captured, not that the session had no console output. */+ console_log_capture_enabled: boolean;+ /** True when the recording started longer ago than the console log retention period. The recording can still exist after its console log entries are deleted. Entries expire one at a time, so a recording close to the retention period can already miss its earliest entries while this is false. */+ logs_expired: boolean;+ }+export type SessionReplayListWidgetCatalogEntryOpenApiWidgetType = typeof SessionReplayListWidgetCatalogEntryOpenApiWidgetType[keyof typeof SessionReplayListWidgetCatalogEntryOpenApiWidgetType];@@ -139843,6 +139883,46 @@ export namespace Schemas {offset?: number;};+ export type SessionRecordingsConsoleLogsRetrieveParams = {+ /**+ * Only return entries at or after this ISO 8601 timestamp. The results never extend outside the recording's own start and end time.+ */+ after?: string;+ /**+ * Only return entries at or before this ISO 8601 timestamp. The results never extend outside the recording's own start and end time.+ */+ before?: string;+ /**+ * Only return entries at this level. Omit to return every level.+ *+ * * `info` - Info+ * * `warn` - Warn+ * * `error` - Error+ * @minLength 1+ */+ level?: SessionRecordingsConsoleLogsRetrieveLevel;+ /**+ * Maximum number of entries to return (1-500, default 100).+ * @minimum 1+ * @maximum 500+ */+ limit?: number;+ /**+ * Number of entries to skip. Use with `limit` to page through a long recording.+ * @minimum 0+ */+ offset?: number;+ };++ export type SessionRecordingsConsoleLogsRetrieveLevel = typeof SessionRecordingsConsoleLogsRetrieveLevel[keyof typeof SessionRecordingsConsoleLogsRetrieveLevel];+++ export const SessionRecordingsConsoleLogsRetrieveLevel = {+ Info: 'info',+ Warn: 'warn',+ Error: 'error',+ } as const;+export type SignalsActivitySummaryVersionsRetrieveParams = {/*** The most versions to return, newest first. Capped at the number of versions kept.diff --git a/services/mcp/src/generated/replay/api.ts b/services/mcp/src/generated/replay/api.tsindex 22bdefcef2d7..42f1cca9bf09 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 7 enabled ops+ * PostHog API - MCP 8 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -129,6 +129,57 @@ export const SessionRecordingsDestroyParams = () => zod.object({),})+/**+ * Returns the browser console messages captured during a recording, oldest first.+ * @summary List console logs of a session recording+ */+export const SessionRecordingsConsoleLogsRetrieveParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this session recording.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const sessionRecordingsConsoleLogsRetrieveQueryLimitDefault = 100+export const sessionRecordingsConsoleLogsRetrieveQueryLimitMax = 500++export const sessionRecordingsConsoleLogsRetrieveQueryOffsetDefault = 0+export const sessionRecordingsConsoleLogsRetrieveQueryOffsetMin = 0++export const SessionRecordingsConsoleLogsRetrieveQueryParams = () => zod.object({+ after: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ "Only return entries at or after this ISO 8601 timestamp. The results never extend outside the recording's own start and end time."+ ),+ before: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ "Only return entries at or before this ISO 8601 timestamp. The results never extend outside the recording's own start and end time."+ ),+ level: zod+ .enum(['info', 'warn', 'error'])+ .optional()+ .describe(+ 'Only return entries at this level. Omit to return every level.\n\n\* `info` - Info\n\* `warn` - Warn\n\* `error` - Error'+ ),+ limit: zod+ .number()+ .min(1)+ .max(sessionRecordingsConsoleLogsRetrieveQueryLimitMax)+ .default(sessionRecordingsConsoleLogsRetrieveQueryLimitDefault)+ .describe('Maximum number of entries to return (1-500, default 100).'),+ offset: zod+ .number()+ .min(sessionRecordingsConsoleLogsRetrieveQueryOffsetMin)+ .default(sessionRecordingsConsoleLogsRetrieveQueryOffsetDefault)+ .describe('Number of entries to skip. Use with `limit` to page through a long recording.'),+})+/*** 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`.*/diff --git a/services/mcp/src/tools/generated/replay.ts b/services/mcp/src/tools/generated/replay.tsindex 16e7cdbf0326..087af6bf9967 100644--- a/services/mcp/src/tools/generated/replay.ts+++ b/services/mcp/src/tools/generated/replay.ts@@ -39,6 +39,38 @@ const sessionRecordingBulkDelete = (): ToolBase<},})+const SessionRecordingConsoleLogsListSchema = () => {+ const SessionRecordingsConsoleLogsRetrieveParams = orvalSchemas.SessionRecordingsConsoleLogsRetrieveParams()+ const SessionRecordingsConsoleLogsRetrieveQueryParams =+ orvalSchemas.SessionRecordingsConsoleLogsRetrieveQueryParams()+ return SessionRecordingsConsoleLogsRetrieveParams.omit({ project_id: true }).extend(+ SessionRecordingsConsoleLogsRetrieveQueryParams.shape+ )+}++const sessionRecordingConsoleLogsList = (): ToolBase<+ ReturnType<typeof SessionRecordingConsoleLogsListSchema>,+ Schemas.SessionRecordingConsoleLogsResponse+> => ({+ name: 'session-recording-console-logs-list',+ schema: SessionRecordingConsoleLogsListSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof SessionRecordingConsoleLogsListSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.SessionRecordingConsoleLogsResponse>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/session_recordings/${encodeURIComponent(String(params.id))}/console_logs/`,+ query: {+ after: params.after,+ before: params.before,+ level: params.level,+ limit: params.limit,+ offset: params.offset,+ },+ })+ return result+ },+})+const SessionRecordingDeleteSchema = () => {const SessionRecordingsDestroyParams = orvalSchemas.SessionRecordingsDestroyParams()return SessionRecordingsDestroyParams.omit({ project_id: true })@@ -662,6 +694,7 @@ const AssistantRecordingsQuery = z.object({export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'session-recording-bulk-delete': sessionRecordingBulkDelete,+ 'session-recording-console-logs-list': sessionRecordingConsoleLogsList,'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-console-logs-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/session-recording-console-logs-list.jsonnew file mode 100644index 000000000000..1b8573b9fa95--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/session-recording-console-logs-list.json@@ -0,0 +1,41 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "after": {+ "description": "Only return entries at or after this ISO 8601 timestamp. The results never extend outside the recording's own start and end time.",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },+ "before": {+ "description": "Only return entries at or before this ISO 8601 timestamp. The results never extend outside the recording's own start and end time.",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },+ "id": {+ "description": "A UUID string identifying this session recording.",+ "type": "string"+ },+ "level": {+ "description": "Only return entries at this level. Omit to return every level.\n\n* `info` - Info\n* `warn` - Warn\n* `error` - Error",+ "enum": ["info", "warn", "error"],+ "type": "string"+ },+ "limit": {+ "default": 100,+ "description": "Maximum number of entries to return (1-500, default 100).",+ "maximum": 500,+ "minimum": 1,+ "type": "number"+ },+ "offset": {+ "default": 0,+ "description": "Number of entries to skip. Use with `limit` to page through a long recording.",+ "minimum": 0,+ "type": "number"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex e9583f8d0a9f..d6b7f24cad3e 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -1128,6 +1128,7 @@ describe('Tool Filtering - Feature Flags', () => {'workflows-email-domain-agent-setup','feature-flag-rules-v2-mcp','investigate-insight',+ 'mcp-session-recording-console-logs',]expect(allFlags).toEqual(expect.arrayContaining(branchFlags))// The flags branches add are asserted on the line above and held out of the list anddiff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.tsindex 73e1be14ca08..11a3219c1f6d 100644--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts@@ -113,6 +113,7 @@ async function loadSnapshotTools(): Promise<Tool<ZodObjectAny>[]> {'workflows-transactional-email-api': true,'activity-summary': true,'aeo-citation-tracking': true,+ 'mcp-session-recording-console-logs': true,'anomalies-search': true,'warehouse-multi-destination': true,'feature-flag-rules-v2-mcp': true,