Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(surveys): resolve $survey_response_<id> taxonomy to question text (#59072)

Lucas Faria87f0ad3266ed
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 367d55490956..9ac2b03cadfb 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -5038,6 +5038,17 @@ const api = {
.withQueryString(surveyIds ? { survey_ids: surveyIds } : undefined)
.get()
},
+ async questionLabels(): Promise<{
+ labels: {
+ question_id: string
+ question_text: string
+ question_index: number
+ survey_id: string
+ survey_name: string
+ }[]
+ }> {
+ return await new ApiRequest().surveys().withAction('question_labels').get()
+ },
async summarize_responses(
surveyId: Survey['id'],
questionIndex: number | undefined,
diff --git a/frontend/src/lib/components/PropertyKeyInfo.tsx b/frontend/src/lib/components/PropertyKeyInfo.tsx
index f61b9b8aa584..14ece5de0502 100644
--- a/frontend/src/lib/components/PropertyKeyInfo.tsx
+++ b/frontend/src/lib/components/PropertyKeyInfo.tsx
@@ -1,17 +1,21 @@
import './PropertyKeyInfo.scss'
import clsx from 'clsx'
+import { useValues } from 'kea'
import React, { useState } from 'react'
import { LemonDivider, TooltipProps } from '@posthog/lemon-ui'
import { Popover } from 'lib/lemon-ui/Popover'
import { pluralize } from 'lib/utils'
+import { surveyQuestionLabelsLogic } from 'scenes/surveys/surveyQuestionLabelsLogic'
import { PropertyKey, getCoreFilterDefinition } from '~/taxonomy/helpers'
import { TaxonomicFilterGroupType } from './TaxonomicFilter/types'
+const SURVEY_RESPONSE_PREFIX = '$survey_response_'
+
export interface PropertyKeyInfoProps {
value: PropertyKey
type?: TaxonomicFilterGroupType
@@ -24,7 +28,7 @@ export interface PropertyKeyInfoProps {
className?: string
}
-export const PropertyKeyInfo = React.forwardRef<HTMLSpanElement, PropertyKeyInfoProps>(function PropertyKeyInfo(
+const PropertyKeyInfoBase = React.forwardRef<HTMLSpanElement, PropertyKeyInfoProps>(function PropertyKeyInfoBase(
{
value,
type = TaxonomicFilterGroupType.EventProperties,
@@ -38,7 +42,7 @@ export const PropertyKeyInfo = React.forwardRef<HTMLSpanElement, PropertyKeyInfo
): JSX.Element {
const [popoverVisible, setPopoverVisible] = useState(false)
- value = value?.toString() ?? '' // convert to string
+ value = value?.toString() ?? ''
const coreDefinition = getCoreFilterDefinition(value, type)
const valueDisplayText = displayText || ((coreDefinition ? coreDefinition.label : value)?.trim() ?? '')
@@ -115,3 +119,27 @@ export const PropertyKeyInfo = React.forwardRef<HTMLSpanElement, PropertyKeyInfo
</Popover>
)
})
+
+// Mounted only when the value is a `$survey_response_<question-id>` key. Two
+// jobs: (1) trigger the `surveyQuestionLabelsLogic` mount so its `afterMount`
+// fires the slim labels endpoint, and (2) subscribe to the resulting state so
+// this component re-renders when the labels land, picking up the enriched
+// label via `getCoreFilterDefinition`. The enrichment itself lives in the
+// helper so non-React consumers (popovers, chart legends, definitions admin
+// page) benefit too.
+const PropertyKeyInfoWithSurveyMount = React.forwardRef<HTMLSpanElement, PropertyKeyInfoProps>(
+ function PropertyKeyInfoWithSurveyMount(props, ref): JSX.Element {
+ useValues(surveyQuestionLabelsLogic)
+ return <PropertyKeyInfoBase {...props} ref={ref} />
+ }
+)
+
+export const PropertyKeyInfo = React.forwardRef<HTMLSpanElement, PropertyKeyInfoProps>(
+ function PropertyKeyInfo(props, ref): JSX.Element {
+ const value = props.value?.toString() ?? ''
+ if (value.startsWith(SURVEY_RESPONSE_PREFIX)) {
+ return <PropertyKeyInfoWithSurveyMount {...props} ref={ref} />
+ }
+ return <PropertyKeyInfoBase {...props} ref={ref} />
+ }
+)
diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/AutocompleteInput.tsx b/frontend/src/lib/components/TaxonomicFilter/headless/AutocompleteInput.tsx
index dccfb2d292a5..b4c6ddae8317 100644
--- a/frontend/src/lib/components/TaxonomicFilter/headless/AutocompleteInput.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/headless/AutocompleteInput.tsx
@@ -70,6 +70,7 @@ import {
} from '@posthog/quill'
import { createFuse } from 'lib/utils/fuseSearch'
+import { surveyQuestionLabelsLogic } from 'scenes/surveys/surveyQuestionLabelsLogic'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
import { getCoreFilterDefinition } from '~/taxonomy/helpers'
@@ -476,6 +477,14 @@ export function Root({
[visibleGroups, category]
)
+ // Mount + subscribe so `$survey_response_<question-id>` keys resolve to the
+ // actual question text. `getFriendlyLabel` reads through `getCoreFilterDefinition`,
+ // which falls back to a static label until `surveyQuestionLabelsLogic` has
+ // loaded. Subscribing here ensures `indexed` recomputes the labels once they
+ // arrive — without this, each entry's `friendlyLabel` would be frozen to the
+ // pre-load fallback for the lifetime of the popover.
+ const { surveyQuestionLabels } = useValues(surveyQuestionLabelsLogic)
+
const indexed = useMemo<IndexedItem[]>(() => {
const merged: IndexedItem[] = []
for (const group of targetGroups) {
@@ -503,7 +512,12 @@ export function Root({
}
}
return merged
- }, [targetGroups, itemsByType])
+ // `surveyQuestionLabels` is a deliberate recompute trigger: it isn't read
+ // directly in the body, but `getFriendlyLabel` → `getCoreFilterDefinition`
+ // reads its value via `findMounted()`. Without this dep the memo would
+ // freeze each entry's `friendlyLabel` to the pre-load fallback.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [targetGroups, itemsByType, surveyQuestionLabels])
const filtered = useMemo<IndexedItem[]>(() => {
const trimmed = searchQuery.trim()
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
index d4bf999791bd..6f585c641133 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
@@ -11,6 +11,7 @@
* commit. Esc → onBack.
*/
import { Autocomplete } from '@base-ui/react/autocomplete'
+import { useValues } from 'kea'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { IconCheck, IconChevronRight } from '@posthog/icons'
@@ -31,6 +32,7 @@ import {
} from '@posthog/quill'
import { createFuse } from 'lib/utils/fuseSearch'
+import { surveyQuestionLabelsLogic } from 'scenes/surveys/surveyQuestionLabelsLogic'
import { getCoreFilterDefinition } from '~/taxonomy/helpers'
@@ -198,6 +200,14 @@ export function MenuFilterCombobox({
return g ? [g] : []
}, [showChips, activeChip, drillTo, groups, visibleChipGroups])
+ // Mount + subscribe so `$survey_response_<question-id>` keys resolve to the
+ // actual question text. `getFriendlyLabel` reads through `getCoreFilterDefinition`,
+ // which falls back to a static label until `surveyQuestionLabelsLogic` has
+ // loaded. Subscribing here ensures `indexed` recomputes the labels once they
+ // arrive — without this, each entry's `friendlyLabel` would be frozen to the
+ // pre-load fallback for the lifetime of the popover.
+ const { surveyQuestionLabels } = useValues(surveyQuestionLabelsLogic)
+
// Indexed entries — flat list across all visible groups (or
// pre-resolved `drillItems` for recent/pinned, or pre-merged
// `suggestedItems` for the Suggested chip / drill).
@@ -248,7 +258,22 @@ export function MenuFilterCombobox({
}
}
return merged
- }, [drillItems, suggestedItems, targetGroups, itemsByType, selectedEntry, showChips, activeChip, drillTo])
+ // `surveyQuestionLabels` is a deliberate recompute trigger: it isn't read
+ // directly in the body, but `getFriendlyLabel` → `getCoreFilterDefinition`
+ // reads its value via `findMounted()`. Without this dep the memo would
+ // freeze each entry's `friendlyLabel` to the pre-load fallback.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [
+ drillItems,
+ suggestedItems,
+ targetGroups,
+ itemsByType,
+ selectedEntry,
+ showChips,
+ activeChip,
+ drillTo,
+ surveyQuestionLabels,
+ ])
const filtered = useMemo<MenuFilterEntry[]>(() => {
const q = searchQuery.trim()
diff --git a/frontend/src/scenes/surveys/surveyQuestionLabelsLogic.ts b/frontend/src/scenes/surveys/surveyQuestionLabelsLogic.ts
new file mode 100644
index 000000000000..3f0a7ae4f309
--- /dev/null
+++ b/frontend/src/scenes/surveys/surveyQuestionLabelsLogic.ts
@@ -0,0 +1,42 @@
+import { afterMount, kea, path } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+
+import type { surveyQuestionLabelsLogicType } from './surveyQuestionLabelsLogicType'
+
+export interface SurveyQuestionLabel {
+ surveyId: string
+ surveyName: string
+ questionText: string
+ questionIndex: number
+}
+
+export const surveyQuestionLabelsLogic = kea<surveyQuestionLabelsLogicType>([
+ path(['scenes', 'surveys', 'surveyQuestionLabelsLogic']),
+ loaders(({ values }) => ({
+ surveyQuestionLabels: [
+ {} as Record<string, SurveyQuestionLabel>,
+ {
+ loadSurveyQuestionLabels: async () => {
+ // The endpoint returns one entry per question with an ID, across all the team's surveys.
+ // The payload is intentionally slim (≈100 bytes per question) so this scales to thousands.
+ const response = await api.surveys.questionLabels()
+ const labels: Record<string, SurveyQuestionLabel> = { ...values.surveyQuestionLabels }
+ for (const entry of response.labels) {
+ labels[entry.question_id] = {
+ surveyId: entry.survey_id,
+ surveyName: entry.survey_name,
+ questionText: entry.question_text,
+ questionIndex: entry.question_index,
+ }
+ }
+ return labels
+ },
+ },
+ ],
+ })),
+ afterMount(({ actions }) => {
+ actions.loadSurveyQuestionLabels()
+ }),
+])
diff --git a/frontend/src/taxonomy/helpers.ts b/frontend/src/taxonomy/helpers.ts
index 74d8cb63da1f..f46520171a30 100644
--- a/frontend/src/taxonomy/helpers.ts
+++ b/frontend/src/taxonomy/helpers.ts
@@ -1,4 +1,5 @@
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { surveyQuestionLabelsLogic } from 'scenes/surveys/surveyQuestionLabelsLogic'
import { CoreFilterDefinition } from '~/types'
@@ -54,13 +55,37 @@ export function getCoreFilterDefinition(
}
}
} else if (value.startsWith('$survey_response_')) {
- const surveyIndex = value.replace(/^\$survey_response_/, '')
- if (surveyIndex) {
- const index = Number(surveyIndex) + 1
- const suffix = index === 2 ? 'nd' : index === 3 ? 'rd' : 'th'
+ const suffix = value.replace(/^\$survey_response_/, '')
+ if (suffix) {
+ // If `surveyQuestionLabelsLogic` is mounted (a `PropertyKeyInfo` for any
+ // survey response key triggers the mount, which auto-loads the slim labels
+ // endpoint), prefer the actual question text. This branch covers every
+ // call site — `PropertyKeyInfo`, the property definitions popover, chart
+ // legends, breakdown labels, the admin definitions page — so all of them
+ // benefit once the labels have loaded.
+ const resolved = surveyQuestionLabelsLogic.findMounted()?.values.surveyQuestionLabels?.[suffix]
+ if (resolved) {
+ return {
+ label: `${resolved.questionText} · ${resolved.surveyName}`,
+ description: `Response to "${resolved.questionText}" in survey "${resolved.surveyName}".`,
+ }
+ }
+ const parsedIndex = Number(suffix)
+ if (Number.isInteger(parsedIndex) && parsedIndex >= 0) {
+ const index = parsedIndex + 1
+ const ordinal = index === 1 ? 'st' : index === 2 ? 'nd' : index === 3 ? 'rd' : 'th'
+ return {
+ label: `Survey response for ${index}${ordinal} question`,
+ description: `The response value for the ${index}${ordinal} question in the survey.`,
+ }
+ }
+ // Modern format `$survey_response_<question-uuid>`, but the labels haven't
+ // loaded yet (or this consumer doesn't subscribe so it won't re-render
+ // when they do). Emit a generic short-ID label as a placeholder.
+ const shortId = suffix.slice(0, 8)
return {
- label: `Survey response for ${index}${suffix} question`,
- description: `The response value for the ${index}${suffix} question in the survey.`,
+ label: `Survey response (${shortId}…)`,
+ description: `Response for survey question with ID "${suffix}".`,
}
}
} else if (value.startsWith('$feature/')) {
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.py
index 3247d944d3b1..6b6802cb8345 100644
--- a/products/surveys/backend/api/survey.py
+++ b/products/surveys/backend/api/survey.py
@@ -2310,6 +2310,74 @@ 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_question_labels",
+ description=(
+ "Return a slim list of question labels for the team's surveys. Used by the frontend to resolve "
+ "`$survey_response_<question_id>` property keys into human-readable question text without "
+ "loading the full survey payload."
+ ),
+ responses={
+ 200: inline_serializer(
+ name="SurveyQuestionLabelsResponse",
+ fields={
+ "labels": serializers.ListField(
+ child=inline_serializer(
+ name="SurveyQuestionLabel",
+ fields={
+ "question_id": serializers.CharField(help_text="UUID assigned to the survey question."),
+ "question_text": serializers.CharField(
+ help_text="Untranslated question text as configured by the survey author.",
+ allow_blank=True,
+ ),
+ "question_index": serializers.IntegerField(
+ help_text="Zero-based index of the question within the survey."
+ ),
+ "survey_id": serializers.CharField(
+ help_text="UUID of the survey this question belongs to."
+ ),
+ "survey_name": serializers.CharField(help_text="Display name of the survey."),
+ },
+ ),
+ help_text="One entry per question that has an ID assigned, across all the team's surveys.",
+ ),
+ },
+ ),
+ },
+ )
+ @action(methods=["GET"], detail=False, url_path="question_labels", required_scopes=["survey:read"])
+ def question_labels(self, request: request.Request, **kwargs) -> Response:
+ # Custom (non-`list`) actions skip the routing layer's automatic access-level filter,
+ # so apply it explicitly here — otherwise a user with access to only one survey would
+ # receive labels for every survey in the team.
+ queryset = self.user_access_control.filter_queryset_by_access_level(self.get_queryset())
+ # The viewset's class-level queryset pre-joins `linked_flag`, `linked_insight`,
+ # `targeting_flag`, `internal_targeting_flag` via `select_related`. `.only(...)` on
+ # those deferred FK columns raises `FieldError: cannot be both deferred and traversed
+ # using select_related`. Reset the select_related list before slimming the projection.
+ queryset = queryset.select_related(None).only("id", "name", "questions")
+ labels: list[dict[str, Any]] = []
+ for survey in queryset.iterator(chunk_size=200):
+ questions = survey.questions or []
+ if not isinstance(questions, list):
+ continue
+ for index, question in enumerate(questions):
+ if not isinstance(question, dict):
+ continue
+ question_id = question.get("id")
+ if not question_id:
+ continue
+ labels.append(
+ {
+ "question_id": question_id,
+ "question_text": question.get("question") or "",
+ "question_index": index,
+ "survey_id": str(survey.id),
+ "survey_name": survey.name,
+ }
+ )
+ return Response({"labels": labels})
+
@extend_schema(
parameters=[
OpenApiParameter(
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index 1a7238780362..bf706e7ff594 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -5404,6 +5404,137 @@ class TestSurveyStats(ClickhouseTestMixin, APIBaseTest):
self.assertIn("Available variants: option_1, option_2", error_data["detail"])
+class TestSurveyQuestionLabels(APIBaseTest):
+ """`surveys/question_labels/` is the slim taxonomy endpoint the frontend uses to
+ resolve `$survey_response_<question-id>` property keys into the actual question
+ text. Regression guard: the viewset's class-level queryset pre-joins several FKs
+ via `select_related`, which silently conflicts with `.only(...)` on those FK
+ columns and raises `FieldError` at iteration time. These tests pin the happy
+ path, the question-shape edge cases, and the team-scoping boundary so that
+ conflict can't sneak back in undetected."""
+
+ def _question_labels(self, team_id: int | None = None):
+ team_id = team_id if team_id is not None else self.team.id
+ return self.client.get(f"/api/projects/{team_id}/surveys/question_labels/")
+
+ def test_returns_question_labels_for_team_surveys(self):
+ # Two surveys, three questions across them — covers the iterator + index logic.
+ Survey.objects.create(
+ team=self.team,
+ name="NPS",
+ created_by=self.user,
+ questions=[
+ {"type": "rating", "id": "q-nps-score", "question": "How likely to recommend?"},
+ {"type": "open", "id": "q-nps-followup", "question": "Why that score?"},
+ ],
+ )
+ Survey.objects.create(
+ team=self.team,
+ name="Feedback",
+ created_by=self.user,
+ questions=[
+ {"type": "open", "id": "q-feedback", "question": "Anything else?"},
+ ],
+ )
+
+ response = self._question_labels()
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ labels = response.json()["labels"]
+ self.assertEqual(len(labels), 3)
+
+ by_id = {entry["question_id"]: entry for entry in labels}
+ self.assertEqual(by_id["q-nps-score"]["question_text"], "How likely to recommend?")
+ self.assertEqual(by_id["q-nps-score"]["question_index"], 0)
+ self.assertEqual(by_id["q-nps-score"]["survey_name"], "NPS")
+ self.assertEqual(by_id["q-nps-followup"]["question_index"], 1)
+ self.assertEqual(by_id["q-feedback"]["survey_name"], "Feedback")
+ # Every entry must carry the keys the frontend resolver indexes on — guards
+ # against accidental serializer field removal.
+ for entry in labels:
+ self.assertIn("question_id", entry)
+ self.assertIn("question_text", entry)
+ self.assertIn("question_index", entry)
+ self.assertIn("survey_id", entry)
+ self.assertIn("survey_name", entry)
+
+ def test_skips_questions_without_ids(self):
+ # `Survey.save()` auto-assigns UUIDs via `ensure_question_ids`, so under
+ # normal use every question has an `id`. But manual SQL edits, legacy
+ # rows pre-dating that hook, or `.update(questions=...)` bypass the
+ # hook entirely. The endpoint must drop those rows rather than emit
+ # entries with `question_id: null` (the frontend resolver keys on the
+ # id, so a null id would mask every other row at lookup time).
+ survey = Survey.objects.create(
+ team=self.team,
+ name="Mixed",
+ created_by=self.user,
+ questions=[{"type": "open", "id": "q-with-id", "question": "Has id"}],
+ )
+ Survey.objects.filter(pk=survey.pk).update(
+ questions=[
+ {"type": "open", "id": "q-with-id", "question": "Has id"},
+ {"type": "open", "question": "No id"},
+ {"type": "open", "id": "", "question": "Blank id"},
+ ]
+ )
+
+ response = self._question_labels()
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ labels = response.json()["labels"]
+ self.assertEqual([entry["question_id"] for entry in labels], ["q-with-id"])
+
+ def test_returns_empty_for_team_without_surveys(self):
+ response = self._question_labels()
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"labels": []})
+
+ def test_does_not_leak_other_team_surveys(self):
+ other_team = Team.objects.create(organization=self.organization, name="Other team")
+ Survey.objects.create(
+ team=other_team,
+ name="Other team survey",
+ created_by=self.user,
+ questions=[{"type": "open", "id": "q-other-team", "question": "Other team question"}],
+ )
+ Survey.objects.create(
+ team=self.team,
+ name="Mine",
+ created_by=self.user,
+ questions=[{"type": "open", "id": "q-mine", "question": "My question"}],
+ )
+
+ response = self._question_labels()
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ ids = [entry["question_id"] for entry in response.json()["labels"]]
+ self.assertEqual(ids, ["q-mine"])
+
+ def test_runs_without_select_related_only_conflict(self):
+ # Regression: the viewset's class-level queryset pre-joins `linked_flag`,
+ # `linked_insight`, `targeting_flag`, `internal_targeting_flag` via
+ # `select_related`. Calling `.only("id", "name", "questions")` on top of
+ # that raises `FieldError: Field Survey.linked_flag cannot be both
+ # deferred and traversed using select_related at the same time` the moment
+ # the queryset is iterated. The previous version of this endpoint did
+ # exactly that and returned 500 on every call — silently broken because
+ # the frontend's kea-loaders swallows API errors. This test exists
+ # specifically to fail loudly if anyone re-introduces that conflict.
+ survey = Survey.objects.create(
+ team=self.team,
+ name="With FKs",
+ created_by=self.user,
+ questions=[{"type": "open", "id": "q-fk", "question": "Question with FKs attached"}],
+ )
+ survey.linked_flag = FeatureFlag.objects.create(team=self.team, key="linked", created_by=self.user)
+ survey.targeting_flag = FeatureFlag.objects.create(team=self.team, key="targeting", created_by=self.user)
+ survey.save()
+
+ response = self._question_labels()
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ labels = response.json()["labels"]
+ self.assertEqual(len(labels), 1)
+ self.assertEqual(labels[0]["question_id"], "q-fk")
+
+
class TestExternalSurveyValidation(APIBaseTest):
"""Test external survey specific validation logic"""
diff --git a/products/surveys/frontend/generated/api.schemas.ts b/products/surveys/frontend/generated/api.schemas.ts
index 4e5713016657..94806072bf25 100644
--- a/products/surveys/frontend/generated/api.schemas.ts
+++ b/products/surveys/frontend/generated/api.schemas.ts
@@ -1971,6 +1971,24 @@ export interface SurveyStatsResponseApi {
rates: SurveyStatsResponseApiRates
}
+export interface SurveyQuestionLabelApi {
+ /** UUID assigned to the survey question. */
+ question_id: string
+ /** Untranslated question text as configured by the survey author. */
+ question_text: string
+ /** Zero-based index of the question within the survey. */
+ question_index: number
+ /** UUID of the survey this question belongs to. */
+ survey_id: string
+ /** Display name of the survey. */
+ survey_name: string
+}
+
+export interface SurveyQuestionLabelsResponseApi {
+ /** One entry per question that has an ID assigned, across all the team's surveys. */
+ labels: SurveyQuestionLabelApi[]
+}
+
/**
* Event counts keyed by event name (survey shown, survey dismissed, survey sent).
*/
diff --git a/products/surveys/frontend/generated/api.ts b/products/surveys/frontend/generated/api.ts
index f946dec127a6..881632df7aa9 100644
--- a/products/surveys/frontend/generated/api.ts
+++ b/products/surveys/frontend/generated/api.ts
@@ -15,6 +15,7 @@ import type {
PatchedSurveySerializerCreateUpdateOnlySchemaApi,
SurveyApi,
SurveyGlobalStatsResponseApi,
+ SurveyQuestionLabelsResponseApi,
SurveySerializerCreateUpdateOnlyApi,
SurveySerializerCreateUpdateOnlySchemaApi,
SurveyStatsResponseApi,
@@ -346,6 +347,23 @@ export const surveysAllActivityRetrieve = async (projectId: string, options?: Re
})
}
+export const getSurveysQuestionLabelsUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/surveys/question_labels/`
+}
+
+/**
+ * Return a slim list of question labels for the team's surveys. Used by the frontend to resolve `$survey_response_<question_id>` property keys into human-readable question text without loading the full survey payload.
+ */
+export const surveysQuestionLabels = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<SurveyQuestionLabelsResponseApi> => {
+ return apiMutator<SurveyQuestionLabelsResponseApi>(getSurveysQuestionLabelsUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getSurveysResponsesCountRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/surveys/responses_count/`
}
diff --git a/products/surveys/mcp/tools.yaml b/products/surveys/mcp/tools.yaml
index 2bd3e32288f4..a8ce5f310611 100644
--- a/products/surveys/mcp/tools.yaml
+++ b/products/surveys/mcp/tools.yaml
@@ -252,6 +252,9 @@ tools:
Get aggregated response statistics across all surveys in the project. Includes event counts (shown,
dismissed, sent), unique respondents, conversion rates, and timing data. Supports optional date filtering.
ui_app: survey-global-stats
+ surveys-question-labels:
+ operation: surveys_question_labels
+ enabled: false
surveys-responses-archive-create:
operation: surveys_responses_archive_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 217dabd382d9..45dd70d8afa2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -34447,6 +34447,24 @@ export namespace Schemas {
rates: SurveyGlobalStatsResponseRates;
}
+ export interface SurveyQuestionLabel {
+ /** UUID assigned to the survey question. */
+ question_id: string;
+ /** Untranslated question text as configured by the survey author. */
+ question_text: string;
+ /** Zero-based index of the question within the survey. */
+ question_index: number;
+ /** UUID of the survey this question belongs to. */
+ survey_id: string;
+ /** Display name of the survey. */
+ survey_name: string;
+ }
+
+ export interface SurveyQuestionLabelsResponse {
+ /** One entry per question that has an ID assigned, across all the team's surveys. */
+ labels: SurveyQuestionLabel[];
+ }
+
export interface SurveySerializerCreateUpdateOnly {
readonly id: string;
/** @maxLength 400 */