: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(surveys): make surveys a 1st-class MCP citizen (responses, summarize, list, lifecycle, stats) (#59947)
Lucas Fariaebb834900968
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex c1ad3d3c1136..542944218465 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -77,6 +77,7 @@ from products.feature_flags.backend.api.feature_flag import (from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_analytics.backend.models.insight import Insightfrom products.surveys.backend.models import MAX_ITERATION_COUNT, Survey, SurveyResponseArchive, ensure_question_ids+from products.surveys.backend.responses import fetch_per_question_stats, fetch_response_rowsfrom products.surveys.backend.summarization import fetch_responses, format_as_markdown, summarize_responsesfrom products.surveys.backend.translation import generate_survey_translationfrom products.surveys.backend.util import (@@ -601,6 +602,151 @@ class SurveyConditionsSchemaSerializer(serializers.Serializer):)+class SurveySummarizeRequestSerializer(serializers.Serializer):+ force_refresh = serializers.BooleanField(+ required=False,+ default=False,+ help_text="When true, bypass cached summaries and regenerate. Defaults to false.",+ )+++class SurveyResponseAnswerSerializer(serializers.Serializer):+ question_id = serializers.CharField(help_text="UUID of the survey question this answer belongs to.")+ question_index = serializers.IntegerField(help_text="Zero-based index of the question within the survey.")+ question_text = serializers.CharField(+ allow_blank=True, help_text="Untranslated question text as configured by the survey author."+ )+ question_type = serializers.CharField(+ help_text=(+ "Question type: open, rating, single_choice, multiple_choice, or link. "+ "Determines the shape of the answer field."+ ),+ )+ answer = serializers.JSONField(+ help_text=(+ "Resolved answer. String for open/rating/single_choice/link questions, "+ "list of strings for multiple_choice questions. Already decoded from the "+ "raw $survey_response_<id> property so callers don't need to parse it."+ )+ )+++class SurveyResponseExtraSerializer(serializers.Serializer):+ device_type = serializers.CharField(+ allow_null=True, allow_blank=True, required=False, help_text="$device_type at the time the response was sent."+ )+ browser = serializers.CharField(+ allow_null=True, allow_blank=True, required=False, help_text="$browser at the time the response was sent."+ )+ os = serializers.CharField(+ allow_null=True,+ allow_blank=True,+ required=False,+ help_text="$os (operating system) at the time the response was sent.",+ )+ geoip_country_code = serializers.CharField(+ allow_null=True, allow_blank=True, required=False, help_text="$geoip_country_code at submission time."+ )+ geoip_country_name = serializers.CharField(+ allow_null=True, allow_blank=True, required=False, help_text="$geoip_country_name at submission time."+ )+ geoip_city_name = serializers.CharField(+ allow_null=True, allow_blank=True, required=False, help_text="$geoip_city_name at submission time."+ )+ current_url = serializers.CharField(+ allow_null=True, allow_blank=True, required=False, help_text="$current_url where the survey was submitted."+ )+ iteration = serializers.CharField(+ allow_null=True,+ allow_blank=True,+ required=False,+ help_text="Survey iteration number when the response was sent. Only set for recurring surveys.",+ )+++class SurveyResponseRowSerializer(serializers.Serializer):+ uuid = serializers.CharField(+ help_text="UUID of the underlying `survey sent` event. Use as the response identifier for archive operations."+ )+ distinct_id = serializers.CharField(+ help_text="distinct_id of the respondent. Cross-pivot to the persons API or session recordings."+ )+ session_id = serializers.CharField(+ allow_null=True,+ help_text="$session_id of the respondent when available. Use to pull the session recording for this response.",+ )+ submitted_at = serializers.DateTimeField(help_text="Event timestamp when the response was sent (ISO 8601, UTC).")+ answers = SurveyResponseAnswerSerializer(+ many=True,+ help_text=(+ "One entry per survey question that received a non-empty answer. Question text is already resolved — "+ "callers do not need to look up `$survey_response_<id>` keys."+ ),+ )+ extra = SurveyResponseExtraSerializer(+ help_text="Convenience fields extracted from the event properties (device, browser, geoip, iteration)."+ )+++class SurveyResponsesQuerySerializer(serializers.Serializer):+ since = serializers.DateTimeField(+ required=False,+ help_text="Only return responses submitted on or after this ISO 8601 timestamp.",+ )+ until = serializers.DateTimeField(+ required=False,+ help_text="Only return responses submitted on or before this ISO 8601 timestamp.",+ )+ question_id = serializers.CharField(+ required=False,+ help_text=(+ "If set, only return rows where this question has a non-empty answer, and only include that question's "+ "answer in each row. Required when using score_lte or score_gte."+ ),+ )+ score_lte = serializers.FloatField(+ required=False,+ help_text=(+ "Filter to rows where the rating answer for `question_id` is <= this value. "+ "Common use: NPS detractors with score_lte=6. Requires question_id."+ ),+ )+ score_gte = serializers.FloatField(+ required=False,+ help_text=(+ "Filter to rows where the rating answer for `question_id` is >= this value. "+ "Common use: NPS promoters with score_gte=9. Requires question_id."+ ),+ )+ exclude_archived = serializers.BooleanField(+ required=False,+ default=False,+ help_text="When true, exclude responses that have been archived via the archive_response endpoint.",+ )+ limit = serializers.IntegerField(+ required=False,+ default=100,+ min_value=1,+ max_value=500,+ help_text="Maximum number of rows to return (1-500). Defaults to 100.",+ )+ offset = serializers.IntegerField(+ required=False,+ default=0,+ min_value=0,+ help_text="Number of rows to skip for pagination. Combine with `limit` and the `has_more` field to paginate.",+ )+++class SurveyResponsesListSerializer(serializers.Serializer):+ results = SurveyResponseRowSerializer(many=True, help_text="Survey response rows for the requested page.")+ has_more = serializers.BooleanField(+ help_text="True if more rows exist beyond the current page — fetch the next page with offset + limit."+ )+ limit = serializers.IntegerField(help_text="The limit applied to this query (echoed back for pagination).")+ offset = serializers.IntegerField(help_text="The offset applied to this query (echoed back for pagination).")++class SurveySerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):linked_flag_id = serializers.IntegerField(required=False, allow_null=True, source="linked_flag.id")linked_flag = MinimalFeatureFlagSerializer(read_only=True)@@ -1869,7 +2015,7 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets."linked_flag", "linked_insight", "targeting_flag", "internal_targeting_flag").all()filter_backends = [DjangoFilterBackend]- filterset_fields = ["archived"]+ filterset_fields = ["archived", "type"]def get_serializer_class(self) -> type[serializers.Serializer]:if self.request.method == "POST" or self.request.method == "PATCH":@@ -1961,6 +2107,104 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.return super().destroy(request, *args, **kwargs)+ @extend_schema(+ operation_id="surveys_launch",+ description=(+ "Launch a survey by setting `start_date` to the current time. No-op if the survey is already launched "+ "(start_date set in the past) — returns the existing state unchanged. Does not affect archived surveys "+ "or surveys with an end_date in the past; unarchive or extend the end_date first."+ ),+ request=None,+ responses={200: SurveySerializer},+ )+ @action(methods=["POST"], detail=True, required_scopes=["survey:write"])+ def launch(self, request: request.Request, **kwargs: Any) -> Response:+ survey = self.get_object()+ now = datetime.now(UTC)+ if survey.archived:+ raise exceptions.ValidationError("Cannot launch an archived survey. Unarchive it first.")+ if survey.end_date and survey.end_date <= now:+ raise exceptions.ValidationError(+ "Cannot launch a survey with end_date in the past. Extend the end_date first."+ )+ if survey.start_date and survey.start_date <= now:+ # Already launched — no-op, return current state.+ return Response(SurveySerializer(survey, context=self.get_serializer_context()).data)++ previous_start = survey.start_date+ survey.start_date = now+ survey.save(update_fields=["start_date"])++ log_activity(+ organization_id=self.organization.id,+ team_id=self.team_id,+ user=cast(User, self.request.user),+ was_impersonated=is_impersonated_session(request),+ item_id=survey.id,+ scope="Survey",+ activity="launched",+ detail=Detail(+ name=survey.name,+ changes=[+ Change(+ type="Survey",+ action="changed",+ field="start_date",+ before=previous_start,+ after=survey.start_date,+ )+ ],+ ),+ )++ return Response(SurveySerializer(survey, context=self.get_serializer_context()).data)++ @extend_schema(+ operation_id="surveys_stop",+ description=(+ "Stop a survey by setting `end_date` to the current time. No new responses are accepted after this; "+ "existing responses remain available. No-op if the survey already has an end_date in the past."+ ),+ request=None,+ responses={200: SurveySerializer},+ )+ @action(methods=["POST"], detail=True, required_scopes=["survey:write"])+ def stop(self, request: request.Request, **kwargs: Any) -> Response:+ survey = self.get_object()+ now = datetime.now(UTC)+ if survey.archived:+ raise exceptions.ValidationError("Cannot stop an archived survey. Unarchive it first if needed.")+ if survey.end_date and survey.end_date <= now:+ return Response(SurveySerializer(survey, context=self.get_serializer_context()).data)++ previous_end = survey.end_date+ survey.end_date = now+ survey.save(update_fields=["end_date"])++ log_activity(+ organization_id=self.organization.id,+ team_id=self.team_id,+ user=cast(User, self.request.user),+ was_impersonated=is_impersonated_session(request),+ item_id=survey.id,+ scope="Survey",+ activity="stopped",+ detail=Detail(+ name=survey.name,+ changes=[+ Change(+ type="Survey",+ action="changed",+ field="end_date",+ before=previous_end,+ after=survey.end_date,+ )+ ],+ ),+ )++ return Response(SurveySerializer(survey, context=self.get_serializer_context()).data)+def _get_partial_responses_filter(self, base_conditions_sql: builtins.list[str]) -> str:unique_uuids_subquery = get_unique_survey_event_uuids_sql_subquery(base_conditions_sql=base_conditions_sql,@@ -2388,6 +2632,15 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.required=False,description="Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)",),+ OpenApiParameter(+ "include_per_question_stats",+ OpenApiTypes.BOOL,+ required=False,+ description=(+ "When true, also return per-question response counts and answer distributions. "+ "Adds one extra HogQL query per question, so leave off unless you need the breakdown."+ ),+ ),],responses={200: inline_serializer(@@ -2404,6 +2657,15 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.help_text="Event counts keyed by event name (survey shown, survey dismissed, survey sent)."),"rates": serializers.DictField(help_text="Calculated response and dismissal rates."),+ "per_question_stats": serializers.ListField(+ required=False,+ help_text=(+ "Per-question response counts and distributions. Only present when "+ "include_per_question_stats=true was passed. For rating questions includes `average`; "+ "for choice/rating questions `distribution` maps answer value to count; for open "+ "questions `distribution` is empty (use surveys-responses-list to read free-text)."+ ),+ ),},)},@@ -2416,6 +2678,7 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.date_from: Optional ISO timestamp for start date (e.g. 2024-01-01T00:00:00Z)date_to: Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)exclude_archived: Optional boolean to exclude archived responses (default: false, includes archived)+ include_per_question_stats: Optional boolean to include per-question response counts and distributionsReturns:Survey statistics including event counts, unique respondents, and conversion rates@@ -2424,6 +2687,7 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.date_from = request.query_params.get("date_from", None)date_to = request.query_params.get("date_to", None)exclude_archived = request.query_params.get("exclude_archived", "false").lower() == "true"+ include_per_question_stats = request.query_params.get("include_per_question_stats", "false").lower() == "true"try:survey = self.get_object()@@ -2437,6 +2701,27 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.response_data["start_date"] = survey.start_dateresponse_data["end_date"] = survey.end_date+ if include_per_question_stats:+ try:+ from_ts = datetime.fromisoformat(date_from) if date_from else None+ to_ts = datetime.fromisoformat(date_to) if date_to else None+ except ValueError:+ from_ts = None+ to_ts = None+ per_question = fetch_per_question_stats(survey=survey, team=self.team, since=from_ts, until=to_ts)+ response_data["per_question_stats"] = [+ {+ "question_id": q.question_id,+ "question_index": q.question_index,+ "question_text": q.question_text,+ "question_type": q.question_type,+ "response_count": q.response_count,+ "distribution": q.distribution,+ "average": q.average,+ }+ for q in per_question+ ]+return Response(response_data)@action(@@ -2519,6 +2804,82 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.uuids = get_archived_response_uuids(str(survey.id), self.team_id)return Response(list(uuids))+ @extend_schema(+ operation_id="surveys_responses_list",+ description=(+ "List survey responses for a specific survey, with question text resolved server-side so callers do not "+ "have to map opaque `$survey_response_<id>` keys. Each row carries `distinct_id`, `session_id`, "+ "`submitted_at`, and an `extra` block (device, browser, OS, geoip, current_url, iteration) so agents can "+ "cross-pivot to recordings, persons, or paths in a single follow-up call. For person properties at "+ "event time, follow up with `persons-get` using the returned `distinct_id` — keeps scopes scoped. "+ "Use `question_id` + `score_lte` to fetch NPS detractors and similar score-filtered cohorts."+ ),+ parameters=[SurveyResponsesQuerySerializer],+ responses={200: SurveyResponsesListSerializer},+ )+ @action(methods=["GET"], detail=True, url_path="responses", required_scopes=["survey:read", "query:read"])+ def survey_responses_list(self, request: request.Request, **kwargs) -> Response:+ survey = self.get_object()++ params = SurveyResponsesQuerySerializer(data=request.query_params)+ params.is_valid(raise_exception=True)+ cleaned = params.validated_data++ # score_lte / score_gte only make sense for a specific rating question — reject the+ # combination at the API boundary rather than letting the HogQL helper raise later.+ if (cleaned.get("score_lte") is not None or cleaned.get("score_gte") is not None) and not cleaned.get(+ "question_id"+ ):+ raise exceptions.ValidationError("score_lte and score_gte require question_id to be specified")++ exclude_uuids: set[str] | None = None+ if cleaned.get("exclude_archived"):+ exclude_uuids = get_archived_response_uuids(str(survey.id), self.team_id)++ rows, has_more = fetch_response_rows(+ survey=survey,+ team=self.team,+ since=cleaned.get("since"),+ until=cleaned.get("until"),+ question_id=cleaned.get("question_id"),+ score_lte=cleaned.get("score_lte"),+ score_gte=cleaned.get("score_gte"),+ limit=cleaned.get("limit", 100),+ offset=cleaned.get("offset", 0),+ exclude_uuids=exclude_uuids,+ )++ tag_queries(product=ProductKey.SURVEYS, feature=Feature.QUERY)++ serialized = SurveyResponsesListSerializer(+ instance={+ "results": [+ {+ "uuid": row.uuid,+ "distinct_id": row.distinct_id,+ "session_id": row.session_id,+ "submitted_at": row.submitted_at,+ "answers": [+ {+ "question_id": a.question_id,+ "question_index": a.question_index,+ "question_text": a.question_text,+ "question_type": a.question_type,+ "answer": a.answer,+ }+ for a in row.answers+ ],+ "extra": row.extra,+ }+ for row in rows+ ],+ "has_more": has_more,+ "limit": cleaned.get("limit", 100),+ "offset": cleaned.get("offset", 0),+ }+ )+ return Response(serialized.data)+@extend_schema(operation_id="surveys_question_labels",description=(@@ -2658,6 +3019,32 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.)return activity_page_response(activity_page, limit, page, request)+ @extend_schema(+ description=(+ "Summarize survey responses. When `question_index` or `question_id` is provided, returns a per-question "+ "theme summary using cached `survey.question_summaries` when fresh. When neither is provided, returns "+ "the survey-wide headline summary (delegates to summary_headline). Pass `force_refresh=true` in the body "+ "to bypass caches."+ ),+ # request= is critical here — without it drf-spectacular falls back to the default ModelViewSet serializer+ # (SurveySerializerCreateUpdateOnly) and generates a Zod schema demanding name/type fields that have nothing+ # to do with summarization.+ request=SurveySummarizeRequestSerializer,+ parameters=[+ OpenApiParameter(+ "question_index",+ OpenApiTypes.INT,+ required=False,+ description="Zero-based question index. Omit to get the survey-wide headline instead.",+ ),+ OpenApiParameter(+ "question_id",+ OpenApiTypes.STR,+ required=False,+ description="Question UUID. Preferred over question_index — stable across question edits.",+ ),+ ],+ )@action(methods=["POST"], detail=True, required_scopes=["survey:read"])def summarize_responses(self, request: request.Request, **kwargs):if not request.user.is_authenticated:@@ -2681,7 +3068,9 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.question_id = request.query_params.get("question_id", None)if question_index is None and question_id is None:- raise exceptions.ValidationError("question_index or question_id is required")+ # No question specified — dispatch to the survey-wide headline summarizer.+ # Keeps a single MCP tool surface for both per-question and whole-survey summarization.+ return self.summary_headline(request, **kwargs)# Check for force_refresh flag in request bodyforce_refresh = request.data.get("force_refresh", False)@@ -2711,6 +3100,13 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.if not environment_is_allowed or not has_gemini_api_key:raise exceptions.ValidationError("survey summary is only supported in PostHog Cloud")+ # Same AI-processing gate that summary_headline uses — applies to per-question summaries too.+ if not self.team.organization.is_ai_data_processing_approved:+ return Response(+ {"error": "AI data processing must be approved to generate summaries"},+ status=status.HTTP_403_FORBIDDEN,+ )+end_date: datetime = (survey.end_date or datetime.now()).replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex 0431621da89a..c540f6a6026e 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -6524,6 +6524,334 @@ class TestSurveyResponseArchive(ClickhouseTestMixin, APIBaseTest):self.assertNotIn(uuid3, uuids)+class TestSurveyResponsesList(ClickhouseTestMixin, APIBaseTest):+ def setUp(self):+ super().setUp()+ self.question_id_text = str(uuid.uuid4())+ self.question_id_rating = str(uuid.uuid4())+ self.survey = Survey.objects.create(+ team=self.team,+ name="NPS",+ type="popover",+ questions=[+ {"id": self.question_id_rating, "type": "rating", "question": "How likely are you to recommend us?"},+ {"id": self.question_id_text, "type": "open", "question": "Why?"},+ ],+ start_date=datetime(2024, 5, 1, tzinfo=UTC),+ )+ self.url = f"/api/projects/{self.team.id}/surveys/{self.survey.id}/responses/"++ def _create_response_event(self, distinct_id, timestamp, rating, text, submission_id=None, event_uuid=None):+ properties: dict[str, Any] = {+ "$survey_id": str(self.survey.id),+ f"$survey_response_{self.question_id_rating}": rating,+ f"$survey_response_{self.question_id_text}": text,+ "$session_id": "sess-1",+ "$device_type": "Mobile",+ "$geoip_country_code": "US",+ }+ if submission_id:+ properties["$survey_submission_id"] = submission_id+ kwargs = {+ "team": self.team,+ "event": "survey sent",+ "distinct_id": distinct_id,+ "timestamp": timestamp,+ "properties": properties,+ }+ if event_uuid:+ kwargs["event_uuid"] = event_uuid+ _create_event(**kwargs)++ def test_nonexistent_survey_returns_404(self):+ response = self.client.get(f"/api/projects/{self.team.id}/surveys/{uuid.uuid4()}/responses/")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ def test_empty_results_when_no_events(self):+ response = self.client.get(self.url)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertEqual(data["results"], [])+ self.assertFalse(data["has_more"])+ self.assertEqual(data["limit"], 100)+ self.assertEqual(data["offset"], 0)++ def test_returns_rows_with_resolved_question_text(self):+ person = Person.objects.create(team=self.team, distinct_ids=["user-1"])+ self._create_response_event("user-1", "2024-06-10 09:05:00", "9", "Loved the UX")+ flush_persons_and_events()++ response = self.client.get(self.url)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertEqual(len(data["results"]), 1)+ row = data["results"][0]+ self.assertEqual(row["distinct_id"], "user-1")+ self.assertEqual(row["session_id"], "sess-1")+ self.assertEqual(row["extra"]["device_type"], "Mobile")+ self.assertEqual(row["extra"]["geoip_country_code"], "US")+ # Question text is resolved, not opaque $survey_response_<id>+ answers_by_id = {a["question_id"]: a for a in row["answers"]}+ self.assertEqual(answers_by_id[self.question_id_rating]["question_text"], "How likely are you to recommend us?")+ self.assertEqual(answers_by_id[self.question_id_rating]["answer"], "9")+ self.assertEqual(answers_by_id[self.question_id_text]["question_text"], "Why?")+ self.assertEqual(answers_by_id[self.question_id_text]["answer"], "Loved the UX")+ # Person properties off by default+ # Person properties intentionally not exposed on this endpoint — agents should call+ # persons-get with the row's distinct_id to fetch person data under the right scope.+ self.assertNotIn("person_properties", row)+ assert person # silence unused++ def test_score_lte_filters_detractors(self):+ Person.objects.create(team=self.team, distinct_ids=["detractor"])+ Person.objects.create(team=self.team, distinct_ids=["promoter"])+ self._create_response_event("detractor", "2024-06-10 09:05:00", "3", "Frustrating")+ self._create_response_event("promoter", "2024-06-10 09:06:00", "10", "Amazing")+ flush_persons_and_events()++ response = self.client.get(self.url, {"question_id": self.question_id_rating, "score_lte": "6"})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertEqual(len(data["results"]), 1)+ self.assertEqual(data["results"][0]["distinct_id"], "detractor")+ # When question_id is set, only that question's answer is returned per row+ self.assertEqual(len(data["results"][0]["answers"]), 1)+ self.assertEqual(data["results"][0]["answers"][0]["question_id"], self.question_id_rating)++ def test_score_filter_without_question_id_returns_400(self):+ response = self.client.get(self.url, {"score_lte": "6"})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_pagination_has_more(self):+ Person.objects.create(team=self.team, distinct_ids=["u-1"])+ Person.objects.create(team=self.team, distinct_ids=["u-2"])+ Person.objects.create(team=self.team, distinct_ids=["u-3"])+ self._create_response_event("u-1", "2024-06-10 09:01:00", "8", "a")+ self._create_response_event("u-2", "2024-06-10 09:02:00", "8", "b")+ self._create_response_event("u-3", "2024-06-10 09:03:00", "8", "c")+ flush_persons_and_events()++ response = self.client.get(self.url, {"limit": "2"})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertEqual(len(data["results"]), 2)+ self.assertTrue(data["has_more"])++ response2 = self.client.get(self.url, {"limit": "2", "offset": "2"})+ data2 = response2.json()+ self.assertEqual(len(data2["results"]), 1)+ self.assertFalse(data2["has_more"])++ def test_since_filter(self):+ Person.objects.create(team=self.team, distinct_ids=["old"])+ Person.objects.create(team=self.team, distinct_ids=["new"])+ self._create_response_event("old", "2024-06-01 09:00:00", "8", "old")+ self._create_response_event("new", "2024-06-15 09:00:00", "8", "new")+ flush_persons_and_events()++ response = self.client.get(self.url, {"since": "2024-06-10T00:00:00Z"})+ data = response.json()+ self.assertEqual(len(data["results"]), 1)+ self.assertEqual(data["results"][0]["distinct_id"], "new")++ def test_exclude_archived(self):+ Person.objects.create(team=self.team, distinct_ids=["kept"])+ Person.objects.create(team=self.team, distinct_ids=["archived"])+ archived_uuid = str(uuid.uuid4())+ self._create_response_event("kept", "2024-06-10 09:05:00", "8", "kept")+ self._create_response_event("archived", "2024-06-10 09:06:00", "3", "archived", event_uuid=archived_uuid)+ SurveyResponseArchive.objects.create(team=self.team, survey=self.survey, response_uuid=archived_uuid)+ flush_persons_and_events()++ response = self.client.get(self.url, {"exclude_archived": "true"})+ data = response.json()+ self.assertEqual(len(data["results"]), 1)+ self.assertEqual(data["results"][0]["distinct_id"], "kept")+++class TestSurveySummarizeDispatchesToHeadline(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.survey = Survey.objects.create(+ team=self.team,+ name="Test",+ type="popover",+ questions=[{"id": "q1", "type": "open", "question": "Why?"}],+ )++ @patch("products.surveys.backend.api.survey.generate_survey_headline")+ def test_summarize_with_no_question_delegates_to_headline(self, mock_headline):+ mock_headline.return_value = {"headline": "Users love it", "responses_sampled": 12, "has_more": False}+ self.team.organization.is_ai_data_processing_approved = True+ self.team.organization.save()++ response = self.client.post(f"/api/projects/{self.team.id}/surveys/{self.survey.id}/summarize_responses/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertEqual(data["headline"], "Users love it")+ self.assertEqual(data["responses_sampled"], 12)+ mock_headline.assert_called_once()+++class TestSurveyLifecycleActions(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.survey = Survey.objects.create(+ team=self.team,+ name="Lifecycle",+ type="popover",+ questions=[{"type": "open", "question": "Q?"}],+ )++ def test_launch_sets_start_date(self):+ self.assertIsNone(self.survey.start_date)+ response = self.client.post(f"/api/projects/{self.team.id}/surveys/{self.survey.id}/launch/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.survey.refresh_from_db()+ self.assertIsNotNone(self.survey.start_date)+ # Verify the response includes the updated start_date+ self.assertIsNotNone(response.json()["start_date"])++ def test_launch_is_idempotent_when_already_launched(self):+ original_start = datetime(2024, 1, 1, tzinfo=UTC)+ self.survey.start_date = original_start+ self.survey.save()+ response = self.client.post(f"/api/projects/{self.team.id}/surveys/{self.survey.id}/launch/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.survey.refresh_from_db()+ # start_date should not have moved+ self.assertEqual(self.survey.start_date, original_start)++ def test_stop_sets_end_date(self):+ self.survey.start_date = datetime(2024, 1, 1, tzinfo=UTC)+ self.survey.save()+ response = self.client.post(f"/api/projects/{self.team.id}/surveys/{self.survey.id}/stop/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.survey.refresh_from_db()+ self.assertIsNotNone(self.survey.end_date)++ def test_launch_rejects_archived_survey(self):+ self.survey.archived = True+ self.survey.save()+ response = self.client.post(f"/api/projects/{self.team.id}/surveys/{self.survey.id}/launch/")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_launch_rejects_ended_survey(self):+ self.survey.start_date = datetime(2024, 1, 1, tzinfo=UTC)+ self.survey.end_date = datetime(2024, 2, 1, tzinfo=UTC)+ self.survey.save()+ response = self.client.post(f"/api/projects/{self.team.id}/surveys/{self.survey.id}/launch/")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_stop_rejects_archived_survey(self):+ self.survey.archived = True+ self.survey.save()+ response = self.client.post(f"/api/projects/{self.team.id}/surveys/{self.survey.id}/stop/")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_stop_is_idempotent_when_already_stopped(self):+ original_end = datetime(2024, 1, 1, tzinfo=UTC)+ self.survey.start_date = datetime(2023, 12, 1, tzinfo=UTC)+ self.survey.end_date = original_end+ self.survey.save()+ response = self.client.post(f"/api/projects/{self.team.id}/surveys/{self.survey.id}/stop/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.survey.refresh_from_db()+ self.assertEqual(self.survey.end_date, original_end)+++class TestSurveyListTypeFilter(APIBaseTest):+ def test_filter_by_type(self):+ Survey.objects.create(team=self.team, name="popover survey", type="popover", questions=[])+ Survey.objects.create(team=self.team, name="widget survey", type="widget", questions=[])+ Survey.objects.create(team=self.team, name="hosted survey", type="external_survey", questions=[])++ response = self.client.get(f"/api/projects/{self.team.id}/surveys/?type=widget")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertEqual(len(data["results"]), 1)+ self.assertEqual(data["results"][0]["name"], "widget survey")+++class TestSurveyStatsPerQuestion(ClickhouseTestMixin, APIBaseTest):+ def setUp(self):+ super().setUp()+ self.rating_qid = str(uuid.uuid4())+ self.choice_qid = str(uuid.uuid4())+ self.open_qid = str(uuid.uuid4())+ self.survey = Survey.objects.create(+ team=self.team,+ name="Per Q",+ type="popover",+ questions=[+ {"id": self.rating_qid, "type": "rating", "question": "1-10 rating?"},+ {+ "id": self.choice_qid,+ "type": "single_choice",+ "question": "Pick one",+ "choices": ["yes", "no"],+ "hasOpenChoice": True,+ },+ {"id": self.open_qid, "type": "open", "question": "Free text"},+ ],+ start_date=datetime(2024, 5, 1, tzinfo=UTC),+ )++ def test_per_question_stats_excluded_by_default(self):+ response = self.client.get(f"/api/projects/{self.team.id}/surveys/{self.survey.id}/stats/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertNotIn("per_question_stats", response.json())++ def test_per_question_stats_when_requested(self):+ Person.objects.create(team=self.team, distinct_ids=["u-1"])+ Person.objects.create(team=self.team, distinct_ids=["u-2"])+ Person.objects.create(team=self.team, distinct_ids=["u-3"])+ # u-4 picks the open-choice "Other" with free text — must be redacted to <other>.+ Person.objects.create(team=self.team, distinct_ids=["u-4"])+ for distinct_id, rating, choice, text in [+ ("u-1", "9", "yes", "Loved it"),+ ("u-2", "7", "yes", "Good"),+ ("u-3", "3", "no", ""),+ ("u-4", "5", "my own private reason", "Meh"),+ ]:+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id=distinct_id,+ timestamp="2024-06-10 09:00:00",+ properties={+ "$survey_id": str(self.survey.id),+ f"$survey_response_{self.rating_qid}": rating,+ f"$survey_response_{self.choice_qid}": choice,+ f"$survey_response_{self.open_qid}": text,+ },+ )+ flush_persons_and_events()++ response = self.client.get(+ f"/api/projects/{self.team.id}/surveys/{self.survey.id}/stats/?include_per_question_stats=true"+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ per_q = {q["question_id"]: q for q in response.json()["per_question_stats"]}++ # Rating: 4 responses, distribution by value+ self.assertEqual(per_q[self.rating_qid]["response_count"], 4)+ self.assertEqual(per_q[self.rating_qid]["question_type"], "rating")+ self.assertAlmostEqual(per_q[self.rating_qid]["average"], (9 + 7 + 3 + 5) / 4, places=2)+ self.assertEqual(per_q[self.rating_qid]["distribution"], {"9": 1, "7": 1, "3": 1, "5": 1})++ # Choice: 4 responses. Configured choices ("yes"/"no") shown by value; the free-text+ # open-choice answer is redacted into <other> (its count is kept, the text is not).+ self.assertEqual(per_q[self.choice_qid]["response_count"], 4)+ self.assertEqual(per_q[self.choice_qid]["distribution"], {"yes": 2, "no": 1, "<other>": 1})+ self.assertNotIn("my own private reason", per_q[self.choice_qid]["distribution"])+ self.assertIsNone(per_q[self.choice_qid]["average"])++ # Open: 3 responses (one user left it blank), no distribution+ self.assertEqual(per_q[self.open_qid]["response_count"], 3)+ self.assertEqual(per_q[self.open_qid]["distribution"], {})++class TestSurveyFeatureFlagScopeWarning(PersonalAPIKeysBaseTest, APIBaseTest):SURVEY_PAYLOAD = {"name": "Scope warning survey",diff --git a/products/surveys/backend/responses/__init__.py b/products/surveys/backend/responses/__init__.pynew file mode 100644index 000000000000..3d18d9212179--- /dev/null+++ b/products/surveys/backend/responses/__init__.py@@ -0,0 +1,14 @@+from products.surveys.backend.responses.fetch_rows import (+ SurveyResponseRow,+ fetch_response_rows,+ resolve_question_metadata,+)+from products.surveys.backend.responses.per_question_stats import PerQuestionStats, fetch_per_question_stats++__all__ = [+ "PerQuestionStats",+ "SurveyResponseRow",+ "fetch_per_question_stats",+ "fetch_response_rows",+ "resolve_question_metadata",+]diff --git a/products/surveys/backend/responses/fetch_rows.py b/products/surveys/backend/responses/fetch_rows.pynew file mode 100644index 000000000000..b25f7991e47c--- /dev/null+++ b/products/surveys/backend/responses/fetch_rows.py@@ -0,0 +1,229 @@+"""Fetch full survey response rows (with metadata) for the responses API.++The summarization fetch helper returns response strings only — sufficient for LLM+input but not for agents that need to cross-pivot to recordings, events, or persons.+This module returns rows with `distinct_id`, `session_id`, `submitted_at`, resolved+per-question answers, and event-level metadata (device, geoip, etc).+"""++from dataclasses import dataclass, field+from datetime import UTC, datetime+from typing import Any, cast++from posthog.hogql import ast+from posthog.hogql.parser import parse_select++from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator+from posthog.models import Team++from products.surveys.backend.models import Survey+++@dataclass(frozen=True)+class QuestionAnswer:+ question_id: str+ question_index: int+ question_text: str+ question_type: str+ answer: Any+++@dataclass(frozen=True)+class SurveyResponseRow:+ uuid: str+ distinct_id: str+ session_id: str | None+ submitted_at: datetime+ answers: list[QuestionAnswer]+ extra: dict[str, Any] = field(default_factory=dict)+++def resolve_question_metadata(survey: Survey) -> list[dict[str, Any]]:+ """Return survey questions with stable `(id, index, text, type, choices)` shape."""+ questions = survey.questions or []+ resolved: list[dict[str, Any]] = []+ for index, question in enumerate(questions):+ if not isinstance(question, dict):+ continue+ resolved.append(+ {+ "id": question.get("id") or "",+ "index": index,+ "text": question.get("question") or "",+ "type": question.get("type") or "open",+ "choices": question.get("choices"),+ }+ )+ return resolved+++# Metadata columns appended to every row — known $-prefixed event properties resolved via+# HogQL property accessors (backticked because the keys are literal property names, not+# placeholder values).+_METADATA_COLUMNS: list[tuple[str, str]] = [+ ("session_id", "properties.`$session_id`"),+ ("device_type", "properties.`$device_type`"),+ ("browser", "properties.`$browser`"),+ ("os", "properties.`$os`"),+ ("geoip_country_code", "properties.`$geoip_country_code`"),+ ("geoip_country_name", "properties.`$geoip_country_name`"),+ ("geoip_city_name", "properties.`$geoip_city_name`"),+ ("current_url", "properties.`$current_url`"),+ ("iteration", "properties.`$survey_iteration`"),+]+++def fetch_response_rows(+ *,+ survey: Survey,+ team: Team,+ since: datetime | None = None,+ until: datetime | None = None,+ question_id: str | None = None,+ score_lte: float | None = None,+ score_gte: float | None = None,+ limit: int = 100,+ offset: int = 0,+ exclude_uuids: set[str] | None = None,+) -> tuple[list[SurveyResponseRow], bool]:+ """Fetch survey response rows for the responses API.++ `score_lte` / `score_gte` require `question_id` — score filtering only+ makes sense against a specific rating question.+ """+ if (score_lte is not None or score_gte is not None) and not question_id:+ raise ValueError("score_lte / score_gte require question_id")++ survey_id = str(survey.id)+ questions = resolve_question_metadata(survey)++ questions_in_scope = [q for q in questions if (not question_id or q["id"] == question_id)]+ if question_id and not questions_in_scope:+ return [], False++ paginator = HogQLHasMorePaginator(limit=limit, offset=offset)++ placeholders: dict[str, ast.Expr] = {+ "survey_id": ast.Constant(value=survey_id),+ # uniqueSurveySubmissionsFilter requires bounded dates — fall back to+ # the survey lifetime when the caller didn't supply explicit bounds.+ "start_date": ast.Constant(value=since or survey.start_date or survey.created_at),+ "end_date": ast.Constant(value=until or survey.end_date or datetime.now(UTC)),+ }++ # Dynamically add one column per question using the HogQL getSurveyResponse helper —+ # the same helper the summarization fetch uses, so the resolution semantics match.+ answer_columns: list[str] = []+ for q in questions_in_scope:+ idx_name = f"q_idx_{q['index']}"+ id_name = f"q_id_{q['index']}"+ answer_columns.append(f"getSurveyResponse({{{idx_name}}}, {{{id_name}}}) AS answer_{q['index']}")+ placeholders[idx_name] = ast.Constant(value=q["index"])+ placeholders[id_name] = ast.Constant(value=q["id"])++ select_clause = ", ".join(+ [+ "uuid",+ "distinct_id",+ "timestamp AS submitted_at",+ *(f"{expr} AS {alias}" for alias, expr in _METADATA_COLUMNS),+ *answer_columns,+ ]+ )++ conditions = [+ "event = 'survey sent'",+ "properties.`$survey_id` = {survey_id}",+ "uniqueSurveySubmissionsFilter({survey_id}, {start_date}, {end_date})",+ ]++ if since is not None:+ conditions.append("timestamp >= {since}")+ placeholders["since"] = ast.Constant(value=since)+ if until is not None:+ conditions.append("timestamp <= {until}")+ placeholders["until"] = ast.Constant(value=until)++ if question_id:+ # Only return rows where this question has a non-empty answer.+ # coalesce-then-trim defends against NULL semantics in HogQL — without it the+ # equivalent `trim(...) != ''` predicate evaluates to NULL for nullified responses+ # and is silently ignored in some contexts.+ target_q = next(q for q in questions_in_scope if q["id"] == question_id)+ conditions.append(+ "length(trim(coalesce(getSurveyResponse({filter_q_idx}, {filter_q_id}), ''))) > 0",+ )+ placeholders["filter_q_idx"] = ast.Constant(value=target_q["index"])+ placeholders["filter_q_id"] = ast.Constant(value=target_q["id"])++ if score_lte is not None:+ conditions.append("toFloat(getSurveyResponse({filter_q_idx}, {filter_q_id})) <= {score_lte}")+ placeholders["score_lte"] = ast.Constant(value=score_lte)+ if score_gte is not None:+ conditions.append("toFloat(getSurveyResponse({filter_q_idx}, {filter_q_id})) >= {score_gte}")+ placeholders["score_gte"] = ast.Constant(value=score_gte)++ if exclude_uuids:+ conditions.append("uuid NOT IN {exclude_uuids}")+ placeholders["exclude_uuids"] = ast.Tuple(exprs=[ast.Constant(value=u) for u in exclude_uuids])++ query_str = f"""+ SELECT {select_clause}+ FROM events+ WHERE {" AND ".join(conditions)}+ ORDER BY timestamp DESC+ """++ select_ast = cast(ast.SelectQuery, parse_select(query_str, placeholders))+ paginator.execute_hogql_query(+ team=team,+ query_type="survey_responses_rows_query",+ query=select_ast,+ )++ # Column order matches the SELECT list above. The metadata columns slot in between+ # the fixed leading 3 (uuid, distinct_id, submitted_at) and the per-question answer columns.+ metadata_offset = 3 # uuid, distinct_id, submitted_at+ answer_offset = metadata_offset + len(_METADATA_COLUMNS)++ rows: list[SurveyResponseRow] = []+ for raw in paginator.results:+ uuid_val, distinct_id, submitted_at = raw[0], raw[1], raw[2]++ extra: dict[str, Any] = {}+ session_id: str | None = None+ for i, (alias, _) in enumerate(_METADATA_COLUMNS):+ value = raw[metadata_offset + i]+ if alias == "session_id":+ session_id = str(value) if value else None+ else:+ # Pass empty/null through as None to keep payloads clean for agents.+ extra[alias] = value if value not in (None, "") else None++ answers: list[QuestionAnswer] = []+ for i, q in enumerate(questions_in_scope):+ value = raw[answer_offset + i]+ if value in (None, ""):+ continue+ answers.append(+ QuestionAnswer(+ question_id=q["id"],+ question_index=q["index"],+ question_text=q["text"],+ question_type=q["type"],+ answer=value,+ )+ )++ rows.append(+ SurveyResponseRow(+ uuid=str(uuid_val),+ distinct_id=str(distinct_id),+ session_id=session_id,+ submitted_at=submitted_at,+ answers=answers,+ extra=extra,+ )+ )++ return rows, paginator.has_more()diff --git a/products/surveys/backend/responses/per_question_stats.py b/products/surveys/backend/responses/per_question_stats.pynew file mode 100644index 000000000000..3d6309eeacea--- /dev/null+++ b/products/surveys/backend/responses/per_question_stats.py@@ -0,0 +1,176 @@+"""Per-question response aggregation for the survey-stats endpoint."""++from dataclasses import dataclass, field+from datetime import UTC, datetime+from typing import cast++from posthog.hogql import ast+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.models import Team++from products.surveys.backend.models import Survey+from products.surveys.backend.responses.fetch_rows import resolve_question_metadata+++@dataclass(frozen=True)+class PerQuestionStats:+ question_id: str+ question_index: int+ question_text: str+ question_type: str+ response_count: int+ distribution: dict[str, int] = field(default_factory=dict)+ average: float | None = None+++def fetch_per_question_stats(+ *,+ survey: Survey,+ team: Team,+ since: datetime | None = None,+ until: datetime | None = None,+) -> list[PerQuestionStats]:+ """Aggregate response counts and distributions per survey question.++ Runs one HogQL query per question (typically <=10 questions per survey),+ using the same `getSurveyResponse` helper the summarization fetch uses+ so question ID / index resolution matches the rest of the surveys API.+ For choice/rating questions distribution is by answer value;+ for open questions distribution is empty — callers should fall back to+ survey-responses-list to read the actual text.+ """+ questions = resolve_question_metadata(survey)+ if not questions:+ return []++ survey_id = str(survey.id)+ start_date = since or survey.start_date or survey.created_at+ end_date = until or survey.end_date or datetime.now(UTC)++ results: list[PerQuestionStats] = []+ for q in questions:+ question_id, question_index = q["id"], q["index"]+ question_type = q["type"]++ placeholders: dict[str, ast.Expr] = {+ "survey_id": ast.Constant(value=survey_id),+ "start_date": ast.Constant(value=start_date),+ "end_date": ast.Constant(value=end_date),+ "q_idx": ast.Constant(value=question_index),+ "q_id": ast.Constant(value=question_id),+ }++ # For open questions: just count non-empty responses — distribution across free-text+ # answers isn't meaningful and reading them is what survey-responses-list is for.+ #+ # Use coalesce(..., '') before trim so the count is correct when getSurveyResponse+ # resolves to NULL (e.g. via its nullIf path) — `NULL != ''` is NULL, which would+ # filter the row implicitly but doesn't always behave consistently in count contexts.+ if question_type == "open":+ query_str = """+ SELECT countIf(length(trim(coalesce(getSurveyResponse({q_idx}, {q_id}), ''))) > 0) AS n+ FROM events+ WHERE event = 'survey sent'+ AND properties.`$survey_id` = {survey_id}+ AND timestamp >= {start_date}+ AND timestamp <= {end_date}+ AND uniqueSurveySubmissionsFilter({survey_id}, {start_date}, {end_date})+ """+ select_ast = cast(ast.SelectQuery, parse_select(query_str, placeholders))+ response = execute_hogql_query(+ query=select_ast,+ team=team,+ query_type="survey_per_question_stats_open_query",+ )+ count_val = int(response.results[0][0]) if response.results else 0+ results.append(+ PerQuestionStats(+ question_id=question_id,+ question_index=question_index,+ question_text=q["text"],+ question_type=question_type,+ response_count=count_val,+ )+ )+ continue++ # For rating/choice: aggregate by answer value to get a distribution.+ # Same defensive coalesce as the open branch — filter out NULL and empty before grouping.+ query_str = """+ SELECT getSurveyResponse({q_idx}, {q_id}) AS answer, count() AS n+ FROM events+ WHERE event = 'survey sent'+ AND properties.`$survey_id` = {survey_id}+ AND timestamp >= {start_date}+ AND timestamp <= {end_date}+ AND uniqueSurveySubmissionsFilter({survey_id}, {start_date}, {end_date})+ AND length(trim(coalesce(getSurveyResponse({q_idx}, {q_id}), ''))) > 0+ GROUP BY answer+ ORDER BY n DESC+ LIMIT 200+ """+ select_ast = cast(ast.SelectQuery, parse_select(query_str, placeholders))+ response = execute_hogql_query(+ query=select_ast,+ team=team,+ query_type="survey_per_question_stats_grouped_query",+ )++ # For choice questions, only the configured answer values are safe to expose under+ # `survey:read` — any value outside that set is user-entered free text (e.g. a+ # `hasOpenChoice` "Other: ___" response) and would leak respondent-entered content.+ # Bucket free-text answers under "<other>" so callers still see how many people picked+ # "Other" without exposing the text itself. Reading the text requires the responses+ # endpoint, which requires `query:read`.+ allowed_choices: set[str] | None = None+ if question_type in ("single_choice", "multiple_choice"):+ choices = q.get("choices") or []+ allowed_choices = set(choices) if choices else set()++ distribution: dict[str, int] = {}+ total_count = 0+ rating_sum = 0.0+ rating_count = 0+ other_count = 0+ for row in response.results:+ answer_raw, count_n = row[0], int(row[1])+ answer_str = str(answer_raw) if answer_raw is not None else ""+ if not answer_str:+ continue++ if allowed_choices is not None and answer_str not in allowed_choices:+ # Free-text "Other" — keep the count but not the value.+ other_count += count_n+ total_count += count_n+ continue++ distribution[answer_str] = count_n+ total_count += count_n+ if question_type == "rating":+ try:+ rating_sum += float(answer_str) * count_n+ rating_count += count_n+ except ValueError:+ # Non-numeric rating answer — skip from avg, keep in distribution.+ continue++ if other_count:+ distribution["<other>"] = other_count++ average = (rating_sum / rating_count) if rating_count else None++ results.append(+ PerQuestionStats(+ question_id=question_id,+ question_index=question_index,+ question_text=q["text"],+ question_type=question_type,+ response_count=total_count,+ distribution=distribution,+ average=average,+ )+ )++ return resultsdiff --git a/products/surveys/frontend/generated/api.schemas.ts b/products/surveys/frontend/generated/api.schemas.tsindex 4356223fc4ff..740f813273ce 100644--- a/products/surveys/frontend/generated/api.schemas.ts+++ b/products/surveys/frontend/generated/api.schemas.ts@@ -1960,6 +1960,91 @@ export interface GenerateSurveyTranslationsResponseApi {trace_id: string}+export interface SurveyResponseAnswerApi {+ /** UUID of the survey question this answer belongs to. */+ question_id: string+ /** Zero-based index of the question within the survey. */+ question_index: number+ /** Untranslated question text as configured by the survey author. */+ question_text: string+ /** Question type: open, rating, single_choice, multiple_choice, or link. Determines the shape of the answer field. */+ question_type: string+ /** Resolved answer. String for open/rating/single_choice/link questions, list of strings for multiple_choice questions. Already decoded from the raw $survey_response_<id> property so callers don't need to parse it. */+ answer: unknown+}++export interface SurveyResponseExtraApi {+ /**+ * $device_type at the time the response was sent.+ * @nullable+ */+ device_type?: string | null+ /**+ * $browser at the time the response was sent.+ * @nullable+ */+ browser?: string | null+ /**+ * $os (operating system) at the time the response was sent.+ * @nullable+ */+ os?: string | null+ /**+ * $geoip_country_code at submission time.+ * @nullable+ */+ geoip_country_code?: string | null+ /**+ * $geoip_country_name at submission time.+ * @nullable+ */+ geoip_country_name?: string | null+ /**+ * $geoip_city_name at submission time.+ * @nullable+ */+ geoip_city_name?: string | null+ /**+ * $current_url where the survey was submitted.+ * @nullable+ */+ current_url?: string | null+ /**+ * Survey iteration number when the response was sent. Only set for recurring surveys.+ * @nullable+ */+ iteration?: string | null+}++export interface SurveyResponseRowApi {+ /** UUID of the underlying `survey sent` event. Use as the response identifier for archive operations. */+ uuid: string+ /** distinct_id of the respondent. Cross-pivot to the persons API or session recordings. */+ distinct_id: string+ /**+ * $session_id of the respondent when available. Use to pull the session recording for this response.+ * @nullable+ */+ session_id: string | null+ /** Event timestamp when the response was sent (ISO 8601, UTC). */+ submitted_at: string+ /** One entry per survey question that received a non-empty answer. Question text is already resolved — callers do not need to look up `$survey_response_<id>` keys. */+ answers: SurveyResponseAnswerApi[]+ /** Convenience fields extracted from the event properties (device, browser, geoip, iteration). */+ extra: SurveyResponseExtraApi+}++export interface SurveyResponsesListApi {+ /** Survey response rows for the requested page. */+ results: SurveyResponseRowApi[]+ /** True if more rows exist beyond the current page — fetch the next page with offset + limit. */+ has_more: boolean+ /** The limit applied to this query (echoed back for pagination). */+ limit: number+ /** The offset applied to this query (echoed back for pagination). */+ offset: number+}+/*** Event counts keyed by event name (survey shown, survey dismissed, survey sent).*/@@ -1987,6 +2072,13 @@ export interface SurveyStatsResponseApi {stats: SurveyStatsResponseApiStats/** Calculated response and dismissal rates. */rates: SurveyStatsResponseApiRates+ /** Per-question response counts and distributions. Only present when include_per_question_stats=true was passed. For rating questions includes `average`; for choice/rating questions `distribution` maps answer value to count; for open questions `distribution` is empty (use surveys-responses-list to read free-text). */+ per_question_stats?: unknown[]+}++export interface SurveySummarizeRequestApi {+ /** When true, bypass cached summaries and regenerate. Defaults to false. */+ force_refresh?: boolean}export interface SurveyQuestionLabelApi {@@ -2038,6 +2130,61 @@ export type SurveysListParams = {* Fuzzy match against survey `name` and `description` using Postgres trigram word similarity. Supports typos and prefix-as-you-type.*/search?: string+ /**+ * * `popover` - popover+ * `widget` - widget+ * `external_survey` - external survey+ * `api` - api+ */+ type?: SurveysListType+}++export type SurveysListType = (typeof SurveysListType)[keyof typeof SurveysListType]++export const SurveysListType = {+ Api: 'api',+ ExternalSurvey: 'external_survey',+ Popover: 'popover',+ Widget: 'widget',+} as const++export type SurveysResponsesListParams = {+ /**+ * When true, exclude responses that have been archived via the archive_response endpoint.+ */+ exclude_archived?: boolean+ /**+ * Maximum number of rows to return (1-500). Defaults to 100.+ * @minimum 1+ * @maximum 500+ */+ limit?: number+ /**+ * Number of rows to skip for pagination. Combine with `limit` and the `has_more` field to paginate.+ * @minimum 0+ */+ offset?: number+ /**+ * If set, only return rows where this question has a non-empty answer, and only include that question's answer in each row. Required when using score_lte or score_gte.+ * @minLength 1+ */+ question_id?: string+ /**+ * Filter to rows where the rating answer for `question_id` is >= this value. Common use: NPS promoters with score_gte=9. Requires question_id.+ */+ score_gte?: number+ /**+ * Filter to rows where the rating answer for `question_id` is <= this value. Common use: NPS detractors with score_lte=6. Requires question_id.+ */+ score_lte?: number+ /**+ * Only return responses submitted on or after this ISO 8601 timestamp.+ */+ since?: string+ /**+ * Only return responses submitted on or before this ISO 8601 timestamp.+ */+ until?: string}export type SurveysStatsRetrieveParams = {@@ -2049,6 +2196,21 @@ export type SurveysStatsRetrieveParams = {* Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)*/date_to?: string+ /**+ * When true, also return per-question response counts and answer distributions. Adds one extra HogQL query per question, so leave off unless you need the breakdown.+ */+ include_per_question_stats?: boolean+}++export type SurveysSummarizeResponsesCreateParams = {+ /**+ * Question UUID. Preferred over question_index — stable across question edits.+ */+ question_id?: string+ /**+ * Zero-based question index. Omit to get the survey-wide headline instead.+ */+ question_index?: number}export type SurveysGlobalStatsRetrieveParams = {diff --git a/products/surveys/frontend/generated/api.ts b/products/surveys/frontend/generated/api.tsindex 881632df7aa9..3bf208d04c4b 100644--- a/products/surveys/frontend/generated/api.ts+++ b/products/surveys/frontend/generated/api.ts@@ -16,12 +16,16 @@ import type {SurveyApi,SurveyGlobalStatsResponseApi,SurveyQuestionLabelsResponseApi,+ SurveyResponsesListApi,SurveySerializerCreateUpdateOnlyApi,SurveySerializerCreateUpdateOnlySchemaApi,SurveyStatsResponseApi,+ SurveySummarizeRequestApi,SurveysGlobalStatsRetrieveParams,SurveysListParams,+ SurveysResponsesListParams,SurveysStatsRetrieveParams,+ SurveysSummarizeResponsesCreateParams,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -217,6 +221,51 @@ export const surveysGenerateTranslationsCreate = async (})}+export const getSurveysLaunchUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/surveys/${id}/launch/`+}++/**+ * Launch a survey by setting `start_date` to the current time. No-op if the survey is already launched (start_date set in the past) — returns the existing state unchanged. Does not affect archived surveys or surveys with an end_date in the past; unarchive or extend the end_date first.+ */+export const surveysLaunch = async (projectId: string, id: string, options?: RequestInit): Promise<SurveyApi> => {+ return apiMutator<SurveyApi>(getSurveysLaunchUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}++export const getSurveysResponsesListUrl = (projectId: string, id: string, params?: SurveysResponsesListParams) => {+ 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}/surveys/${id}/responses/?${stringifiedParams}`+ : `/api/projects/${projectId}/surveys/${id}/responses/`+}++/**+ * List survey responses for a specific survey, with question text resolved server-side so callers do not have to map opaque `$survey_response_<id>` keys. Each row carries `distinct_id`, `session_id`, `submitted_at`, and an `extra` block (device, browser, OS, geoip, current_url, iteration) so agents can cross-pivot to recordings, persons, or paths in a single follow-up call. For person properties at event time, follow up with `persons-get` using the returned `distinct_id` — keeps scopes scoped. Use `question_id` + `score_lte` to fetch NPS detractors and similar score-filtered cohorts.+ */+export const surveysResponsesList = async (+ projectId: string,+ id: string,+ params?: SurveysResponsesListParams,+ options?: RequestInit+): Promise<SurveyResponsesListApi> => {+ return apiMutator<SurveyResponsesListApi>(getSurveysResponsesListUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}+export const getSurveysResponsesArchiveCreateUrl = (projectId: string, id: string, responseUuid: string) => {return `/api/projects/${projectId}/surveys/${id}/responses/${responseUuid}/archive/`}@@ -284,6 +333,7 @@ Args:date_from: Optional ISO timestamp for start date (e.g. 2024-01-01T00:00:00Z)date_to: Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)exclude_archived: Optional boolean to exclude archived responses (default: false, includes archived)+ include_per_question_stats: Optional boolean to include per-question response counts and distributionsReturns:Survey statistics including event counts, unique respondents, and conversion rates@@ -300,21 +350,55 @@ export const surveysStatsRetrieve = async (})}-export const getSurveysSummarizeResponsesCreateUrl = (projectId: string, id: string) => {- return `/api/projects/${projectId}/surveys/${id}/summarize_responses/`+export const getSurveysStopUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/surveys/${id}/stop/`}+/**+ * Stop a survey by setting `end_date` to the current time. No new responses are accepted after this; existing responses remain available. No-op if the survey already has an end_date in the past.+ */+export const surveysStop = async (projectId: string, id: string, options?: RequestInit): Promise<SurveyApi> => {+ return apiMutator<SurveyApi>(getSurveysStopUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}++export const getSurveysSummarizeResponsesCreateUrl = (+ projectId: string,+ id: string,+ params?: SurveysSummarizeResponsesCreateParams+) => {+ 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}/surveys/${id}/summarize_responses/?${stringifiedParams}`+ : `/api/projects/${projectId}/surveys/${id}/summarize_responses/`+}++/**+ * Summarize survey responses. When `question_index` or `question_id` is provided, returns a per-question theme summary using cached `survey.question_summaries` when fresh. When neither is provided, returns the survey-wide headline summary (delegates to summary_headline). Pass `force_refresh=true` in the body to bypass caches.+ */export const surveysSummarizeResponsesCreate = async (projectId: string,id: string,- surveySerializerCreateUpdateOnlyApi: NonReadonly<SurveySerializerCreateUpdateOnlyApi>,+ surveySummarizeRequestApi?: SurveySummarizeRequestApi,+ params?: SurveysSummarizeResponsesCreateParams,options?: RequestInit): Promise<void> => {- return apiMutator<void>(getSurveysSummarizeResponsesCreateUrl(projectId, id), {+ return apiMutator<void>(getSurveysSummarizeResponsesCreateUrl(projectId, id, params), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(surveySerializerCreateUpdateOnlyApi),+ body: JSON.stringify(surveySummarizeRequestApi),})}diff --git a/products/surveys/frontend/generated/api.zod.ts b/products/surveys/frontend/generated/api.zod.tsindex 44753673eeb7..16163e24ed67 100644--- a/products/surveys/frontend/generated/api.zod.ts+++ b/products/surveys/frontend/generated/api.zod.ts@@ -2027,106 +2027,16 @@ export const SurveysResponsesUnarchiveCreateBody = /* @__PURE__ */ zod.object({form_content: zod.unknown().optional(),})-export const surveysSummarizeResponsesCreateBodyNameMax = 400--export const surveysSummarizeResponsesCreateBodyResponsesLimitMin = 0-export const surveysSummarizeResponsesCreateBodyResponsesLimitMax = 2147483647--export const surveysSummarizeResponsesCreateBodyIterationCountMin = 0-export const surveysSummarizeResponsesCreateBodyIterationCountMax = 500--export const surveysSummarizeResponsesCreateBodyIterationFrequencyDaysMin = 0-export const surveysSummarizeResponsesCreateBodyIterationFrequencyDaysMax = 2147483647--export const surveysSummarizeResponsesCreateBodyCurrentIterationMin = 0-export const surveysSummarizeResponsesCreateBodyCurrentIterationMax = 2147483647--export const surveysSummarizeResponsesCreateBodyResponseSamplingIntervalMin = 0-export const surveysSummarizeResponsesCreateBodyResponseSamplingIntervalMax = 2147483647--export const surveysSummarizeResponsesCreateBodyResponseSamplingLimitMin = 0-export const surveysSummarizeResponsesCreateBodyResponseSamplingLimitMax = 2147483647--export const surveysSummarizeResponsesCreateBodyBaseLanguageMax = 20+/**+ * Summarize survey responses. When `question_index` or `question_id` is provided, returns a per-question theme summary using cached `survey.question_summaries` when fresh. When neither is provided, returns the survey-wide headline summary (delegates to summary_headline). Pass `force_refresh=true` in the body to bypass caches.+ */+export const surveysSummarizeResponsesCreateBodyForceRefreshDefault = falseexport const SurveysSummarizeResponsesCreateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(surveysSummarizeResponsesCreateBodyNameMax),- description: zod.string().optional(),- type: zod- .enum(['popover', 'widget', 'external_survey', 'api'])- .describe(- '\* `popover` - popover\n\* `widget` - widget\n\* `external_survey` - external survey\n\* `api` - api'- ),- schedule: zod.string().nullish(),- linked_flag_id: zod.number().nullish(),- linked_insight_id: zod.number().nullish(),- targeting_flag_id: zod.number().optional(),- targeting_flag_filters: zod.unknown().optional(),- remove_targeting_flag: zod.boolean().nullish(),- questions: zod- .unknown()- .optional()- .describe(- '\n The `array` of questions included in the survey. Each question must conform to one of the defined question types: Basic, Link, Rating, or Multiple Choice.\n\n Basic (open-ended question)\n - `id`: The question ID\n - `type`: `open`\n - `question`: The text of the question.\n - `description`: Optional description of the question.\n - `descriptionContentType`: Content type of the description (`html` or `text`).\n - `optional`: Whether the question is optional (`boolean`).\n - `buttonText`: Text displayed on the submit button.\n - `branching`: Branching logic for the question. See branching types below for details.\n\n Link (a question with a link)\n - `id`: The question ID\n - `type`: `link`\n - `question`: The text of the question.\n - `description`: Optional description of the question.\n - `descriptionContentType`: Content type of the description (`html` or `text`).\n - `optional`: Whether the question is optional (`boolean`).\n - `buttonText`: Text displayed on the submit button.\n - `link`: The URL associated with the question.\n - `branching`: Branching logic for the question. See branching types below for details.\n\n Rating (a question with a rating scale)\n - `id`: The question ID\n - `type`: `rating`\n - `question`: The text of the question.\n - `description`: Optional description of the question.\n - `descriptionContentType`: Content type of the description (`html` or `text`).\n - `optional`: Whether the question is optional (`boolean`).\n - `buttonText`: Text displayed on the submit button.\n - `display`: Display style of the rating (`number` or `emoji`).\n - `scale`: The scale of the rating (`number`).\n - `lowerBoundLabel`: Label for the lower bound of the scale.\n - `upperBoundLabel`: Label for the upper bound of the scale.\n - `isNpsQuestion`: Whether the question is an NPS rating.\n - `branching`: Branching logic for the question. See branching types below for details.\n\n Multiple choice\n - `id`: The question ID\n - `type`: `single_choice` or `multiple_choice`\n - `question`: The text of the question.\n - `description`: Optional description of the question.\n - `descriptionContentType`: Content type of the description (`html` or `text`).\n - `optional`: Whether the question is optional (`boolean`).\n - `buttonText`: Text displayed on the submit button.\n - `choices`: An array of choices for the question.\n - `shuffleOptions`: Whether to shuffle the order of the choices (`boolean`).\n - `hasOpenChoice`: Whether the question allows an open-ended response (`boolean`).\n - `branching`: Branching logic for the question. See branching types below for details.\n\n Branching logic can be one of the following types:\n\n Next question: Proceeds to the next question\n ```json\n {\n \"type\": \"next_question\"\n }\n ```\n\n End: Ends the survey, optionally displaying a confirmation message.\n ```json\n {\n \"type\": \"end\"\n }\n ```\n\n Response-based: Branches based on the response values. Available for the `rating` and `single_choice` question types.\n ```json\n {\n \"type\": \"response_based\",\n \"responseValues\": {\n \"responseKey\": \"value\"\n }\n }\n ```\n\n Specific question: Proceeds to a specific question by index.\n ```json\n {\n \"type\": \"specific_question\",\n \"index\": 2\n }\n ```\n\n Translations: Each question can include inline translations.\n - `translations`: Object mapping language codes to translated fields.\n - Language codes: Canonical BCP-47-ish strings (e.g., \"es\", \"es-MX\", \"zh-CN\"). Aliases like \"english\" or \"default\" are rejected. The survey\'s `base_language` (default \"en\") declares the language of the untranslated text and cannot also appear as a translation key.\n - Translatable fields: `question`, `description`, `buttonText`, `choices`, `lowerBoundLabel`, `upperBoundLabel`, `link`\n\n Example with translations:\n ```json\n {\n \"id\": \"uuid\",\n \"type\": \"rating\",\n \"question\": \"How satisfied are you?\",\n \"lowerBoundLabel\": \"Not satisfied\",\n \"upperBoundLabel\": \"Very satisfied\",\n \"translations\": {\n \"es\": {\n \"question\": \"¿Qué tan satisfecho estás?\",\n \"lowerBoundLabel\": \"No satisfecho\",\n \"upperBoundLabel\": \"Muy satisfecho\"\n },\n \"fr\": {\n \"question\": \"Dans quelle mesure êtes-vous satisfait?\"\n }\n }\n }\n ```\n '- ),- conditions: zod.unknown().optional(),- appearance: zod.unknown().optional(),- start_date: zod.iso.datetime({ offset: true }).nullish(),- end_date: zod.iso.datetime({ offset: true }).nullish(),- archived: zod.boolean().optional(),- responses_limit: zod- .number()- .min(surveysSummarizeResponsesCreateBodyResponsesLimitMin)- .max(surveysSummarizeResponsesCreateBodyResponsesLimitMax)- .nullish(),- iteration_count: zod- .number()- .min(surveysSummarizeResponsesCreateBodyIterationCountMin)- .max(surveysSummarizeResponsesCreateBodyIterationCountMax)- .nullish(),- iteration_frequency_days: zod- .number()- .min(surveysSummarizeResponsesCreateBodyIterationFrequencyDaysMin)- .max(surveysSummarizeResponsesCreateBodyIterationFrequencyDaysMax)- .nullish(),- iteration_start_dates: zod.array(zod.iso.datetime({ offset: true }).nullable()).nullish(),- current_iteration: zod- .number()- .min(surveysSummarizeResponsesCreateBodyCurrentIterationMin)- .max(surveysSummarizeResponsesCreateBodyCurrentIterationMax)- .nullish(),- current_iteration_start_date: zod.iso.datetime({ offset: true }).nullish(),- response_sampling_start_date: zod.iso.datetime({ offset: true }).nullish(),- response_sampling_interval_type: zod- .union([- zod.enum(['day', 'week', 'month']).describe('\* `day` - day\n\* `week` - week\n\* `month` - month'),- zod.enum(['']),- zod.null(),- ])- .optional(),- response_sampling_interval: zod- .number()- .min(surveysSummarizeResponsesCreateBodyResponseSamplingIntervalMin)- .max(surveysSummarizeResponsesCreateBodyResponseSamplingIntervalMax)- .nullish(),- response_sampling_limit: zod- .number()- .min(surveysSummarizeResponsesCreateBodyResponseSamplingLimitMin)- .max(surveysSummarizeResponsesCreateBodyResponseSamplingLimitMax)- .nullish(),- response_sampling_daily_limits: zod.unknown().optional(),- enable_partial_responses: zod.boolean().nullish(),- enable_iframe_embedding: zod.boolean().nullish(),- base_language: zod- .string()- .max(surveysSummarizeResponsesCreateBodyBaseLanguageMax)- .optional()- .describe(- "BCP-47 language code (e.g. 'en', 'es', 'es-MX') describing the language of the survey's untranslated text. Defaults to 'en'. Cannot also appear as a key in `translations`."- ),- translations: zod.unknown().optional(),- _create_in_folder: zod.string().optional(),- form_content: zod.unknown().optional(),+ force_refresh: zod+ .boolean()+ .default(surveysSummarizeResponsesCreateBodyForceRefreshDefault)+ .describe('When true, bypass cached summaries and regenerate. Defaults to false.'),})export const surveysSummaryHeadlineCreateBodyNameMax = 400diff --git a/products/surveys/mcp/tools.yaml b/products/surveys/mcp/tools.yamlindex a8ce5f310611..bb3f8c94932c 100644--- a/products/surveys/mcp/tools.yaml+++ b/products/surveys/mcp/tools.yaml@@ -132,6 +132,22 @@ tools:Get a specific survey by ID. Returns the survey configuration including questions, targeting, and schedulingdetails.ui_app: survey+ survey-launch:+ operation: surveys_launch+ enabled: true+ scopes:+ - survey:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ enrich_url: '{id}'+ title: Launch a survey now.+ description: >+ Launch a survey by setting `start_date` to the current time. Prefer this over `survey-update` with a manual+ `start_date` — it's an explicit lifecycle action and self-documenting in activity logs. No-op if the survey+ is already launched.+ ui_app: surveysurvey-stats:operation: surveys_stats_retrieveenabled: true@@ -147,6 +163,23 @@ tools:Get response statistics for a specific survey. Includes detailed event counts (shown, dismissed, sent),unique respondents, conversion rates, and timing data. Supports optional date filtering.ui_app: survey-stats+ survey-stop:+ operation: surveys_stop+ enabled: true+ scopes:+ - survey:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ enrich_url: '{id}'+ title: Stop a survey now.+ description: >+ Stop a survey by setting `end_date` to the current time. No new responses are accepted after this; existing+ responses remain available. Prefer this over `survey-update` with a manual `end_date`. No-op if the survey+ already has an end_date in the past. To hide the survey from the list, archive it via `survey-update` with+ `archived=true` instead.+ ui_app: surveysurvey-update:operation: surveys_partial_updateenabled: true@@ -234,9 +267,14 @@ tools:idempotent: trueenrich_url: '{id}'list: true- title: Get all surveys in the project with optional filtering.- description: |- Get all surveys in the project with optional filtering. Can filter by search term or use pagination.+ title: List surveys in the project (server-side search + filters).+ description: >+ List surveys in the project. Use `search` for fuzzy match against survey name and description (handles typos+ and prefix-as-you-type). Use `type` to filter by survey kind (popover, widget, external_survey, api). Use+ `archived` to filter archived state. Combine with pagination via `limit`/`offset`.++ Companion tools to avoid the recon-loop pattern: - For individual response rows: surveys-responses-list -+ For aggregate event counts: surveys-stats (single survey) or surveys-global-stats (project-wide)ui_app: survey-listsurveys-global-stats:operation: surveys_global_stats_retrieve@@ -261,12 +299,56 @@ tools:surveys-responses-count-retrieve:operation: surveys_responses_count_retrieveenabled: false+ surveys-responses-list:+ operation: surveys_responses_list+ enabled: true+ scopes:+ - survey:read+ - query:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List individual survey responses with resolved question text.+ description: >+ List individual responses for a specific survey. Question text is already resolved server-side — callers do+ not need to map opaque $survey_response_<id> property keys. Each row carries distinct_id, session_id, and+ submitted_at so agents can pivot to recordings, persons, or paths in one follow-up call. Use this instead of+ executing raw SQL against `survey sent` events.++ Common patterns: - NPS detractors: question_id=<rating question id> + score_lte=6 - Voice-of-customer+ mining: question_id=<open question id> + since=<date> - Per-respondent context: read distinct_id from a row,+ then pull recordings or events for that user.++ For person properties on respondents, follow up with persons-get using the row's distinct_id — this tool+ only requires survey:read scope and intentionally doesn't return person data inline. Use limit/offset and+ the has_more field to paginate. For surveys with many thousands of responses, prefer scoping with `since` /+ `until` over deep offset paging (ClickHouse offset cost grows with skipped rows, and new responses arriving+ between pages can shift boundaries).+ ui_app: survey-statssurveys-responses-unarchive-create:operation: surveys_responses_unarchive_createenabled: falsesurveys-summarize-responses-create:operation: surveys_summarize_responses_create- enabled: false+ enabled: true+ scopes:+ - survey:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: false+ title: Summarize survey responses (per question, or survey-wide headline).+ description: >+ Summarize survey responses using PostHog's LLM summarization. Pass question_id (preferred) or question_index+ to get a per-question theme summary. Omit both to get the survey-wide headline summary instead — the+ endpoint dispatches automatically based on what you pass.++ Pass force_refresh=true in the body to bypass cached summaries. Per-question summaries are cached on the+ survey object; headline summaries are cached on the survey row.++ Use this after you have identified a survey of interest. If you need raw response rows for cross-pivot, use+ surveys-responses-list instead.surveys-summary-headline-create:operation: surveys_summary_headline_createenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex cbaf6976cc4f..c226de211605 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4864,6 +4864,20 @@"readOnlyHint": true}},+ "survey-launch": {+ "description": "Launch a survey by setting `start_date` to the current time. Prefer this over `survey-update` with a manual `start_date` — it's an explicit lifecycle action and self-documenting in activity logs. No-op if the survey is already launched.",+ "category": "Surveys",+ "feature": "surveys",+ "summary": "Launch a survey now.",+ "title": "Launch a survey now.",+ "required_scopes": ["survey:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"survey-stats": {"description": "Get response statistics for a specific survey. Includes detailed event counts (shown, dismissed, sent), unique respondents, conversion rates, and timing data. Supports optional date filtering.","category": "Surveys",@@ -4878,6 +4892,20 @@"readOnlyHint": true}},+ "survey-stop": {+ "description": "Stop a survey by setting `end_date` to the current time. No new responses are accepted after this; existing responses remain available. Prefer this over `survey-update` with a manual `end_date`. No-op if the survey already has an end_date in the past. To hide the survey from the list, archive it via `survey-update` with `archived=true` instead.",+ "category": "Surveys",+ "feature": "surveys",+ "summary": "Stop a survey now.",+ "title": "Stop a survey now.",+ "required_scopes": ["survey:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"survey-update": {"description": "Update an existing survey by ID. Omitted top-level fields are preserved, but nested objects and arrays you provide may replace existing values. Before changing questions, conditions, appearance, targeting, translations, or hosted-form content, retrieve the survey first and preserve fields that should remain. Do not send null to clear a field unless the user explicitly asked to remove it.","category": "Surveys",@@ -4893,11 +4921,11 @@}},"surveys-get-all": {- "description": "Get all surveys in the project with optional filtering. Can filter by search term or use pagination.",+ "description": "List surveys in the project. Use `search` for fuzzy match against survey name and description (handles typos and prefix-as-you-type). Use `type` to filter by survey kind (popover, widget, external_survey, api). Use `archived` to filter archived state. Combine with pagination via `limit`/`offset`.\nCompanion tools to avoid the recon-loop pattern: - For individual response rows: surveys-responses-list - For aggregate event counts: surveys-stats (single survey) or surveys-global-stats (project-wide)","category": "Surveys","feature": "surveys",- "summary": "Get all surveys in the project with optional filtering.",- "title": "Get all surveys in the project with optional filtering.",+ "summary": "List surveys in the project (server-side search + filters).",+ "title": "List surveys in the project (server-side search + filters).","required_scopes": ["survey:read"],"annotations": {"destructiveHint": false,@@ -4920,6 +4948,34 @@"readOnlyHint": true}},+ "surveys-responses-list": {+ "description": "List individual responses for a specific survey. Question text is already resolved server-side — callers do not need to map opaque $survey_response_<id> property keys. Each row carries distinct_id, session_id, and submitted_at so agents can pivot to recordings, persons, or paths in one follow-up call. Use this instead of executing raw SQL against `survey sent` events.\nCommon patterns: - NPS detractors: question_id=<rating question id> + score_lte=6 - Voice-of-customer mining: question_id=<open question id> + since=<date> - Per-respondent context: read distinct_id from a row, then pull recordings or events for that user.\nFor person properties on respondents, follow up with persons-get using the row's distinct_id — this tool only requires survey:read scope and intentionally doesn't return person data inline. Use limit/offset and the has_more field to paginate. For surveys with many thousands of responses, prefer scoping with `since` / `until` over deep offset paging (ClickHouse offset cost grows with skipped rows, and new responses arriving between pages can shift boundaries).",+ "category": "Surveys",+ "feature": "surveys",+ "summary": "List individual survey responses with resolved question text.",+ "title": "List individual survey responses with resolved question text.",+ "required_scopes": ["survey:read", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "surveys-summarize-responses-create": {+ "description": "Summarize survey responses using PostHog's LLM summarization. Pass question_id (preferred) or question_index to get a per-question theme summary. Omit both to get the survey-wide headline summary instead — the endpoint dispatches automatically based on what you pass.\nPass force_refresh=true in the body to bypass cached summaries. Per-question summaries are cached on the survey object; headline summaries are cached on the survey row.\nUse this after you have identified a survey of interest. If you need raw response rows for cross-pivot, use surveys-responses-list instead.",+ "category": "Surveys",+ "feature": "surveys",+ "summary": "Summarize survey responses (per question, or survey-wide headline).",+ "title": "Summarize survey responses (per question, or survey-wide headline).",+ "required_scopes": ["survey:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"tasks-list": {"description": "List agent tasks in the current project. Supports filtering by `origin_product`, `stage`, `organization`, `repository`, `created_by`, and `internal`. Returns lightweight task metadata only — call tasks-retrieve for the full task including its latest run, or tasks-runs-list for run history. Requires the calling token's organization to have Tasks access enabled.","category": "Tasks",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 62efbea94708..eb5a565f7e80 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5191,6 +5191,20 @@"readOnlyHint": true}},+ "survey-launch": {+ "description": "Launch a survey by setting `start_date` to the current time. Prefer this over `survey-update` with a manual `start_date` — it's an explicit lifecycle action and self-documenting in activity logs. No-op if the survey is already launched.",+ "category": "Surveys",+ "feature": "surveys",+ "summary": "Launch a survey now.",+ "title": "Launch a survey now.",+ "required_scopes": ["survey:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"survey-stats": {"description": "Get response statistics for a specific survey. Includes detailed event counts (shown, dismissed, sent), unique respondents, conversion rates, and timing data. Supports optional date filtering.","category": "Surveys",@@ -5205,6 +5219,20 @@"readOnlyHint": true}},+ "survey-stop": {+ "description": "Stop a survey by setting `end_date` to the current time. No new responses are accepted after this; existing responses remain available. Prefer this over `survey-update` with a manual `end_date`. No-op if the survey already has an end_date in the past. To hide the survey from the list, archive it via `survey-update` with `archived=true` instead.",+ "category": "Surveys",+ "feature": "surveys",+ "summary": "Stop a survey now.",+ "title": "Stop a survey now.",+ "required_scopes": ["survey:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"survey-update": {"description": "Update an existing survey by ID. Omitted top-level fields are preserved, but nested objects and arrays you provide may replace existing values. Before changing questions, conditions, appearance, targeting, translations, or hosted-form content, retrieve the survey first and preserve fields that should remain. Do not send null to clear a field unless the user explicitly asked to remove it.","category": "Surveys",@@ -5220,11 +5248,11 @@}},"surveys-get-all": {- "description": "Get all surveys in the project with optional filtering. Can filter by search term or use pagination.",+ "description": "List surveys in the project. Use `search` for fuzzy match against survey name and description (handles typos and prefix-as-you-type). Use `type` to filter by survey kind (popover, widget, external_survey, api). Use `archived` to filter archived state. Combine with pagination via `limit`/`offset`.\nCompanion tools to avoid the recon-loop pattern: - For individual response rows: surveys-responses-list - For aggregate event counts: surveys-stats (single survey) or surveys-global-stats (project-wide)","category": "Surveys","feature": "surveys",- "summary": "Get all surveys in the project with optional filtering.",- "title": "Get all surveys in the project with optional filtering.",+ "summary": "List surveys in the project (server-side search + filters).",+ "title": "List surveys in the project (server-side search + filters).","required_scopes": ["survey:read"],"annotations": {"destructiveHint": false,@@ -5247,6 +5275,34 @@"readOnlyHint": true}},+ "surveys-responses-list": {+ "description": "List individual responses for a specific survey. Question text is already resolved server-side — callers do not need to map opaque $survey_response_<id> property keys. Each row carries distinct_id, session_id, and submitted_at so agents can pivot to recordings, persons, or paths in one follow-up call. Use this instead of executing raw SQL against `survey sent` events.\nCommon patterns: - NPS detractors: question_id=<rating question id> + score_lte=6 - Voice-of-customer mining: question_id=<open question id> + since=<date> - Per-respondent context: read distinct_id from a row, then pull recordings or events for that user.\nFor person properties on respondents, follow up with persons-get using the row's distinct_id — this tool only requires survey:read scope and intentionally doesn't return person data inline. Use limit/offset and the has_more field to paginate. For surveys with many thousands of responses, prefer scoping with `since` / `until` over deep offset paging (ClickHouse offset cost grows with skipped rows, and new responses arriving between pages can shift boundaries).",+ "category": "Surveys",+ "feature": "surveys",+ "summary": "List individual survey responses with resolved question text.",+ "title": "List individual survey responses with resolved question text.",+ "required_scopes": ["survey:read", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "surveys-summarize-responses-create": {+ "description": "Summarize survey responses using PostHog's LLM summarization. Pass question_id (preferred) or question_index to get a per-question theme summary. Omit both to get the survey-wide headline summary instead — the endpoint dispatches automatically based on what you pass.\nPass force_refresh=true in the body to bypass cached summaries. Per-question summaries are cached on the survey object; headline summaries are cached on the survey row.\nUse this after you have identified a survey of interest. If you need raw response rows for cross-pivot, use surveys-responses-list instead.",+ "category": "Surveys",+ "feature": "surveys",+ "summary": "Summarize survey responses (per question, or survey-wide headline).",+ "title": "Summarize survey responses (per question, or survey-wide headline).",+ "required_scopes": ["survey:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"switch-organization": {"description": "Switch the active PostHog organization for subsequent tool calls. Call this proactively whenever the user names an organization they want to operate on. Use `organizations-list` to resolve an organization name to an id. Default to the active organization when no specific organization is mentioned.","category": "Organization & project management",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f5aa744f5b9f..f7fa8fec4475 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -37450,6 +37450,91 @@ export namespace Schemas {labels: SurveyQuestionLabel[];}+ export interface SurveyResponseAnswer {+ /** UUID of the survey question this answer belongs to. */+ question_id: string;+ /** Zero-based index of the question within the survey. */+ question_index: number;+ /** Untranslated question text as configured by the survey author. */+ question_text: string;+ /** Question type: open, rating, single_choice, multiple_choice, or link. Determines the shape of the answer field. */+ question_type: string;+ /** Resolved answer. String for open/rating/single_choice/link questions, list of strings for multiple_choice questions. Already decoded from the raw $survey_response_<id> property so callers don't need to parse it. */+ answer: unknown;+ }++ export interface SurveyResponseExtra {+ /**+ * $device_type at the time the response was sent.+ * @nullable+ */+ device_type?: string | null;+ /**+ * $browser at the time the response was sent.+ * @nullable+ */+ browser?: string | null;+ /**+ * $os (operating system) at the time the response was sent.+ * @nullable+ */+ os?: string | null;+ /**+ * $geoip_country_code at submission time.+ * @nullable+ */+ geoip_country_code?: string | null;+ /**+ * $geoip_country_name at submission time.+ * @nullable+ */+ geoip_country_name?: string | null;+ /**+ * $geoip_city_name at submission time.+ * @nullable+ */+ geoip_city_name?: string | null;+ /**+ * $current_url where the survey was submitted.+ * @nullable+ */+ current_url?: string | null;+ /**+ * Survey iteration number when the response was sent. Only set for recurring surveys.+ * @nullable+ */+ iteration?: string | null;+ }++ export interface SurveyResponseRow {+ /** UUID of the underlying `survey sent` event. Use as the response identifier for archive operations. */+ uuid: string;+ /** distinct_id of the respondent. Cross-pivot to the persons API or session recordings. */+ distinct_id: string;+ /**+ * $session_id of the respondent when available. Use to pull the session recording for this response.+ * @nullable+ */+ session_id: string | null;+ /** Event timestamp when the response was sent (ISO 8601, UTC). */+ submitted_at: string;+ /** One entry per survey question that received a non-empty answer. Question text is already resolved — callers do not need to look up `$survey_response_<id>` keys. */+ answers: SurveyResponseAnswer[];+ /** Convenience fields extracted from the event properties (device, browser, geoip, iteration). */+ extra: SurveyResponseExtra;+ }++ export interface SurveyResponsesList {+ /** Survey response rows for the requested page. */+ results: SurveyResponseRow[];+ /** True if more rows exist beyond the current page — fetch the next page with offset + limit. */+ has_more: boolean;+ /** The limit applied to this query (echoed back for pagination). */+ limit: number;+ /** The offset applied to this query (echoed back for pagination). */+ offset: number;+ }+export interface SurveySerializerCreateUpdateOnly {readonly id: string;/** @maxLength 400 */@@ -37914,6 +37999,13 @@ export namespace Schemas {stats: SurveyStatsResponseStats;/** Calculated response and dismissal rates. */rates: SurveyStatsResponseRates;+ /** Per-question response counts and distributions. Only present when include_per_question_stats=true was passed. For rating questions includes `average`; for choice/rating questions `distribution` maps answer value to count; for open questions `distribution` is empty (use surveys-responses-list to read free-text). */+ per_question_stats?: unknown[];+ }++ export interface SurveySummarizeRequest {+ /** When true, bypass cached summaries and regenerate. Defaults to false. */+ force_refresh?: boolean;}export interface Synthesize {@@ -49253,6 +49345,62 @@ export namespace Schemas {* Fuzzy match against survey `name` and `description` using Postgres trigram word similarity. Supports typos and prefix-as-you-type.*/search?: string;+ /**+ * * `popover` - popover+ * `widget` - widget+ * `external_survey` - external survey+ * `api` - api+ */+ type?: SurveysListType;+ };++ export type SurveysListType = typeof SurveysListType[keyof typeof SurveysListType];+++ export const SurveysListType = {+ Api: 'api',+ ExternalSurvey: 'external_survey',+ Popover: 'popover',+ Widget: 'widget',+ } as const;++ export type SurveysResponsesListParams = {+ /**+ * When true, exclude responses that have been archived via the archive_response endpoint.+ */+ exclude_archived?: boolean;+ /**+ * Maximum number of rows to return (1-500). Defaults to 100.+ * @minimum 1+ * @maximum 500+ */+ limit?: number;+ /**+ * Number of rows to skip for pagination. Combine with `limit` and the `has_more` field to paginate.+ * @minimum 0+ */+ offset?: number;+ /**+ * If set, only return rows where this question has a non-empty answer, and only include that question's answer in each row. Required when using score_lte or score_gte.+ * @minLength 1+ */+ question_id?: string;+ /**+ * Filter to rows where the rating answer for `question_id` is >= this value. Common use: NPS promoters with score_gte=9. Requires question_id.+ */+ score_gte?: number;+ /**+ * Filter to rows where the rating answer for `question_id` is <= this value. Common use: NPS detractors with score_lte=6. Requires question_id.+ */+ score_lte?: number;+ /**+ * Only return responses submitted on or after this ISO 8601 timestamp.+ */+ since?: string;+ /**+ * Only return responses submitted on or before this ISO 8601 timestamp.+ */+ until?: string;};export type SurveysStatsRetrieveParams = {@@ -49264,6 +49412,21 @@ export namespace Schemas {* Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)*/date_to?: string;+ /**+ * When true, also return per-question response counts and answer distributions. Adds one extra HogQL query per question, so leave off unless you need the breakdown.+ */+ include_per_question_stats?: boolean;+ };++ export type SurveysSummarizeResponsesCreateParams = {+ /**+ * Question UUID. Preferred over question_index — stable across question edits.+ */+ question_id?: string;+ /**+ * Zero-based question index. Omit to get the survey-wide headline instead.+ */+ question_index?: number;};export type SurveysGlobalStatsRetrieveParams = {diff --git a/services/mcp/src/generated/surveys/api.ts b/services/mcp/src/generated/surveys/api.tsindex 54e3cc1a50f1..b1d49413db0a 100644--- a/services/mcp/src/generated/surveys/api.ts+++ b/services/mcp/src/generated/surveys/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 11 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -26,6 +26,10 @@ export const SurveysListQueryParams = /* @__PURE__ */ zod.object({.describe('Fuzzy match against survey `name` and `description` using Postgres trigram word similarity. Supports typos and prefix-as-you-type.'),+ type: zod+ .enum(['api', 'external_survey', 'popover', 'widget'])+ .optional()+ .describe('* `popover` - popover\n* `widget` - widget\n* `external_survey` - external survey\n* `api` - api'),})export const SurveysCreateParams = /* @__PURE__ */ zod.object({@@ -1620,6 +1624,82 @@ export const SurveysDestroyParams = /* @__PURE__ */ zod.object({),})+/**+ * Launch a survey by setting `start_date` to the current time. No-op if the survey is already launched (start_date set in the past) — returns the existing state unchanged. Does not affect archived surveys or surveys with an end_date in the past; unarchive or extend the end_date first.+ */+export const SurveysLaunchParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this survey.'),+ 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/."+ ),+})++/**+ * List survey responses for a specific survey, with question text resolved server-side so callers do not have to map opaque `$survey_response_<id>` keys. Each row carries `distinct_id`, `session_id`, `submitted_at`, and an `extra` block (device, browser, OS, geoip, current_url, iteration) so agents can cross-pivot to recordings, persons, or paths in a single follow-up call. For person properties at event time, follow up with `persons-get` using the returned `distinct_id` — keeps scopes scoped. Use `question_id` + `score_lte` to fetch NPS detractors and similar score-filtered cohorts.+ */+export const SurveysResponsesListParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this survey.'),+ 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 surveysResponsesListQueryExcludeArchivedDefault = false+export const surveysResponsesListQueryLimitDefault = 100+export const surveysResponsesListQueryLimitMax = 500++export const surveysResponsesListQueryOffsetDefault = 0+export const surveysResponsesListQueryOffsetMin = 0++export const SurveysResponsesListQueryParams = /* @__PURE__ */ zod.object({+ exclude_archived: zod+ .boolean()+ .default(surveysResponsesListQueryExcludeArchivedDefault)+ .describe('When true, exclude responses that have been archived via the archive_response endpoint.'),+ limit: zod+ .number()+ .min(1)+ .max(surveysResponsesListQueryLimitMax)+ .default(surveysResponsesListQueryLimitDefault)+ .describe('Maximum number of rows to return (1-500). Defaults to 100.'),+ offset: zod+ .number()+ .min(surveysResponsesListQueryOffsetMin)+ .default(surveysResponsesListQueryOffsetDefault)+ .describe('Number of rows to skip for pagination. Combine with `limit` and the `has_more` field to paginate.'),+ question_id: zod+ .string()+ .min(1)+ .optional()+ .describe(+ "If set, only return rows where this question has a non-empty answer, and only include that question's answer in each row. Required when using score_lte or score_gte."+ ),+ score_gte: zod+ .number()+ .optional()+ .describe(+ 'Filter to rows where the rating answer for `question_id` is >= this value. Common use: NPS promoters with score_gte=9. Requires question_id.'+ ),+ score_lte: zod+ .number()+ .optional()+ .describe(+ 'Filter to rows where the rating answer for `question_id` is <= this value. Common use: NPS detractors with score_lte=6. Requires question_id.'+ ),+ since: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe('Only return responses submitted on or after this ISO 8601 timestamp.'),+ until: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe('Only return responses submitted on or before this ISO 8601 timestamp.'),+})+/*** Get survey response statistics for a specific survey.@@ -1627,6 +1707,7 @@ Args:date_from: Optional ISO timestamp for start date (e.g. 2024-01-01T00:00:00Z)date_to: Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)exclude_archived: Optional boolean to exclude archived responses (default: false, includes archived)+ include_per_question_stats: Optional boolean to include per-question response counts and distributionsReturns:Survey statistics including event counts, unique respondents, and conversion rates@@ -1649,6 +1730,56 @@ export const SurveysStatsRetrieveQueryParams = /* @__PURE__ */ zod.object({.datetime({ offset: true }).optional().describe('Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)'),+ include_per_question_stats: zod+ .boolean()+ .optional()+ .describe(+ 'When true, also return per-question response counts and answer distributions. Adds one extra HogQL query per question, so leave off unless you need the breakdown.'+ ),+})++/**+ * Stop a survey by setting `end_date` to the current time. No new responses are accepted after this; existing responses remain available. No-op if the survey already has an end_date in the past.+ */+export const SurveysStopParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this survey.'),+ 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/."+ ),+})++/**+ * Summarize survey responses. When `question_index` or `question_id` is provided, returns a per-question theme summary using cached `survey.question_summaries` when fresh. When neither is provided, returns the survey-wide headline summary (delegates to summary_headline). Pass `force_refresh=true` in the body to bypass caches.+ */+export const SurveysSummarizeResponsesCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this survey.'),+ 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 SurveysSummarizeResponsesCreateQueryParams = /* @__PURE__ */ zod.object({+ question_id: zod+ .string()+ .optional()+ .describe('Question UUID. Preferred over question_index — stable across question edits.'),+ question_index: zod+ .number()+ .optional()+ .describe('Zero-based question index. Omit to get the survey-wide headline instead.'),+})++export const surveysSummarizeResponsesCreateBodyForceRefreshDefault = false++export const SurveysSummarizeResponsesCreateBody = /* @__PURE__ */ zod.object({+ force_refresh: zod+ .boolean()+ .default(surveysSummarizeResponsesCreateBodyForceRefreshDefault)+ .describe('When true, bypass cached summaries and regenerate. Defaults to false.'),})/**diff --git a/services/mcp/src/tools/generated/surveys.ts b/services/mcp/src/tools/generated/surveys.tsindex bcce7912a96f..d41a402e0277 100644--- a/services/mcp/src/tools/generated/surveys.ts+++ b/services/mcp/src/tools/generated/surveys.ts@@ -6,12 +6,19 @@ import {SurveysCreateBody,SurveysDestroyParams,SurveysGlobalStatsRetrieveQueryParams,+ SurveysLaunchParams,SurveysListQueryParams,SurveysPartialUpdateBody,SurveysPartialUpdateParams,+ SurveysResponsesListParams,+ SurveysResponsesListQueryParams,SurveysRetrieveParams,SurveysStatsRetrieveParams,SurveysStatsRetrieveQueryParams,+ SurveysStopParams,+ SurveysSummarizeResponsesCreateBody,+ SurveysSummarizeResponsesCreateParams,+ SurveysSummarizeResponsesCreateQueryParams,} from '@/generated/surveys/api'import { withUiApp } from '@/resources/ui-apps'import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'@@ -168,6 +175,22 @@ const surveyGet = (): ToolBase<typeof SurveyGetSchema, WithPostHogUrl<Schemas.Su},})+const SurveyLaunchSchema = SurveysLaunchParams.omit({ project_id: true })++const surveyLaunch = (): ToolBase<typeof SurveyLaunchSchema, WithPostHogUrl<Schemas.Survey>> =>+ withUiApp('survey', {+ name: 'survey-launch',+ schema: SurveyLaunchSchema,+ handler: async (context: Context, params: z.infer<typeof SurveyLaunchSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.Survey>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/${encodeURIComponent(String(params.id))}/launch/`,+ })+ return await withPostHogUrl(context, result, `/surveys/${result.id}`)+ },+ })+const SurveyStatsSchema = SurveysStatsRetrieveParams.omit({ project_id: true }).extend(SurveysStatsRetrieveQueryParams.shape)@@ -184,12 +207,29 @@ const surveyStats = (): ToolBase<typeof SurveyStatsSchema, WithPostHogUrl<Schemaquery: {date_from: params.date_from,date_to: params.date_to,+ include_per_question_stats: params.include_per_question_stats,},})return await withPostHogUrl(context, result, `/surveys/${result.survey_id}`)},})+const SurveyStopSchema = SurveysStopParams.omit({ project_id: true })++const surveyStop = (): ToolBase<typeof SurveyStopSchema, WithPostHogUrl<Schemas.Survey>> =>+ withUiApp('survey', {+ name: 'survey-stop',+ schema: SurveyStopSchema,+ handler: async (context: Context, params: z.infer<typeof SurveyStopSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.Survey>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/${encodeURIComponent(String(params.id))}/stop/`,+ })+ return await withPostHogUrl(context, result, `/surveys/${result.id}`)+ },+ })+const SurveyUpdateSchema = SurveysPartialUpdateParams.omit({ project_id: true }).extend(SurveysPartialUpdateBody.omit({@@ -319,6 +359,7 @@ const surveysGetAll = (): ToolBase<typeof SurveysGetAllSchema, WithPostHogUrl<Sclimit: params.limit,offset: params.offset,search: params.search,+ type: params.type,},})return await withPostHogUrl(@@ -354,12 +395,70 @@ const surveysGlobalStats = (): ToolBase<typeof SurveysGlobalStatsSchema, Schemas},})+const SurveysResponsesListSchema = SurveysResponsesListParams.omit({ project_id: true }).extend(+ SurveysResponsesListQueryParams.shape+)++const surveysResponsesList = (): ToolBase<typeof SurveysResponsesListSchema, Schemas.SurveyResponsesList> =>+ withUiApp('survey-stats', {+ name: 'surveys-responses-list',+ schema: SurveysResponsesListSchema,+ handler: async (context: Context, params: z.infer<typeof SurveysResponsesListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.SurveyResponsesList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/${encodeURIComponent(String(params.id))}/responses/`,+ query: {+ exclude_archived: params.exclude_archived,+ limit: params.limit,+ offset: params.offset,+ question_id: params.question_id,+ score_gte: params.score_gte,+ score_lte: params.score_lte,+ since: params.since,+ until: params.until,+ },+ })+ return result+ },+ })++const SurveysSummarizeResponsesCreateSchema = SurveysSummarizeResponsesCreateParams.omit({ project_id: true })+ .extend(SurveysSummarizeResponsesCreateQueryParams.shape)+ .extend(SurveysSummarizeResponsesCreateBody.shape)++const surveysSummarizeResponsesCreate = (): ToolBase<typeof SurveysSummarizeResponsesCreateSchema, unknown> => ({+ name: 'surveys-summarize-responses-create',+ schema: SurveysSummarizeResponsesCreateSchema,+ handler: async (context: Context, params: z.infer<typeof SurveysSummarizeResponsesCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.force_refresh !== undefined) {+ body['force_refresh'] = params.force_refresh+ }+ const result = await context.api.request<unknown>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/${encodeURIComponent(String(params.id))}/summarize_responses/`,+ body,+ query: {+ question_id: params.question_id,+ question_index: params.question_index,+ },+ })+ return result+ },+})+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'survey-create': surveyCreate,'survey-delete': surveyDelete,'survey-get': surveyGet,+ 'survey-launch': surveyLaunch,'survey-stats': surveyStats,+ 'survey-stop': surveyStop,'survey-update': surveyUpdate,'surveys-get-all': surveysGetAll,'surveys-global-stats': surveysGlobalStats,+ 'surveys-responses-list': surveysResponsesList,+ 'surveys-summarize-responses-create': surveysSummarizeResponsesCreate,}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-launch.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-launch.jsonnew file mode 100644index 000000000000..1e2ce50c84ed--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-launch.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this survey.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-stats.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-stats.jsonindex e91c9fd8f508..a3d7a6335272 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-stats.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-stats.json@@ -16,6 +16,10 @@"id": {"description": "A UUID string identifying this survey.","type": "string"+ },+ "include_per_question_stats": {+ "description": "When true, also return per-question response counts and answer distributions. Adds one extra HogQL query per question, so leave off unless you need the breakdown.",+ "type": "boolean"}},"required": ["id"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-stop.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-stop.jsonnew file mode 100644index 000000000000..1e2ce50c84ed--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-stop.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this survey.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-get-all.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-get-all.jsonindex 72cef9ba35b0..2f92e1a9813a 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-get-all.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-get-all.json@@ -15,6 +15,11 @@"search": {"description": "Fuzzy match against survey `name` and `description` using Postgres trigram word similarity. Supports typos and prefix-as-you-type.","type": "string"+ },+ "type": {+ "description": "* `popover` - popover\n* `widget` - widget\n* `external_survey` - external survey\n* `api` - api",+ "enum": ["api", "external_survey", "popover", "widget"],+ "type": "string"}},"type": "object"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-responses-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-responses-list.jsonnew file mode 100644index 000000000000..0e90b3415f64--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-responses-list.json@@ -0,0 +1,54 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "exclude_archived": {+ "default": false,+ "description": "When true, exclude responses that have been archived via the archive_response endpoint.",+ "type": "boolean"+ },+ "id": {+ "description": "A UUID string identifying this survey.",+ "type": "string"+ },+ "limit": {+ "default": 100,+ "description": "Maximum number of rows to return (1-500). Defaults to 100.",+ "maximum": 500,+ "minimum": 1,+ "type": "number"+ },+ "offset": {+ "default": 0,+ "description": "Number of rows to skip for pagination. Combine with `limit` and the `has_more` field to paginate.",+ "minimum": 0,+ "type": "number"+ },+ "question_id": {+ "description": "If set, only return rows where this question has a non-empty answer, and only include that question's answer in each row. Required when using score_lte or score_gte.",+ "minLength": 1,+ "type": "string"+ },+ "score_gte": {+ "description": "Filter to rows where the rating answer for `question_id` is >= this value. Common use: NPS promoters with score_gte=9. Requires question_id.",+ "type": "number"+ },+ "score_lte": {+ "description": "Filter to rows where the rating answer for `question_id` is <= this value. Common use: NPS detractors with score_lte=6. Requires question_id.",+ "type": "number"+ },+ "since": {+ "description": "Only return responses submitted on or after this ISO 8601 timestamp.",+ "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"+ },+ "until": {+ "description": "Only return responses submitted on or before this ISO 8601 timestamp.",+ "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"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-summarize-responses-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-summarize-responses-create.jsonnew file mode 100644index 000000000000..22dca611d84e--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-summarize-responses-create.json@@ -0,0 +1,24 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "force_refresh": {+ "default": false,+ "description": "When true, bypass cached summaries and regenerate. Defaults to false.",+ "type": "boolean"+ },+ "id": {+ "description": "A UUID string identifying this survey.",+ "type": "string"+ },+ "question_id": {+ "description": "Question UUID. Preferred over question_index — stable across question edits.",+ "type": "string"+ },+ "question_index": {+ "description": "Zero-based question index. Omit to get the survey-wide headline instead.",+ "type": "number"+ }+ },+ "required": ["id"],+ "type": "object"+}