: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(mcp/replay): make session summarizer tool streaming (#57552)
Kim Svatos Dugan0fb30e1ebf5c
diff --git a/ee/api/session_summaries.py b/ee/api/session_summaries.pyindex 2e38629440ab..94100a202181 100644--- a/ee/api/session_summaries.py+++ b/ee/api/session_summaries.py@@ -1,12 +1,15 @@import osimport re+import jsonimport asyncio+from collections.abc import AsyncGeneratorfrom datetime import datetimefrom typing import Any, castfrom django.conf import settingsfrom django.contrib.auth.models import AnonymousUserfrom django.db.models import Func, IntegerField, QuerySet+from django.http import StreamingHttpResponseimport structlogfrom asgiref.sync import async_to_sync@@ -30,6 +33,7 @@ from posthog.models.activity_logging.activity_log import Change, Detail, log_actfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.utils import UUIDfrom posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle+from posthog.renderers import ServerSentEventRendererfrom posthog.temporal.session_replay.session_summary.workflow import execute_summarize_sessionfrom posthog.temporal.session_replay.session_summary_group.types import SessionSummaryStreamUpdatefrom posthog.temporal.session_replay.session_summary_group.workflow import execute_summarize_session_group@@ -49,6 +53,7 @@ from ee.hogai.session_summaries.tracking import (generate_tracking_id,)from ee.hogai.session_summaries.utils import logging_session_ids+from ee.hogai.utils.aio import async_to_sync as async_generator_to_syncfrom ee.models.session_summaries import SessionGroupSummaryfrom ee.models.team_session_summaries_config import (CUSTOM_TAG_DESCRIPTION_MAX_LENGTH,@@ -89,6 +94,12 @@ def _sanitize_custom_tag_description(value: str) -> str:# between the workflow's exception text and the API-layer classification is explicit and grep-able._NO_READY_SUMMARY_ERROR_SUBSTRING = "No ready summary found in DB"+# Cap on concurrent in-flight per-session summary tasks within a single streaming request.+# Each task triggers a Temporal workflow that issues ClickHouse + LLM provider calls, so an+# unbounded fan-out (e.g. 300 sessions in one batch) can spike both. 10 keeps backpressure+# reasonable while still amortizing latency for typical batch sizes.+_STREAM_BATCH_CONCURRENCY = 10+class SessionSummariesConfigSerializer(serializers.ModelSerializer):product_context = serializers.CharField(@@ -443,6 +454,120 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):f"Failed to generate individual session summaries for sessions {logging_session_ids(session_ids)}. Please try again later.")+ @extend_schema(exclude=True)+ @action(+ methods=["POST"],+ detail=False,+ url_path="stream_batch",+ required_scopes=["session_recording:read"],+ renderer_classes=[ServerSentEventRenderer],+ )+ def stream_batch_session_summaries(self, request: Request, **kwargs) -> StreamingHttpResponse:+ user = self._validate_user(request)+ # Use _parse_input (not _validate_input) — the individual flow must surface bad+ # session IDs as per-session error events, not fail the whole batch up front.+ session_ids, extra_summary_context = self._parse_input(request)+ tracking_id = generate_tracking_id()+ team = self.team++ capture_session_summary_started(+ user=user,+ team=team,+ tracking_id=tracking_id,+ summary_source="api",+ summary_type="single",+ session_ids=session_ids,+ )++ async def async_stream() -> AsyncGenerator[bytes, None]:+ SSE_KEEPALIVE_COMMENT = b": keepalive\n\n"+ SSE_KEEPALIVE_INTERVAL = 15 # seconds — well under typical LB idle timeouts (60s)++ sem = asyncio.Semaphore(_STREAM_BATCH_CONCURRENCY)+ pending: set[asyncio.Task[tuple[str, SessionSummarySerializer | Exception]]] = set()+ for session_id in session_ids:++ async def _run(sid: str = session_id) -> tuple[str, SessionSummarySerializer | Exception]:+ async with sem:+ result = await self._summarize_session(+ session_id=sid,+ user=user,+ team=team,+ extra_summary_context=extra_summary_context,+ )+ return sid, result++ pending.add(asyncio.create_task(_run()))++ completed_ids: list[str] = []+ failed_ids: list[str] = []++ try:+ while pending:+ done, pending = await asyncio.wait(+ pending, timeout=SSE_KEEPALIVE_INTERVAL, return_when=asyncio.FIRST_COMPLETED+ )+ if not done:+ yield SSE_KEEPALIVE_COMMENT+ continue++ for task in done:+ sid, result = task.result()+ if isinstance(result, Exception):+ error_type, error_message = self._classify_summary_error(result)+ # _summarize_session returns exceptions as values, so we're not in an except+ # block here — sys.exc_info() is empty. Pass exc_info=result explicitly so+ # the traceback isn't dropped.+ logger.error(+ f"Failed to generate streaming session summary for session {sid} from team {team.pk} by user {user.id}: {result}",+ team_id=team.pk,+ user_id=user.id,+ error_type=error_type,+ exc_info=result,+ )+ failed_ids.append(sid)+ event_data = json.dumps(+ {+ "session_id": sid,+ "error": error_type,+ "error_message": error_message,+ }+ )+ yield f"event: error\ndata: {event_data}\n\n".encode()+ else:+ completed_ids.append(sid)+ event_data = json.dumps({"session_id": sid, "summary": result.data})+ yield f"event: summary\ndata: {event_data}\n\n".encode()+ finally:+ # Cancel still-running tasks on client disconnect or any other early exit+ # to avoid wasting Temporal workflow + LLM calls.+ for task in pending:+ task.cancel()+ if pending:+ await asyncio.gather(*pending, return_exceptions=True)++ capture_session_summary_generated(+ user=user,+ team=team,+ tracking_id=tracking_id,+ summary_source="api",+ summary_type="single",+ session_ids=session_ids,+ success=len(failed_ids) == 0,+ )++ done_data = json.dumps({"completed": completed_ids, "failed": failed_ids})+ yield f"event: done\ndata: {done_data}\n\n".encode()++ return StreamingHttpResponse(+ (async_stream() if settings.SERVER_GATEWAY_INTERFACE == "ASGI" else async_generator_to_sync(async_stream)),+ content_type="text/event-stream",+ headers={+ "Cache-Control": "no-cache",+ "X-Accel-Buffering": "no",+ },+ )+@extend_schema(methods=["GET"],operation_id="retrieve_session_summaries_config",diff --git a/ee/api/test/test_session_summaries.py b/ee/api/test/test_session_summaries.pyindex ca5068eb2cd5..7d2732dcd121 100644--- a/ee/api/test/test_session_summaries.py+++ b/ee/api/test/test_session_summaries.py@@ -1,4 +1,5 @@import os+import jsonfrom collections.abc import AsyncIteratorfrom datetime import datetimefrom typing import Any, Optional, Union@@ -13,6 +14,7 @@ from rest_framework import exceptionsfrom posthog.temporal.session_replay.session_summary_group.types import SessionSummaryStreamUpdate+from ee.api.session_summaries import _NO_READY_SUMMARY_ERROR_SUBSTRINGfrom ee.hogai.session_summaries.session_group.patterns import (EnrichedSessionGroupSummaryPattern,EnrichedSessionGroupSummaryPatternsList,@@ -427,3 +429,310 @@ class TestSessionSummariesAPI(APIBaseTest):# And we should not have invoked the workflow for the missing sessioncalled_session_ids = {call.kwargs.get("session_id") for call in mock_execute.call_args_list}self.assertEqual(called_session_ids, {"session_1"})+++MOCK_SUMMARY_DATA: dict[str, Any] = {+ "segments": [+ {+ "index": 0,+ "name": "Login",+ "start_event_id": "evt00001",+ "end_event_id": "evt00002",+ "meta": {+ "duration": 30,+ "duration_percentage": 1.0,+ "events_count": 2,+ "events_percentage": 1.0,+ "key_action_count": 1,+ "failure_count": 0,+ "abandonment_count": 0,+ "confusion_count": 0,+ "exception_count": 0,+ },+ }+ ],+ "key_actions": [+ {+ "segment_index": 0,+ "events": [+ {+ "description": "Clicked login",+ "abandonment": False,+ "confusion": False,+ "exception": None,+ "event_id": "evt00001",+ "timestamp": "2024-01-01T10:00:00Z",+ "milliseconds_since_start": 0,+ "window_id": "w1",+ "current_url": "https://app.example.com/login",+ "event": "$autocapture",+ "event_type": "click",+ "event_index": 0,+ "session_id": "session1",+ "event_uuid": "00000000-0000-0000-0000-000000000001",+ }+ ],+ }+ ],+ "segment_outcomes": [{"segment_index": 0, "summary": "User logged in successfully", "success": True}],+ "session_outcome": {"description": "Successful login", "success": True},+ "sentiment": {"frustration_score": 0.1, "outcome": "successful", "sentiment_signals": []},+}+++def _parse_sse_events(content: bytes) -> list[dict[str, str]]:+ """Parse SSE response bytes into a list of dicts with 'event' and 'data' keys."""+ raw_blocks = content.decode().split("\n\n")+ events = []+ for block in raw_blocks:+ block = block.strip()+ if not block:+ continue+ parsed: dict[str, str] = {}+ for line in block.splitlines():+ if line.startswith("event:"):+ parsed["event"] = line[len("event:") :].strip()+ elif line.startswith("data:"):+ parsed["data"] = line[len("data:") :].strip()+ if parsed:+ events.append(parsed)+ return events+++class TestStreamSessionSummariesAPI(APIBaseTest):+ environment_patches: list[Any]++ def setUp(self) -> None:+ super().setUp()+ self.url = f"/api/environments/{self.team.id}/session_summaries/stream_batch/"++ self.environment_patches = [+ patch("ee.api.session_summaries.is_cloud", return_value=True),+ patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}),+ ]+ for p in self.environment_patches:+ p.start()++ def tearDown(self) -> None:+ super().tearDown()+ for p in self.environment_patches:+ p.stop()++ def _make_streaming_request(self, session_ids: list[str], focus_area: Optional[str] = None) -> Any:+ payload: dict[str, Any] = {"session_ids": session_ids}+ if focus_area is not None:+ payload["focus_area"] = focus_area+ return self.client.post(self.url, payload, format="json")++ def _get_sse_events(self, response: Any) -> list[dict[str, str]]:+ content = b"".join(response.streaming_content)+ return _parse_sse_events(content)++ @parameterized.expand(+ [+ (+ "all_success",+ ["session_1"],+ None,+ {"summary", "done"},+ ["session_1"],+ [],+ ),+ (+ "mixed_success_and_failure",+ ["session_ok", "session_fail"],+ {"session_fail"},+ {"summary", "error", "done"},+ ["session_ok"],+ ["session_fail"],+ ),+ (+ "all_failures",+ ["s1", "s2"],+ {"s1", "s2"},+ {"error", "done"},+ [],+ ["s1", "s2"],+ ),+ ]+ )+ @patch("ee.api.session_summaries.capture_session_summary_generated")+ @patch("ee.api.session_summaries.capture_session_summary_started")+ @patch("ee.api.session_summaries.execute_summarize_session")+ def test_stream_individually_emits_expected_events(+ self,+ _name: str,+ session_ids: list[str],+ failing_ids: Optional[set[str]],+ expected_event_types: set[str],+ expected_completed: list[str],+ expected_failed: list[str],+ mock_execute: Mock,+ mock_capture_started: Mock,+ mock_capture_generated: Mock,+ ) -> None:+ failing = failing_ids or set()++ def side_effect(session_id: str, **_kwargs: Any) -> Any:+ if session_id in failing:+ raise Exception("summarization failed")+ return get_mock_enriched_llm_json_response(session_id)++ mock_execute.side_effect = side_effect++ response = self._make_streaming_request(session_ids=session_ids)+ self.assertEqual(response.status_code, 200)++ events = self._get_sse_events(response)+ event_types = {e["event"] for e in events}+ self.assertEqual(event_types, expected_event_types)++ done_event = next(e for e in events if e["event"] == "done")+ done_data = json.loads(done_event["data"])+ self.assertCountEqual(done_data["completed"], expected_completed)+ self.assertCountEqual(done_data["failed"], expected_failed)++ # Failed sessions surface as classified, sanitized error events+ if expected_failed:+ error_events = [e for e in events if e["event"] == "error"]+ self.assertEqual(len(error_events), len(expected_failed))+ for event in error_events:+ error_data = json.loads(event["data"])+ self.assertIn(error_data["session_id"], expected_failed)+ self.assertEqual(error_data["error"], "summary_failed")+ self.assertIn("Failed to generate", error_data["error_message"])++ @patch("ee.api.session_summaries.execute_summarize_session")+ def test_stream_individually_summary_event_includes_full_summary_shape(self, mock_execute: Mock) -> None:+ # Smoke-tests that the serialized SessionSummary fields make it onto the wire.+ mock_execute.side_effect = lambda session_id, **_kwargs: get_mock_enriched_llm_json_response(session_id)++ response = self._make_streaming_request(session_ids=["session_1"])+ events = self._get_sse_events(response)+ summary_event = next(e for e in events if e["event"] == "summary")+ summary_data = json.loads(summary_event["data"])++ self.assertEqual(summary_data["session_id"], "session_1")+ for field in ("segments", "key_actions", "segment_outcomes", "session_outcome"):+ self.assertIn(field, summary_data["summary"])++ @patch("ee.api.session_summaries.execute_summarize_session")+ def test_stream_individually_response_headers(self, mock_execute: Mock) -> None:+ mock_execute.side_effect = lambda session_id, **_kwargs: get_mock_enriched_llm_json_response(session_id)++ response = self._make_streaming_request(session_ids=["session_1"])++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.get("Content-Type"), "text/event-stream")+ self.assertEqual(response.get("Cache-Control"), "no-cache")+ self.assertEqual(response.get("X-Accel-Buffering"), "no")++ @patch("ee.api.session_summaries.capture_session_summary_generated")+ @patch("ee.api.session_summaries.capture_session_summary_started")+ @patch("ee.api.session_summaries.execute_summarize_session")+ def test_stream_individually_tracking_uses_single_stream_summary_type(+ self,+ mock_execute: Mock,+ mock_capture_started: Mock,+ mock_capture_generated: Mock,+ ) -> None:+ mock_execute.side_effect = lambda session_id, **_kwargs: get_mock_enriched_llm_json_response(session_id)++ response = self._make_streaming_request(session_ids=["session_1", "session_2"])+ b"".join(response.streaming_content)++ mock_capture_started.assert_called_once()+ started_kwargs = mock_capture_started.call_args[1]+ self.assertEqual(started_kwargs["summary_type"], "single")+ self.assertEqual(started_kwargs["summary_source"], "api")+ self.assertEqual(started_kwargs["session_ids"], ["session_1", "session_2"])++ mock_capture_generated.assert_called_once()+ generated_kwargs = mock_capture_generated.call_args[1]+ self.assertEqual(generated_kwargs["summary_type"], "single")+ self.assertEqual(generated_kwargs["summary_source"], "api")+ self.assertEqual(generated_kwargs["session_ids"], ["session_1", "session_2"])++ self.assertEqual(started_kwargs["tracking_id"], generated_kwargs["tracking_id"])++ @patch("ee.api.session_summaries.execute_summarize_session")+ def test_stream_individually_error_payload_does_not_leak_exception_message(self, mock_execute: Mock) -> None:+ sensitive_message = "openai key sk-internal-leak at /etc/secrets/prompt.txt"+ mock_execute.side_effect = Exception(sensitive_message)++ response = self._make_streaming_request(session_ids=["session_1"])++ self.assertEqual(response.status_code, 200)+ events = self._get_sse_events(response)+ error_event = next(e for e in events if e["event"] == "error")+ error_data = json.loads(error_event["data"])++ self.assertEqual(error_data["error"], "summary_failed")+ self.assertIn("Failed to generate", error_data["error_message"])+ # Regression: the raw exception message must not leak through the SSE payload.+ self.assertNotIn("sk-internal-leak", error_event["data"])+ self.assertNotIn("/etc/secrets", error_event["data"])+ self.assertNotIn(sensitive_message, error_event["data"])++ @parameterized.expand(+ [+ ("missing_session_ids", {"focus_area": "login"}),+ ("empty_session_ids", {"session_ids": []}),+ ]+ )+ def test_stream_individually_invalid_payload_returns_400(self, _name: str, payload: dict[str, Any]) -> None:+ response = self.client.post(self.url, payload, format="json")+ self.assertEqual(response.status_code, 400)++ def test_stream_individually_unauthenticated_returns_401(self) -> None:+ self.client.logout()+ response = self._make_streaming_request(session_ids=["session_1"])+ self.assertEqual(response.status_code, 401)++ @patch("ee.api.session_summaries.is_cloud")+ def test_stream_individually_not_cloud_returns_400(self, mock_is_cloud: Mock) -> None:+ mock_is_cloud.return_value = False+ response = self._make_streaming_request(session_ids=["session_1"])+ self.assertEqual(response.status_code, 400)++ @patch("ee.api.session_summaries.execute_summarize_session")+ def test_stream_individually_bad_session_id_surfaces_as_per_session_error(self, mock_execute: Mock) -> None:+ # Bad session IDs must NOT fail the whole batch — they should surface as per-session+ # error events so callers can distinguish "skipped on purpose" from "tool broke".+ mock_execute.side_effect = ValueError(f"{_NO_READY_SUMMARY_ERROR_SUBSTRING} for session nonexistent")+ response = self._make_streaming_request(session_ids=["nonexistent"])+ self.assertEqual(response.status_code, 200)+ events = self._get_sse_events(response)+ error_event = next(e for e in events if e["event"] == "error")+ error_data = json.loads(error_event["data"])+ self.assertEqual(error_data["session_id"], "nonexistent")+ self.assertEqual(error_data["error"], "no_events_or_too_short")++ @patch("ee.api.session_summaries.execute_summarize_session")+ def test_stream_individually_with_focus_area_passes_extra_context(self, mock_execute: Mock) -> None:+ mock_execute.side_effect = lambda session_id, **_kwargs: get_mock_enriched_llm_json_response(session_id)++ response = self._make_streaming_request(session_ids=["session_1"], focus_area="checkout flow")+ b"".join(response.streaming_content)++ call_kwargs = mock_execute.call_args[1]+ self.assertIsNotNone(call_kwargs.get("extra_summary_context"))+ self.assertEqual(call_kwargs["extra_summary_context"].focus_area, "checkout flow")++ @patch("ee.api.session_summaries.capture_session_summary_generated")+ @patch("ee.api.session_summaries.capture_session_summary_started")+ @patch("ee.api.session_summaries.execute_summarize_session")+ def test_stream_individually_tracking_generated_success_false_when_all_fail(+ self,+ mock_execute: Mock,+ mock_capture_started: Mock,+ mock_capture_generated: Mock,+ ) -> None:+ mock_execute.side_effect = Exception("summarization failed")++ response = self._make_streaming_request(session_ids=["session_1"])+ b"".join(response.streaming_content)++ mock_capture_generated.assert_called_once()+ generated_kwargs = mock_capture_generated.call_args[1]+ self.assertFalse(generated_kwargs["success"])diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9e294d52964c..1b06c13d4cdf 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3445,6 +3445,9 @@ importers:ai:specifier: ^6.0.0version: 6.0.77([email protected])+ eventsource-parser:+ specifier: ^3.0.0+ version: 3.0.6fflate:specifier: ^0.8.2version: 0.8.2diff --git a/products/replay/mcp/tools.yaml b/products/replay/mcp/tools.yamlindex 52d03bd4e603..4bc221ac7fed 100644--- a/products/replay/mcp/tools.yaml+++ b/products/replay/mcp/tools.yaml@@ -15,6 +15,9 @@ ui_apps:type: detailview_prop: datatools:+ create-session-summaries-individually:+ operation: create_session_summaries_individually+ enabled: falsesession-recording-delete:operation: session_recordings_destroyenabled: true@@ -140,40 +143,6 @@ tools:session-recording-playlists-update:operation: session_recording_playlists_updateenabled: false- session-recording-summarize:- operation: create_session_summaries_individually- enabled: true- scopes:- - session_recording:read- annotations:- readOnly: true- destructive: false- idempotent: true- title: Summarize session recording- 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. `recording_not_found`, `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.--- DEEP 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.- include_params:- - session_ids- - focus_area- ui_app: session-summary- requires_ai_consent: true- feature_flag: replay-video-based-summarizationsession-recordings-list:operation: session_recordings_listenabled: falsediff --git a/services/mcp/package.json b/services/mcp/package.jsonindex e1d7dfd010f4..727ca1616545 100644--- a/services/mcp/package.json+++ b/services/mcp/package.json@@ -40,6 +40,7 @@"@toon-format/toon": "^2.1.0","agents": "0.10.2","ai": "^6.0.0",+ "eventsource-parser": "^3.0.0","fflate": "^0.8.2","mcpcat": "0.1.15","posthog-js-lite": "4.2.2",diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 1413614fd39d..6bb9c8b1f35d 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4229,23 +4229,6 @@"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. `recording_not_found`, `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",- "feature": "replay",- "summary": "Summarize session recording",- "title": "Summarize session recording",- "required_scopes": ["session_recording:read"],- "new_mcp": true,- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": true- },- "requires_ai_consent": true,- "feature_flag": "replay-video-based-summarization"- },"sql-variables-create": {"description": "Create a reusable SQL variable for HogQL queries. Provide a human-readable name and type. The code_name is generated from the name and is referenced in SQL as {variables.code_name}. For List variables, provide values as the allowed options.","category": "Data warehouse",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 9e75cef05cea..8c85a53d8e73 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -4664,21 +4664,21 @@}},"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. `recording_not_found`, `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.",+ "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","feature": "replay",- "summary": "Summarize session recording",+ "summary": "Generate AI-powered summaries of session recordings via streaming.","title": "Summarize session recording","required_scopes": ["session_recording:read"],"new_mcp": true,+ "requires_ai_consent": true,+ "feature_flag": "replay-video-based-summarization","annotations": {"destructiveHint": false,"idempotentHint": true,"openWorldHint": true,"readOnlyHint": true- },- "requires_ai_consent": true,- "feature_flag": "replay-video-based-summarization"+ }},"sql-variables-create": {"description": "Create a reusable SQL variable for HogQL queries. Provide a human-readable name and type. The code_name is generated from the name and is referenced in SQL as {variables.code_name}. For List variables, provide values as the allowed options.",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex 8da32a876daa..ccea2c41fdd1 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -520,5 +520,22 @@"openWorldHint": false,"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",+ "feature": "replay",+ "summary": "Generate AI-powered summaries of session recordings via streaming.",+ "title": "Summarize session recording",+ "required_scopes": ["session_recording:read"],+ "new_mcp": true,+ "requires_ai_consent": true,+ "feature_flag": "replay-video-based-summarization",+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }}}diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.tsindex b240ac0934ac..0f12f3fd8d39 100644--- a/services/mcp/src/api/client.ts+++ b/services/mcp/src/api/client.ts@@ -1,3 +1,4 @@+import { createParser } from 'eventsource-parser'import { z } from 'zod'import { getUserAgent } from '@/lib/constants'@@ -17,6 +18,17 @@ import { isShortId } from '@/tools/insights/utils'import type { Schemas } from './generated.js'import { globalRateLimiter } from './rate-limiter.js'+// Default overall timeout for an SSE stream (wall-clock cap from connect to close).+// Sized to comfortably cover the slowest known caller (session summarization, ~5 min+// average) with headroom for cold-cache LLM calls.+const SSE_DEFAULT_TIMEOUT_MS = 10 * 60 * 1000++// Per-read inactivity timeout: if no chunk (not even a keepalive comment) arrives+// within this window, the server is assumed dead. Must comfortably exceed the+// server-side keepalive interval — kept in sync with `SSE_KEEPALIVE_INTERVAL = 15s`+// in `ee/api/session_summaries.py`. If you change one, check the other.+const SSE_READ_TIMEOUT_MS = 30_000+export interface GroupType {group_type: stringgroup_type_index: number@@ -176,6 +188,92 @@ export class ApiClient {return result.data as T}+ /**+ * Open a Server-Sent Events (text/event-stream) connection and invoke `onEvent`+ * for each parsed event. Resolves when the server closes the stream, throws on+ * HTTP error, missing body, per-read inactivity, or overall stream timeout.+ *+ * Used by tools that consume long-running streaming endpoints (e.g. session+ * summarization) where a synchronous request would exceed gateway timeouts.+ */+ async requestSSE<T = unknown>(opts: {+ method: 'GET' | 'POST'+ path: string+ body?: Record<string, unknown>+ onEvent: (event: string, data: T) => void+ timeoutMs?: number+ }): Promise<void> {+ const url = `${this.baseUrl}${opts.path}`+ const fetchOptions: RequestInit = {+ method: opts.method,+ ...(opts.body ? { body: JSON.stringify(opts.body) } : {}),+ headers: {+ Accept: 'text/event-stream',+ },+ }++ const response = await this.fetch(url, fetchOptions)++ if (!response.ok) {+ const errorText = await response.text()+ throw new Error(+ `SSE request failed:\nURL: ${opts.method} ${url}\nStatus Code: ${response.status} (${response.statusText})\nError Message: ${errorText}`+ )+ }++ if (!response.body) {+ throw new Error(`SSE response has no body: ${opts.method} ${url}`)+ }++ const timeoutMs = opts.timeoutMs ?? SSE_DEFAULT_TIMEOUT_MS+ const readTimeoutMs = SSE_READ_TIMEOUT_MS+ const startTime = Date.now()+ const reader = response.body.getReader()+ const decoder = new TextDecoder()++ const parser = createParser({+ onEvent: ({ event, data }) => {+ const eventType = event ?? 'message'+ try {+ const parsed = JSON.parse(data) as T+ opts.onEvent(eventType, parsed)+ } catch {+ // Non-JSON data, pass as-is+ opts.onEvent(eventType, data as T)+ }+ },+ })++ try {+ while (true) {+ if (Date.now() - startTime > timeoutMs) {+ throw new Error(`SSE stream timed out after ${timeoutMs}ms`)+ }++ let readTimeoutId: ReturnType<typeof setTimeout>+ const readResult = await Promise.race([+ reader.read(),+ new Promise<never>((_, reject) => {+ readTimeoutId = setTimeout(+ () => reject(new Error(`SSE read timed out — no data received for ${readTimeoutMs}ms`)),+ readTimeoutMs+ )+ }),+ ])+ clearTimeout(readTimeoutId!)+ const { done, value } = readResult+ if (done) {+ break+ }++ parser.feed(decoder.decode(value, { stream: true }))+ }+ } finally {+ await reader.cancel()+ reader.releaseLock()+ }+ }+private async fetchJson<T>(url: string, options?: RequestInit): Promise<Result<T>> {const maxRetries = 3const baseBackoffMs = 2000diff --git a/services/mcp/src/generated/replay/api.ts b/services/mcp/src/generated/replay/api.tsindex 451f0cf5a90f..f220650f0a9b 100644--- a/services/mcp/src/generated/replay/api.ts+++ b/services/mcp/src/generated/replay/api.ts@@ -3,39 +3,11 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 7 enabled ops+ * PostHog API - MCP 6 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'-/**- * Generate AI individual summary for each session, without grouping.- */-export const CreateSessionSummariesIndividuallyParams = /* @__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 createSessionSummariesIndividuallyBodySessionIdsMax = 300--export const createSessionSummariesIndividuallyBodyFocusAreaMax = 500--export const CreateSessionSummariesIndividuallyBody = /* @__PURE__ */ zod.object({- session_ids: zod- .array(zod.string())- .min(1)- .max(createSessionSummariesIndividuallyBodySessionIdsMax)- .describe('List of session IDs to summarize (max 300)'),- focus_area: zod- .string()- .max(createSessionSummariesIndividuallyBodyFocusAreaMax)- .optional()- .describe('Optional focus area for the summarization'),-})-/*** Override list to include synthetic playlists*/diff --git a/services/mcp/src/tools/generated/replay.ts b/services/mcp/src/tools/generated/replay.tsindex 16f068bcdda3..dfe489e62fa2 100644--- a/services/mcp/src/tools/generated/replay.ts+++ b/services/mcp/src/tools/generated/replay.ts@@ -3,7 +3,6 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import {- CreateSessionSummariesIndividuallyBody,SessionRecordingPlaylistsCreateBody,SessionRecordingPlaylistsListQueryParams,SessionRecordingPlaylistsPartialUpdateBody,@@ -171,30 +170,6 @@ const sessionRecordingPlaylistsList = (): ToolBase<},})-const SessionRecordingSummarizeSchema = CreateSessionSummariesIndividuallyBody--const sessionRecordingSummarize = (): ToolBase<typeof SessionRecordingSummarizeSchema, Schemas.SessionSummaries> =>- withUiApp('session-summary', {- name: 'session-recording-summarize',- schema: SessionRecordingSummarizeSchema,- handler: async (context: Context, params: z.infer<typeof SessionRecordingSummarizeSchema>) => {- const projectId = await context.stateManager.getProjectId()- const body: Record<string, unknown> = {}- if (params.session_ids !== undefined) {- body['session_ids'] = params.session_ids- }- if (params.focus_area !== undefined) {- body['focus_area'] = params.focus_area- }- const result = await context.api.request<Schemas.SessionSummaries>({- method: 'POST',- path: `/api/environments/${encodeURIComponent(String(projectId))}/session_summaries/create_session_summaries_individually/`,- body,- })- return result- },- })-// --- Query wrapper schemas from schema.json ---const integer = z.coerce.number().int()@@ -642,7 +617,6 @@ 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-summarize': sessionRecordingSummarize,'query-session-recordings-list': createQueryWrapper({name: 'query-session-recordings-list',schema: AssistantRecordingsQuery,diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.tsindex bd01f434a9dc..9ef522b2844c 100644--- a/services/mcp/src/tools/index.ts+++ b/services/mcp/src/tools/index.ts@@ -35,6 +35,8 @@ import generateHogQLFromQuestion from './query/generateHogQLFromQuestion'import queryRun from './query/run'import hogqlSchema from './query/schema'import queryValidate from './query/validate'+// Replay+import sessionRecordingSummarize from './replay/sessionRecordingSummarize'// Searchimport entitySearch from './search/entitySearch'// Misc@@ -88,6 +90,9 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {'read-data-schema': readDataSchema,'read-data-warehouse-schema': readDataWarehouseSchema,+ // Replay+ 'session-recording-summarize': sessionRecordingSummarize,+// Data warehouse (custom handlers for non-standard request shapes)'external-data-sources-db-schema': externalDataSourcesDbSchema,'external-data-sources-jobs': externalDataSourcesJobs,diff --git a/services/mcp/src/tools/replay/sessionRecordingSummarize.ts b/services/mcp/src/tools/replay/sessionRecordingSummarize.tsnew file mode 100644index 000000000000..7c7333cf4486--- /dev/null+++ b/services/mcp/src/tools/replay/sessionRecordingSummarize.ts@@ -0,0 +1,102 @@+import { z } from 'zod'++import { withUiApp } from '@/resources/ui-apps'+import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'+import type { Context, ToolBase } from '@/tools/types'++const schema = z.object({+ session_ids: z.array(z.string()).min(1).max(300).describe('List of session IDs to summarize (max 300)'),+ focus_area: z.string().max(500).optional().describe('Optional focus area for the summarization'),+})++type Params = z.infer<typeof schema>++interface SessionSummary {+ [key: string]: unknown+}++interface SessionError {+ error: string+ error_message: string+}++type SessionResult = SessionSummary | SessionError++interface SummaryEvent {+ session_id: string+ summary: SessionSummary+}++interface ErrorEvent {+ session_id: string+ error: string+ error_message: string+}++interface DoneEvent {+ completed: string[]+ failed: string[]+}++type SseEvent = SummaryEvent | ErrorEvent | DoneEvent++type SseResult = WithPostHogUrl<Record<string, SessionResult>>++/**+ * Hand-written session-recording-summarize tool that uses SSE streaming+ * to avoid gateway timeouts on long-running summary generation (~5 min).+ *+ * Instead of blocking on a single HTTP request, this tool:+ * 1. Calls the streaming endpoint which returns SSE events+ * 2. Accumulates individual session summaries as they complete+ * 3. Returns the full result once the stream ends+ */+const sessionRecordingSummarize = (): ToolBase<typeof schema, SseResult> =>+ withUiApp('session-summary', {+ name: 'session-recording-summarize',+ schema,+ handler: async (context: Context, params: Params): Promise<SseResult> => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = { session_ids: params.session_ids }+ if (params.focus_area !== undefined) {+ body['focus_area'] = params.focus_area+ }++ const results: Record<string, SessionResult> = {}+ let sawDone = false++ await context.api.requestSSE<SseEvent>({+ method: 'POST',+ path: `/api/environments/${encodeURIComponent(String(projectId))}/session_summaries/stream_batch/`,+ body,+ onEvent: (event, data) => {+ if (event === 'summary') {+ const d = data as SummaryEvent+ if (d.session_id && d.summary) {+ results[d.session_id] = d.summary+ }+ } else if (event === 'error') {+ const d = data as ErrorEvent+ if (d.session_id) {+ results[d.session_id] = {+ error: d.error,+ error_message: d.error_message,+ }+ }+ } else if (event === 'done') {+ sawDone = true+ }+ },+ })++ if (!sawDone) {+ throw new Error(+ `SSE stream ended without a done event — results may be incomplete (received ${Object.keys(results).length}/${params.session_ids.length} sessions)`+ )+ }++ return withPostHogUrl(context, results, '/replay')+ },+ })++export default sessionRecordingSummarizediff --git a/services/mcp/tests/unit/requestSSE.test.ts b/services/mcp/tests/unit/requestSSE.test.tsnew file mode 100644index 000000000000..1d588d84b063--- /dev/null+++ b/services/mcp/tests/unit/requestSSE.test.ts@@ -0,0 +1,307 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { ApiClient } from '@/api/client'++vi.mock('@/api/rate-limiter', () => ({+ globalRateLimiter: {+ throttle: vi.fn().mockResolvedValue(undefined),+ },+}))++function createMockStream(chunks: string[]): ReadableStream<Uint8Array> {+ const encoder = new TextEncoder()+ let index = 0+ return new ReadableStream({+ pull(controller) {+ if (index < chunks.length) {+ controller.enqueue(encoder.encode(chunks[index]))+ index+++ } else {+ controller.close()+ }+ },+ })+}++function makeMockFetch(response: Response): typeof fetch {+ return vi.fn().mockResolvedValue(response)+}++describe('ApiClient.requestSSE', () => {+ let client: ApiClient++ beforeEach(() => {+ vi.useFakeTimers()+ client = new ApiClient({+ apiToken: 'test-token',+ baseUrl: 'https://app.posthog.com',+ })+ })++ afterEach(() => {+ vi.clearAllTimers()+ vi.restoreAllMocks()+ vi.useRealTimers()+ })++ it('should parse multiple SSE events and call onEvent for each', async () => {+ const sseBody = [+ 'event: summary\ndata: {"session_id": "abc", "summary": {"key": "value"}}\n\n',+ 'event: summary\ndata: {"session_id": "def", "summary": {"key": "other"}}\n\n',+ 'event: done\ndata: {"completed": ["abc", "def"], "failed": []}\n\n',+ ].join('')++ const mockResponse = new Response(createMockStream([sseBody]), {+ status: 200,+ headers: { 'Content-Type': 'text/event-stream' },+ })+ vi.stubGlobal('fetch', makeMockFetch(mockResponse))++ const onEvent = vi.fn()+ const promise = client.requestSSE({+ method: 'GET',+ path: '/api/stream',+ onEvent,+ })+ await vi.runAllTimersAsync()+ await promise++ expect(onEvent).toHaveBeenCalledTimes(3)+ expect(onEvent).toHaveBeenNthCalledWith(1, 'summary', { session_id: 'abc', summary: { key: 'value' } })+ expect(onEvent).toHaveBeenNthCalledWith(2, 'summary', { session_id: 'def', summary: { key: 'other' } })+ expect(onEvent).toHaveBeenNthCalledWith(3, 'done', { completed: ['abc', 'def'], failed: [] })+ })++ it('should skip keepalive comments and only call onEvent for real events', async () => {+ const sseBody = [+ 'event: summary\ndata: {"session_id": "abc"}\n\n',+ ': keepalive\n\n',+ ': keepalive\n\n',+ 'event: done\ndata: {"completed": ["abc"], "failed": []}\n\n',+ ].join('')++ const mockResponse = new Response(createMockStream([sseBody]), {+ status: 200,+ headers: { 'Content-Type': 'text/event-stream' },+ })+ vi.stubGlobal('fetch', makeMockFetch(mockResponse))++ const onEvent = vi.fn()+ const promise = client.requestSSE({+ method: 'GET',+ path: '/api/stream',+ onEvent,+ })+ await vi.runAllTimersAsync()+ await promise++ expect(onEvent).toHaveBeenCalledTimes(2)+ expect(onEvent).toHaveBeenNthCalledWith(1, 'summary', { session_id: 'abc' })+ expect(onEvent).toHaveBeenNthCalledWith(2, 'done', { completed: ['abc'], failed: [] })+ })++ it('should handle chunked delivery by buffering across chunk boundaries', async () => {+ // Split the first event mid-way across two chunks+ const chunks = [+ 'event: summary\ndata: {"session_id": "abc"',+ '}\n\nevent: done\ndata: {"completed": ["abc"], "failed": []}\n\n',+ ]++ const mockResponse = new Response(createMockStream(chunks), {+ status: 200,+ headers: { 'Content-Type': 'text/event-stream' },+ })+ vi.stubGlobal('fetch', makeMockFetch(mockResponse))++ const onEvent = vi.fn()+ const promise = client.requestSSE({+ method: 'GET',+ path: '/api/stream',+ onEvent,+ })+ await vi.runAllTimersAsync()+ await promise++ expect(onEvent).toHaveBeenCalledTimes(2)+ expect(onEvent).toHaveBeenNthCalledWith(1, 'summary', { session_id: 'abc' })+ expect(onEvent).toHaveBeenNthCalledWith(2, 'done', { completed: ['abc'], failed: [] })+ })++ it('should throw with status code and error text on HTTP error response', async () => {+ const mockResponse = new Response('Unauthorized', {+ status: 401,+ statusText: 'Unauthorized',+ })+ vi.stubGlobal('fetch', makeMockFetch(mockResponse))++ await expect(+ client.requestSSE({+ method: 'GET',+ path: '/api/stream',+ onEvent: vi.fn(),+ })+ ).rejects.toThrow('401')+ })++ it('should throw when response body is missing', async () => {+ const mockResponse = new Response(null, {+ status: 200,+ headers: { 'Content-Type': 'text/event-stream' },+ })+ vi.stubGlobal('fetch', makeMockFetch(mockResponse))++ await expect(+ client.requestSSE({+ method: 'GET',+ path: '/api/stream',+ onEvent: vi.fn(),+ })+ ).rejects.toThrow('SSE response has no body')+ })++ it('should throw "SSE read timed out" when no data arrives within the per-read timeout', async () => {+ // Mock the reader so that read() rejects with the per-read timeout error.+ // This directly tests the observable behavior (the error thrown) without+ // relying on fake timers, which would leave dangling timer promises in the+ // cloudflare-workers test environment.+ const mockReader = {+ read: vi.fn().mockRejectedValue(new Error('SSE read timed out — no data received for 30000ms')),+ cancel: vi.fn().mockResolvedValue(undefined),+ releaseLock: vi.fn(),+ }+ const mockBody = {+ getReader: vi.fn().mockReturnValue(mockReader),+ }+ const mockResponse = {+ ok: true,+ body: mockBody,+ text: vi.fn(),+ } as unknown as Response+ vi.stubGlobal('fetch', makeMockFetch(mockResponse))++ await expect(+ client.requestSSE({+ method: 'GET',+ path: '/api/stream',+ onEvent: vi.fn(),+ })+ ).rejects.toThrow('SSE read timed out')+ })++ it('should throw "SSE stream timed out" when overall timeout is exceeded', async () => {+ // Strategy: mock the reader so both read() calls resolve quickly (with keepalives),+ // but advance the fake clock past timeoutMs between calls so the overall timeout+ // check at the top of the loop fires on the second iteration.+ const encoder = new TextEncoder()+ const keepaliveChunk = encoder.encode(': keepalive\n\n')+ const shortTimeoutMs = 500++ // Use a deferred promise for the second read so we can resolve it after+ // advancing the clock, giving the loop a chance to reach the top-of-loop+ // overall timeout check on the next iteration.+ let resolveSecondRead!: (value: ReadableStreamReadResult<Uint8Array>) => void+ const secondReadPromise = new Promise<ReadableStreamReadResult<Uint8Array>>((resolve) => {+ resolveSecondRead = resolve+ })++ const mockReader = {+ read: vi+ .fn()+ .mockResolvedValueOnce({ done: false, value: keepaliveChunk })+ .mockReturnValueOnce(secondReadPromise),+ cancel: vi.fn().mockResolvedValue(undefined),+ releaseLock: vi.fn(),+ }+ const mockBody = {+ getReader: vi.fn().mockReturnValue(mockReader),+ }+ const mockResponse = {+ ok: true,+ body: mockBody,+ text: vi.fn(),+ } as unknown as Response+ vi.stubGlobal('fetch', makeMockFetch(mockResponse))++ const promise = client.requestSSE({+ method: 'GET',+ path: '/api/stream',+ onEvent: vi.fn(),+ timeoutMs: shortTimeoutMs,+ })++ // Advance the clock past the overall timeout, then resolve the second read+ // to unblock the loop so it can reach the top-of-loop timeout check.+ await vi.advanceTimersByTimeAsync(shortTimeoutMs + 1)+ resolveSecondRead({ done: false, value: keepaliveChunk })++ await expect(promise).rejects.toThrow(`SSE stream timed out after ${shortTimeoutMs}ms`)+ })++ it('should pass raw string to onEvent when event data is not valid JSON', async () => {+ const sseBody = 'event: status\ndata: plain text not json\n\n'++ const mockResponse = new Response(createMockStream([sseBody]), {+ status: 200,+ headers: { 'Content-Type': 'text/event-stream' },+ })+ vi.stubGlobal('fetch', makeMockFetch(mockResponse))++ const onEvent = vi.fn()+ const promise = client.requestSSE({+ method: 'GET',+ path: '/api/stream',+ onEvent,+ })+ await vi.runAllTimersAsync()+ await promise++ expect(onEvent).toHaveBeenCalledTimes(1)+ expect(onEvent).toHaveBeenCalledWith('status', 'plain text not json')+ })++ it('should send Accept: text/event-stream header', async () => {+ const mockFetch = vi.fn().mockResolvedValue(+ new Response(createMockStream([]), {+ status: 200,+ headers: { 'Content-Type': 'text/event-stream' },+ })+ )+ vi.stubGlobal('fetch', mockFetch)++ const promise = client.requestSSE({+ method: 'POST',+ path: '/api/stream',+ body: { session_id: 'abc' },+ onEvent: vi.fn(),+ })+ await vi.runAllTimersAsync()+ await promise++ expect(mockFetch).toHaveBeenCalledOnce()+ const [, options] = mockFetch.mock.calls[0]!+ const headers = options.headers as Record<string, string>+ expect(headers['Accept']).toBe('text/event-stream')+ })++ it('should default event type to "message" when event line is absent', async () => {+ const sseBody = 'data: {"value": 42}\n\n'++ const mockResponse = new Response(createMockStream([sseBody]), {+ status: 200,+ headers: { 'Content-Type': 'text/event-stream' },+ })+ vi.stubGlobal('fetch', makeMockFetch(mockResponse))++ const onEvent = vi.fn()+ const promise = client.requestSSE({+ method: 'GET',+ path: '/api/stream',+ onEvent,+ })+ await vi.runAllTimersAsync()+ await promise++ expect(onEvent).toHaveBeenCalledOnce()+ expect(onEvent).toHaveBeenCalledWith('message', { value: 42 })+ })+})