: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
fix(surveys): accept survey id aliases and relative dates in mcp tools (#130437)
Lucas Faria28154b6e9ae0
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.tsindex 898dbc6ef340..35c179083f93 100644--- a/products/desktop/packages/api-client/src/generated.ts+++ b/products/desktop/packages/api-client/src/generated.ts@@ -19232,8 +19232,8 @@ export namespace Endpoints {* Get survey response statistics for a specific survey.** 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)+ * date_from: Optional ISO timestamp (e.g. 2024-01-01T00:00:00Z) or relative date (e.g. -7d) for start date+ * date_to: Optional ISO timestamp (e.g. 2024-01-31T23:59:59Z) or relative date for end date* 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 distributions*diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex 0bbe6706600d..1acafd3ba547 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -1,5 +1,6 @@import reimport builtins+import itertoolsfrom contextlib import contextmanagerfrom datetime import UTC, datetime, timedeltafrom typing import Any, Optional, cast@@ -95,6 +96,7 @@ from products.surveys.backend.models import (ensure_question_ids,)from products.surveys.backend.responses import (+ StatsWindow,SurveyRates,SurveyStats,build_choice_translation_map,@@ -1133,6 +1135,17 @@ class SurveySerializer(SearchMatchTypeSerializerMixin, UserAccessControlSerializreturn data+def _free_name_hint(name: str, project_id: int) -> str:+ taken = set(+ Survey.objects.filter(team__project_id=project_id, name__startswith=name).values_list("name", flat=True)+ )+ free_name = next(candidate for n in itertools.count(2) if (candidate := f"{name} ({n})") not in taken)+ max_length = Survey._meta.get_field("name").max_length+ if max_length is not None and len(free_name) > max_length:+ return "Use a different name."+ return f'Use a different name, such as "{free_name}".'++class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):linked_flag = MinimalFeatureFlagSerializer(read_only=True)linked_flag_id = serializers.IntegerField(required=False, write_only=True, allow_null=True)@@ -1750,7 +1763,10 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):self.context["request"].method == "POST"and Survey.objects.filter(name=data.get("name"), team__project_id=self.context["project_id"]).exists()):- raise serializers.ValidationError("There is already a survey with this name.", code="unique")+ raise serializers.ValidationError(+ f"There is already a survey with this name. {_free_name_hint(data['name'], self.context['project_id'])}",+ code="unique",+ )existing_survey: Survey | None = self.instance@@ -1761,7 +1777,10 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):.exclude(id=existing_survey.id).exists()):- raise serializers.ValidationError("There is already another survey with this name.", code="unique")+ raise serializers.ValidationError(+ f"There is already another survey with this name. {_free_name_hint(data['name'], self.context['project_id'])}",+ code="unique",+ )if data.get("targeting_flag_filters"):groups = (data.get("targeting_flag_filters") or {}).get("groups") or []@@ -2688,11 +2707,9 @@ class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControlcounts = get_survey_responses_count(team=self.team, exclude_archived=exclude_archived, survey_ids=survey_ids)return Response(counts)- def _validate_and_parse_dates(- self, date_from: str | None, date_to: str | None- ) -> tuple[datetime | None, datetime | None]:+ def _validate_and_parse_dates(self, date_from: str | None, date_to: str | None) -> StatsWindow:try:- return validate_and_parse_dates(date_from, date_to)+ return validate_and_parse_dates(date_from, date_to, self.team)except ValueError as exc:raise exceptions.ValidationError(str(exc)) from exc@@ -2710,8 +2727,8 @@ class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControl"""Get survey statistics from ClickHouse.Args:- date_from: Optional ISO timestamp for start date with timezone info- date_to: Optional ISO timestamp for end date with timezone info+ date_from: Optional ISO timestamp or relative date (e.g. -7d) for start date with timezone info+ date_to: Optional ISO timestamp or relative date for end date with timezone infosurvey_id: Optional survey ID to filter for. If None, gets stats for all surveys.exclude_archived: If True, exclude archived responses. Defaults to False (includes archived).@@ -2734,15 +2751,15 @@ class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControlparameters=[OpenApiParameter("date_from",- OpenApiTypes.DATETIME,+ OpenApiTypes.STR,required=False,- description="Optional ISO timestamp for start date (e.g. 2024-01-01T00:00:00Z)",+ description="Optional start date: an ISO 8601 timestamp (e.g. 2024-01-01T00:00:00Z) or a relative date such as -7d, -24h or -1m",),OpenApiParameter("date_to",- OpenApiTypes.DATETIME,+ OpenApiTypes.STR,required=False,- description="Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)",+ description="Optional end date: an ISO 8601 timestamp (e.g. 2024-01-31T23:59:59Z) or a relative date such as -1d",),OpenApiParameter("include_per_question_stats",@@ -2787,8 +2804,8 @@ class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControl"""Get survey response statistics for a specific survey.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)+ date_from: Optional ISO timestamp (e.g. 2024-01-01T00:00:00Z) or relative date (e.g. -7d) for start date+ date_to: Optional ISO timestamp (e.g. 2024-01-31T23:59:59Z) or relative date for end dateexclude_archived: Optional boolean to exclude archived responses (default: false, includes archived)include_per_question_stats: Optional boolean to include per-question response counts and distributions@@ -2814,13 +2831,10 @@ class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControlresponse_data["end_date"] = survey.end_dateif 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)+ window = self._validate_and_parse_dates(date_from, date_to)+ per_question = fetch_per_question_stats(+ survey=survey, team=self.team, since=window.date_from, until=window.date_to+ )response_data["per_question_stats"] = [{"question_id": q.question_id,@@ -3070,15 +3084,15 @@ class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControlparameters=[OpenApiParameter("date_from",- OpenApiTypes.DATETIME,+ OpenApiTypes.STR,required=False,- description="Optional ISO timestamp for start date (e.g. 2024-01-01T00:00:00Z)",+ description="Optional start date: an ISO 8601 timestamp (e.g. 2024-01-01T00:00:00Z) or a relative date such as -7d, -24h or -1m",),OpenApiParameter("date_to",- OpenApiTypes.DATETIME,+ OpenApiTypes.STR,required=False,- description="Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)",+ description="Optional end date: an ISO 8601 timestamp (e.g. 2024-01-31T23:59:59Z) or a relative date such as -1d",),],responses={@@ -3099,8 +3113,8 @@ class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControl"""Get aggregated response statistics across all surveys.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)+ date_from: Optional ISO timestamp (e.g. 2024-01-01T00:00:00Z) or relative date (e.g. -7d) for start date+ date_to: Optional ISO timestamp (e.g. 2024-01-31T23:59:59Z) or relative date for end dateReturns:Aggregated statistics across all surveys including total counts and ratesdiff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex 0043a8683202..6bdfa9183daa 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -3106,6 +3106,12 @@ class TestSurvey(APIBaseTest):format="json",).json()+ self.client.post(+ f"/api/projects/{self.team.id}/surveys/",+ data={"name": "survey without targeting (2)", "type": "popover"},+ format="json",+ )+updated_survey_deletes_targeting_flag = self.client.patch(f"/api/projects/{self.team.id}/surveys/{survey_with_targeting['id']}/",data={@@ -3115,7 +3121,8 @@ class TestSurvey(APIBaseTest):assert updated_survey_deletes_targeting_flag.status_code == status.HTTP_400_BAD_REQUESTassert (- updated_survey_deletes_targeting_flag.json()["detail"] == "There is already another survey with this name."+ updated_survey_deletes_targeting_flag.json()["detail"]+ == 'There is already another survey with this name. Use a different name, such as "survey without targeting (3)".')@time_machine.travel("2023-05-01 12:00:00", tick=False)diff --git a/products/surveys/backend/responses/__init__.py b/products/surveys/backend/responses/__init__.pyindex cf8e1d5d355a..19bf3649ec8f 100644--- a/products/surveys/backend/responses/__init__.py+++ b/products/surveys/backend/responses/__init__.py@@ -7,6 +7,7 @@ from products.surveys.backend.responses.fetch_rows import (from products.surveys.backend.responses.per_question_stats import PerQuestionStats, fetch_per_question_statsfrom products.surveys.backend.responses.stats import (EventStats,+ StatsWindow,SurveyRates,SurveyStats,calculate_rates,@@ -19,6 +20,7 @@ from products.surveys.backend.responses.stats import (__all__ = ["EventStats","PerQuestionStats",+ "StatsWindow","SurveyRates","SurveyResponseRow","SurveyStats",diff --git a/products/surveys/backend/responses/stats.py b/products/surveys/backend/responses/stats.pyindex e5aad8ccc643..a67c0f8a30b4 100644--- a/products/surveys/backend/responses/stats.py+++ b/products/surveys/backend/responses/stats.py@@ -9,6 +9,7 @@ sent response.from __future__ import annotations+import refrom datetime import UTC, datetimefrom typing import Any, TypedDict@@ -21,7 +22,9 @@ from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWSfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, tag_queries+from posthog.dataclasses import frozenfrom posthog.models import Team+from posthog.utils import relative_date_parsefrom products.surveys.backend.models import Surveyfrom products.surveys.backend.responses.fetch_rows import RESPONSE_EVENT_FILTER, SUBMISSION_GROUPING_KEY@@ -55,39 +58,57 @@ SurveyStats = TypedDict()-class _InvertedDateRangeError(ValueError):- """date_from is after date_to — kept distinct so its message survives the parse-error rewrite."""+@frozen+class StatsWindow:+ date_from: datetime | None+ date_to: datetime | None+ def __post_init__(self) -> None:+ if self.date_from and self.date_to and self.date_from > self.date_to:+ raise ValueError("date_from must be before date_to")-def validate_and_parse_dates(date_from: str | None, date_to: str | None) -> tuple[datetime | None, datetime | None]:- """Parse ISO timestamps to UTC datetimes, raising on malformed input or inverted range.- Raises ``ValueError`` on parse failures and inverted ranges so callers in non-REST contexts- (e.g. the dashboard widget) receive a standard Python exception. The REST viewset re-raises- it as ``rest_framework.exceptions.ValidationError``.- """- parsed_from = None- parsed_to = None+# relative_date_parse reads any unmatched string as "now", so only hand it inputs that are relative dates.+RELATIVE_DATE = re.compile(r"-?\d*(?P<unit>[hdwmqy])(?:Start|End)?")+CALENDAR_DAY = re.compile(r"\d{4}-\d{2}-\d{2}")- try:- if date_from:- parsed_from = datetime.fromisoformat(date_from).astimezone(UTC)- if date_to:- parsed_to = datetime.fromisoformat(date_to).astimezone(UTC)+def _parse_date(value: str, team: Team, *, is_end: bool) -> datetime:+ """Follows insight date ranges: a start snaps to the start of its day, an end to the end of its day, except for hours."""+ if relative := RELATIVE_DATE.fullmatch(value):+ parsed = relative_date_parse(+ value, team.timezone_info, always_truncate=not is_end, team_week_start_day=team.week_start_day+ )+ whole_days = relative["unit"] != "h"+ else:+ parsed = datetime.fromisoformat(value)+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=team.timezone_info)+ whole_days = CALENDAR_DAY.fullmatch(value) is not None+ if is_end and whole_days:+ parsed = parsed.replace(hour=23, minute=59, second=59, microsecond=999999)+ return parsed.astimezone(UTC)- if parsed_from and parsed_to and parsed_from > parsed_to:- raise _InvertedDateRangeError("date_from must be before date_to")- return parsed_from, parsed_to+def validate_and_parse_dates(date_from: str | None, date_to: str | None, team: Team) -> StatsWindow:+ """Parse ISO timestamps, calendar days or relative dates (`-7d`, `-24h`, `mStart`) to UTC datetimes.- except _InvertedDateRangeError:- raise- except ValueError as exc:+ Naive and relative inputs are read in the project's timezone, and weeks start on its week start day.+ Raises ``ValueError`` on parse failures and inverted ranges so callers in non-REST contexts+ (e.g. the dashboard widget) receive a standard Python exception. The REST viewset re-raises+ it as ``rest_framework.exceptions.ValidationError``.+ """+ try:+ parsed_from = _parse_date(date_from, team, is_end=False) if date_from else None+ parsed_to = _parse_date(date_to, team, is_end=True) if date_to else None+ except (ValueError, OverflowError) as exc:raise ValueError(- "Invalid date format. Please use ISO 8601 format with timezone info (e.g. 2024-01-01T00:00:00Z or 2024-01-01T00:00:00+00:00)"+ "Invalid date format. Use an ISO 8601 timestamp with timezone (e.g. 2024-01-01T00:00:00Z) "+ "or a relative date such as -7d, -24h or -1m.") from exc+ return StatsWindow(date_from=parsed_from, date_to=parsed_to)+def _isoformat_utc_z(value: datetime | None) -> str | None:if value is None:@@ -207,12 +228,12 @@ def get_survey_stats("""Get survey statistics from ClickHouse.When `survey_id` is None, computes stats across all non-archived surveys for the team.- `date_from`/`date_to` are optional ISO timestamps; for a single survey they are clamped+ `date_from`/`date_to` are optional ISO timestamps or relative dates; for a single survey they are clampedto the survey's own start/end window."""- parsed_from, parsed_to = validate_and_parse_dates(date_from, date_to)-team = Team.objects.get(pk=team_id)+ window = validate_and_parse_dates(date_from, date_to, team)+# Bare events.person_id: no override join; merged persons count per pre-merge id.modifiers = HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS)placeholders: dict[str, ast.Expr] = {@@ -221,8 +242,8 @@ def get_survey_stats("sent": ast.Constant(value=SurveyEventName.SENT.value),}conditions: list[str] = []- effective_from = parsed_from- effective_to = parsed_to+ effective_from = window.date_from+ effective_to = window.date_toif survey_id:survey_dates = (@@ -234,10 +255,10 @@ def get_survey_stats(survey_end = survey_dates["end_date"]if survey_start:- effective_from = max(filter(None, [parsed_from, survey_start]), default=survey_start)+ effective_from = max(filter(None, [window.date_from, survey_start]), default=survey_start)if survey_end:- effective_to = min(filter(None, [parsed_to, survey_end]), default=survey_end)+ effective_to = min(filter(None, [window.date_to, survey_end]), default=survey_end)date_conditions = ""if effective_from:diff --git a/products/surveys/backend/responses/test_stats.py b/products/surveys/backend/responses/test_stats.pynew file mode 100644index 000000000000..574924037abe--- /dev/null+++ b/products/surveys/backend/responses/test_stats.py@@ -0,0 +1,80 @@+from datetime import UTC, datetime++import time_machine++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.models import Team++from products.surveys.backend.responses.stats import StatsWindow, validate_and_parse_dates++NOW = datetime(2026, 3, 15, 12, 30, tzinfo=UTC) # a Sunday+SAO_PAULO = "America/Sao_Paulo" # UTC-3+SUNDAY, MONDAY = 0, 1+++def _team(timezone: str = "UTC", week_start_day: int | None = None) -> Team:+ return Team(timezone=timezone, week_start_day=week_start_day)+++@time_machine.travel(NOW, tick=False)+class TestValidateAndParseDates(SimpleTestCase):+ @parameterized.expand(+ [+ ("iso_utc", "2026-03-01T10:00:00Z", _team(), datetime(2026, 3, 1, 10, tzinfo=UTC)),+ ("iso_offset", "2026-03-01T02:00:00+02:00", _team(), datetime(2026, 3, 1, tzinfo=UTC)),+ ("naive_iso_in_project_tz", "2026-03-01T00:00:00", _team(SAO_PAULO), datetime(2026, 3, 1, 3, tzinfo=UTC)),+ ("days_snap_to_start_of_day", "-7d", _team(), datetime(2026, 3, 8, tzinfo=UTC)),+ ("days_in_project_tz", "-7d", _team(SAO_PAULO), datetime(2026, 3, 8, 3, tzinfo=UTC)),+ ("hours_snap_to_start_of_hour", "-24h", _team(), datetime(2026, 3, 14, 12, tzinfo=UTC)),+ ("months", "-1m", _team(), datetime(2026, 2, 15, tzinfo=UTC)),+ ("month_start", "mStart", _team(), datetime(2026, 3, 1, tzinfo=UTC)),+ ("week_start_sunday", "wStart", _team(week_start_day=SUNDAY), datetime(2026, 3, 15, tzinfo=UTC)),+ ("week_start_monday", "wStart", _team(week_start_day=MONDAY), datetime(2026, 3, 9, tzinfo=UTC)),+ ]+ )+ def test_parses_date_from(self, _name: str, value: str, team: Team, expected: datetime) -> None:+ assert validate_and_parse_dates(value, None, team) == StatsWindow(date_from=expected, date_to=None)++ @parameterized.expand(+ [+ ("iso_keeps_exact_time", "2026-03-10T10:00:00Z", _team(), datetime(2026, 3, 10, 10, tzinfo=UTC)),+ ("calendar_day_is_inclusive", "2026-03-10", _team(), datetime(2026, 3, 10, 23, 59, 59, 999999, tzinfo=UTC)),+ ("days_snap_to_end_of_day", "-1d", _team(), datetime(2026, 3, 14, 23, 59, 59, 999999, tzinfo=UTC)),+ ("days_in_project_tz", "-1d", _team(SAO_PAULO), datetime(2026, 3, 15, 2, 59, 59, 999999, tzinfo=UTC)),+ ("hours_keep_time_of_day", "-24h", _team(), datetime(2026, 3, 14, 12, 30, tzinfo=UTC)),+ (+ "week_end_monday",+ "wEnd",+ _team(week_start_day=MONDAY),+ datetime(2026, 3, 15, 23, 59, 59, 999999, tzinfo=UTC),+ ),+ ]+ )+ def test_parses_date_to(self, _name: str, value: str, team: Team, expected: datetime) -> None:+ assert validate_and_parse_dates(None, value, team) == StatsWindow(date_from=None, date_to=expected)++ def test_same_relative_day_covers_the_whole_day(self) -> None:+ assert validate_and_parse_dates("dStart", "dStart", _team()) == StatsWindow(+ date_from=datetime(2026, 3, 15, tzinfo=UTC),+ date_to=datetime(2026, 3, 15, 23, 59, 59, 999999, tzinfo=UTC),+ )++ @parameterized.expand(+ [+ ("words", "yesterday"),+ ("phrase", "7 days ago"),+ ("unknown_unit", "-7x"),+ ("bare_number", "7"),+ ("out_of_range", "-99999999d"),+ ]+ )+ def test_rejects_unparseable_date(self, _name: str, value: str) -> None:+ with self.assertRaisesRegex(ValueError, "relative date such as -7d"):+ validate_and_parse_dates(value, None, _team())++ def test_rejects_inverted_relative_range(self) -> None:+ with self.assertRaisesRegex(ValueError, "date_from must be before date_to"):+ validate_and_parse_dates("-1d", "-7d", _team())diff --git a/products/surveys/frontend/generated/api.schemas.ts b/products/surveys/frontend/generated/api.schemas.tsindex abb62771041d..b03c1d9aefd0 100644--- a/products/surveys/frontend/generated/api.schemas.ts+++ b/products/surveys/frontend/generated/api.schemas.ts@@ -2555,11 +2555,11 @@ export type SurveysResponsesListParams = {export type SurveysStatsRetrieveParams = {/**- * Optional ISO timestamp for start date (e.g. 2024-01-01T00:00:00Z)+ * Optional start date: an ISO 8601 timestamp (e.g. 2024-01-01T00:00:00Z) or a relative date such as -7d, -24h or -1m*/date_from?: string/**- * Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)+ * Optional end date: an ISO 8601 timestamp (e.g. 2024-01-31T23:59:59Z) or a relative date such as -1d*/date_to?: string/**@@ -2581,11 +2581,11 @@ export type SurveysSummarizeResponsesCreateParams = {export type SurveysGlobalStatsRetrieveParams = {/**- * Optional ISO timestamp for start date (e.g. 2024-01-01T00:00:00Z)+ * Optional start date: an ISO 8601 timestamp (e.g. 2024-01-01T00:00:00Z) or a relative date such as -7d, -24h or -1m*/date_from?: string/**- * Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)+ * Optional end date: an ISO 8601 timestamp (e.g. 2024-01-31T23:59:59Z) or a relative date such as -1d*/date_to?: string}diff --git a/products/surveys/frontend/generated/api.ts b/products/surveys/frontend/generated/api.tsindex 946f8f52efc0..30587506d917 100644--- a/products/surveys/frontend/generated/api.ts+++ b/products/surveys/frontend/generated/api.ts@@ -461,8 +461,8 @@ export const getSurveysStatsRetrieveUrl = (projectId: string, id: string, params* Get survey response statistics for a specific survey.** 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)+ * date_from: Optional ISO timestamp (e.g. 2024-01-01T00:00:00Z) or relative date (e.g. -7d) for start date+ * date_to: Optional ISO timestamp (e.g. 2024-01-31T23:59:59Z) or relative date for end date* 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 distributions*@@ -634,8 +634,8 @@ export const getSurveysGlobalStatsRetrieveUrl = (projectId: string, params?: Sur* Get aggregated response statistics across all surveys.** 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)+ * date_from: Optional ISO timestamp (e.g. 2024-01-01T00:00:00Z) or relative date (e.g. -7d) for start date+ * date_to: Optional ISO timestamp (e.g. 2024-01-31T23:59:59Z) or relative date for end date** Returns:* Aggregated statistics across all surveys including total counts and ratesdiff --git a/products/surveys/mcp/tools.yaml b/products/surveys/mcp/tools.yamlindex d35bef6368b8..afef26c4a88a 100644--- a/products/surveys/mcp/tools.yaml+++ b/products/surveys/mcp/tools.yaml@@ -132,6 +132,11 @@ tools:title: Delete a survey by ID.description: |Delete a survey by ID (soft delete - marks as archived).+ param_overrides:+ id:+ aliases:+ - survey_id+ - surveyIdsoft_delete: archivedsurvey-get:operation: surveys_retrieve@@ -148,6 +153,11 @@ tools:Get a specific survey by ID. Returns its questions, targeting flag — including current property targetingrules under targeting_flag.filters — and scheduling details. To change targeting, use targeting_flag_filterswith survey-update.+ param_overrides:+ id:+ aliases:+ - survey_id+ - surveyIdui_app: surveysurvey-launch:operation: surveys_launch@@ -165,6 +175,11 @@ tools:`start_date` — it's an explicit lifecycle action and self-documenting in activity logs. No-op if the surveyis already launched. Archived surveys must be unarchived first. Surveys with an end_date in the past musthave that date cleared or extended before launch; do this only when the user asks to reopen the survey.+ param_overrides:+ id:+ aliases:+ - survey_id+ - surveyIdui_app: surveysurvey-stats:operation: surveys_stats_retrieve@@ -180,6 +195,11 @@ tools: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.+ param_overrides:+ id:+ aliases:+ - survey_id+ - surveyIdui_app: survey-statssurvey-stop:operation: surveys_stop@@ -197,6 +217,11 @@ tools:responses remain available. Prefer this over `survey-update` with a manual `end_date`. No-op if the surveyalready has an end_date in the past. To hide the survey from the list, archive it via `survey-update` with`archived=true` instead.+ param_overrides:+ id:+ aliases:+ - survey_id+ - surveyIdui_app: surveysurvey-update:operation: surveys_partial_update@@ -242,6 +267,10 @@ tools:- translations- form_contentparam_overrides:+ id:+ aliases:+ - survey_id+ - surveyIdappearance:description: >Optional appearance customization. Omit this to preserve current styling. When changing it, fetch@@ -348,6 +377,11 @@ tools: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 arrivingbetween pages can shift boundaries).+ param_overrides:+ id:+ aliases:+ - survey_id+ - surveyIdui_app: survey-statssurveys-summarize-responses-create:operation: surveys_summarize_responses_create@@ -369,3 +403,8 @@ tools:Use this after you have identified a survey of interest. If you need raw response rows for cross-pivot, usesurveys-responses-list instead.+ param_overrides:+ id:+ aliases:+ - survey_id+ - surveyIddiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6c2b98af0d80..afe31ebdc17c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -134854,11 +134854,11 @@ export namespace Schemas {export type SurveysStatsRetrieveParams = {/**- * Optional ISO timestamp for start date (e.g. 2024-01-01T00:00:00Z)+ * Optional start date: an ISO 8601 timestamp (e.g. 2024-01-01T00:00:00Z) or a relative date such as -7d, -24h or -1m*/date_from?: string;/**- * Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)+ * Optional end date: an ISO 8601 timestamp (e.g. 2024-01-31T23:59:59Z) or a relative date such as -1d*/date_to?: string;/**@@ -134880,11 +134880,11 @@ export namespace Schemas {export type SurveysGlobalStatsRetrieveParams = {/**- * Optional ISO timestamp for start date (e.g. 2024-01-01T00:00:00Z)+ * Optional start date: an ISO 8601 timestamp (e.g. 2024-01-01T00:00:00Z) or a relative date such as -7d, -24h or -1m*/date_from?: string;/**- * Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)+ * Optional end date: an ISO 8601 timestamp (e.g. 2024-01-31T23:59:59Z) or a relative date such as -1d*/date_to?: string;};diff --git a/services/mcp/src/generated/surveys/api.ts b/services/mcp/src/generated/surveys/api.tsindex d01db6ca6de8..db31fe5f1b05 100644--- a/services/mcp/src/generated/surveys/api.ts+++ b/services/mcp/src/generated/surveys/api.ts@@ -2638,8 +2638,8 @@ export const SurveysResponsesListQueryParams = () => zod.object({* Get survey response statistics for a specific survey.** 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)+ * date_from: Optional ISO timestamp (e.g. 2024-01-01T00:00:00Z) or relative date (e.g. -7d) for start date+ * date_to: Optional ISO timestamp (e.g. 2024-01-31T23:59:59Z) or relative date for end date* 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 distributions*@@ -2656,14 +2656,18 @@ export const SurveysStatsRetrieveParams = () => zod.object({})export const SurveysStatsRetrieveQueryParams = () => zod.object({- date_from: zod.iso- .datetime({ offset: true })+ date_from: zod+ .string().optional()- .describe('Optional ISO timestamp for start date (e.g. 2024-01-01T00:00:00Z)'),- date_to: zod.iso- .datetime({ offset: true })+ .describe(+ 'Optional start date: an ISO 8601 timestamp (e.g. 2024-01-01T00:00:00Z) or a relative date such as -7d, -24h or -1m'+ ),+ date_to: zod+ .string().optional()- .describe('Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)'),+ .describe(+ 'Optional end date: an ISO 8601 timestamp (e.g. 2024-01-31T23:59:59Z) or a relative date such as -1d'+ ),include_per_question_stats: zod.boolean().optional()@@ -2720,8 +2724,8 @@ export const SurveysSummarizeResponsesCreateBody = () => zod.object({* Get aggregated response statistics across all surveys.** 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)+ * date_from: Optional ISO timestamp (e.g. 2024-01-01T00:00:00Z) or relative date (e.g. -7d) for start date+ * date_to: Optional ISO timestamp (e.g. 2024-01-31T23:59:59Z) or relative date for end date** Returns:* Aggregated statistics across all surveys including total counts and rates@@ -2735,12 +2739,16 @@ export const SurveysGlobalStatsRetrieveParams = () => zod.object({})export const SurveysGlobalStatsRetrieveQueryParams = () => zod.object({- date_from: zod.iso- .datetime({ offset: true })+ date_from: zod+ .string().optional()- .describe('Optional ISO timestamp for start date (e.g. 2024-01-01T00:00:00Z)'),- date_to: zod.iso- .datetime({ offset: true })+ .describe(+ 'Optional start date: an ISO 8601 timestamp (e.g. 2024-01-01T00:00:00Z) or a relative date such as -7d, -24h or -1m'+ ),+ date_to: zod+ .string().optional()- .describe('Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)'),+ .describe(+ 'Optional end date: an ISO 8601 timestamp (e.g. 2024-01-31T23:59:59Z) or a relative date such as -1d'+ ),})diff --git a/services/mcp/src/tools/generated/surveys.ts b/services/mcp/src/tools/generated/surveys.tsindex 143b06b24c1e..c2121ac757b0 100644--- a/services/mcp/src/tools/generated/surveys.ts+++ b/services/mcp/src/tools/generated/surveys.ts@@ -4,6 +4,7 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import * as orvalSchemas from '@/generated/surveys/api'import { withUiApp } from '@/resources/ui-apps'+import { normalizeParamAliases } from '@/tools/cast-helpers'import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'@@ -134,7 +135,10 @@ const surveyCreate = (): ToolBase<const SurveyDeleteSchema = () => {const SurveysDestroyParams = orvalSchemas.SurveysDestroyParams()- return SurveysDestroyParams.omit({ project_id: true })+ return z.preprocess(+ normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),+ SurveysDestroyParams.omit({ project_id: true })+ )}const surveyDelete = (): ToolBase<ReturnType<typeof SurveyDeleteSchema>, Schemas.SurveySerializerCreateUpdateOnly> => ({@@ -153,7 +157,10 @@ const surveyDelete = (): ToolBase<ReturnType<typeof SurveyDeleteSchema>, Schemasconst SurveyGetSchema = () => {const SurveysRetrieveParams = orvalSchemas.SurveysRetrieveParams()- return SurveysRetrieveParams.omit({ project_id: true })+ return z.preprocess(+ normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),+ SurveysRetrieveParams.omit({ project_id: true })+ )}const surveyGet = (): ToolBase<ReturnType<typeof SurveyGetSchema>, WithPostHogUrl<Schemas.Survey>> =>@@ -172,7 +179,10 @@ const surveyGet = (): ToolBase<ReturnType<typeof SurveyGetSchema>, WithPostHogUrconst SurveyLaunchSchema = () => {const SurveysLaunchParams = orvalSchemas.SurveysLaunchParams()- return SurveysLaunchParams.omit({ project_id: true })+ return z.preprocess(+ normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),+ SurveysLaunchParams.omit({ project_id: true })+ )}const surveyLaunch = (): ToolBase<ReturnType<typeof SurveyLaunchSchema>, WithPostHogUrl<Schemas.Survey>> =>@@ -192,7 +202,10 @@ const surveyLaunch = (): ToolBase<ReturnType<typeof SurveyLaunchSchema>, WithPosconst SurveyStatsSchema = () => {const SurveysStatsRetrieveParams = orvalSchemas.SurveysStatsRetrieveParams()const SurveysStatsRetrieveQueryParams = orvalSchemas.SurveysStatsRetrieveQueryParams()- return SurveysStatsRetrieveParams.omit({ project_id: true }).extend(SurveysStatsRetrieveQueryParams.shape)+ return z.preprocess(+ normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),+ SurveysStatsRetrieveParams.omit({ project_id: true }).extend(SurveysStatsRetrieveQueryParams.shape)+ )}const surveyStats = (): ToolBase<ReturnType<typeof SurveyStatsSchema>, WithPostHogUrl<Schemas.SurveyStatsResponse>> =>@@ -216,7 +229,10 @@ const surveyStats = (): ToolBase<ReturnType<typeof SurveyStatsSchema>, WithPostHconst SurveyStopSchema = () => {const SurveysStopParams = orvalSchemas.SurveysStopParams()- return SurveysStopParams.omit({ project_id: true })+ return z.preprocess(+ normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),+ SurveysStopParams.omit({ project_id: true })+ )}const surveyStop = (): ToolBase<ReturnType<typeof SurveyStopSchema>, WithPostHogUrl<Schemas.Survey>> =>@@ -236,45 +252,48 @@ const surveyStop = (): ToolBase<ReturnType<typeof SurveyStopSchema>, WithPostHogconst SurveyUpdateSchema = () => {const SurveysPartialUpdateBody = orvalSchemas.SurveysPartialUpdateBody()const SurveysPartialUpdateParams = orvalSchemas.SurveysPartialUpdateParams()- return SurveysPartialUpdateParams.omit({ project_id: true })- .extend(- SurveysPartialUpdateBody.omit({- linked_insight_id: true,- iteration_start_dates: true,- current_iteration: true,- current_iteration_start_date: true,- response_sampling_start_date: true,- response_sampling_interval_type: true,- response_sampling_interval: true,- response_sampling_limit: true,- response_sampling_daily_limits: true,- base_language: true,- _create_in_folder: true,- }).shape- )- .extend({- appearance: SurveysPartialUpdateBody.shape['appearance'].describe(- 'Optional appearance customization. Omit this to preserve current styling. When changing it, fetch the survey first and preserve existing appearance fields. whiteLabel=true requires the organization to have the white-labelling entitlement (Enterprise); leave it unset unless requested and available. surveyPopupDelaySeconds must be non-negative.'- ),- schedule: SurveysPartialUpdateBody.shape['schedule'].describe(- 'How often a person can see the survey: once, recurring, or always. Omit this to keep the current schedule. When setting recurring, also set iteration_count and iteration_frequency_days. Use always when the user wants the survey to show every time its display conditions are met, also after the person responds or dismisses it. The survey editor calls this "Every time the display conditions are met". When you change away from recurring, the iteration fields are cleared. An always popover without display conditions or a wait period shows again and again, so suggest a URL condition or seenSurveyWaitPeriodInDays.'- ),- questions: SurveysPartialUpdateBody.shape['questions'].describe(- "Complete replacement question list. Existing question IDs are tied to response data and must be preserved. Before sending this field, fetch the survey first, modify the existing question objects in place, keep every unchanged or edited question's id, and include the complete intended ordered question list. New questions should omit id. Do not regenerate existing questions from scratch."- ),- conditions: SurveysPartialUpdateBody.shape['conditions'].describe(- 'Complete replacement display conditions object. Do not provide this field unless changing display targeting. Use targeting_flag_filters for person, group, or cohort property targeting. Preserve existing URL, selector, event, device, wait-period, and linked flag variant conditions unless explicitly changing them.'- ),- targeting_flag_filters: SurveysPartialUpdateBody.shape['targeting_flag_filters'].describe(- "Update an in-app survey's person, group, or cohort property targeting. Pass rules in groups[].properties[], each with key, value, operator, and an optional type. Use this instead of conditions for property targeting. Complete replacement: fetch the survey first, start from targeting_flag.filters, and send the full groups list — omitted groups are removed. Do not use this for external_survey forms. Cohorts with behavioral filters cannot be used directly. Use a supported static cohort snapshot only with user approval; never remove targeting rules to work around validation."- ),- translations: SurveysPartialUpdateBody.shape['translations'].describe(- 'Complete replacement survey-level translations object. Do not provide this field unless changing translations. Preserve existing language keys and translated fields that should remain. Use null only when the user explicitly asks to remove survey-level translations.'- ),- form_content: SurveysPartialUpdateBody.shape['form_content'].describe(- 'Hosted-form content configuration for external_survey forms. Do not provide this field unless editing hosted-form content. Preserve existing content fields that should remain.'- ),- })+ return z.preprocess(+ normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),+ SurveysPartialUpdateParams.omit({ project_id: true })+ .extend(+ SurveysPartialUpdateBody.omit({+ linked_insight_id: true,+ iteration_start_dates: true,+ current_iteration: true,+ current_iteration_start_date: true,+ response_sampling_start_date: true,+ response_sampling_interval_type: true,+ response_sampling_interval: true,+ response_sampling_limit: true,+ response_sampling_daily_limits: true,+ base_language: true,+ _create_in_folder: true,+ }).shape+ )+ .extend({+ appearance: SurveysPartialUpdateBody.shape['appearance'].describe(+ 'Optional appearance customization. Omit this to preserve current styling. When changing it, fetch the survey first and preserve existing appearance fields. whiteLabel=true requires the organization to have the white-labelling entitlement (Enterprise); leave it unset unless requested and available. surveyPopupDelaySeconds must be non-negative.'+ ),+ schedule: SurveysPartialUpdateBody.shape['schedule'].describe(+ 'How often a person can see the survey: once, recurring, or always. Omit this to keep the current schedule. When setting recurring, also set iteration_count and iteration_frequency_days. Use always when the user wants the survey to show every time its display conditions are met, also after the person responds or dismisses it. The survey editor calls this "Every time the display conditions are met". When you change away from recurring, the iteration fields are cleared. An always popover without display conditions or a wait period shows again and again, so suggest a URL condition or seenSurveyWaitPeriodInDays.'+ ),+ questions: SurveysPartialUpdateBody.shape['questions'].describe(+ "Complete replacement question list. Existing question IDs are tied to response data and must be preserved. Before sending this field, fetch the survey first, modify the existing question objects in place, keep every unchanged or edited question's id, and include the complete intended ordered question list. New questions should omit id. Do not regenerate existing questions from scratch."+ ),+ conditions: SurveysPartialUpdateBody.shape['conditions'].describe(+ 'Complete replacement display conditions object. Do not provide this field unless changing display targeting. Use targeting_flag_filters for person, group, or cohort property targeting. Preserve existing URL, selector, event, device, wait-period, and linked flag variant conditions unless explicitly changing them.'+ ),+ targeting_flag_filters: SurveysPartialUpdateBody.shape['targeting_flag_filters'].describe(+ "Update an in-app survey's person, group, or cohort property targeting. Pass rules in groups[].properties[], each with key, value, operator, and an optional type. Use this instead of conditions for property targeting. Complete replacement: fetch the survey first, start from targeting_flag.filters, and send the full groups list — omitted groups are removed. Do not use this for external_survey forms. Cohorts with behavioral filters cannot be used directly. Use a supported static cohort snapshot only with user approval; never remove targeting rules to work around validation."+ ),+ translations: SurveysPartialUpdateBody.shape['translations'].describe(+ 'Complete replacement survey-level translations object. Do not provide this field unless changing translations. Preserve existing language keys and translated fields that should remain. Use null only when the user explicitly asks to remove survey-level translations.'+ ),+ form_content: SurveysPartialUpdateBody.shape['form_content'].describe(+ 'Hosted-form content configuration for external_survey forms. Do not provide this field unless editing hosted-form content. Preserve existing content fields that should remain.'+ ),+ })+ )}const surveyUpdate = (): ToolBase<@@ -430,7 +449,10 @@ const surveysGlobalStats = (): ToolBase<const SurveysResponsesListSchema = () => {const SurveysResponsesListParams = orvalSchemas.SurveysResponsesListParams()const SurveysResponsesListQueryParams = orvalSchemas.SurveysResponsesListQueryParams()- return SurveysResponsesListParams.omit({ project_id: true }).extend(SurveysResponsesListQueryParams.shape)+ return z.preprocess(+ normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),+ SurveysResponsesListParams.omit({ project_id: true }).extend(SurveysResponsesListQueryParams.shape)+ )}const surveysResponsesList = (): ToolBase<ReturnType<typeof SurveysResponsesListSchema>, Schemas.SurveyResponsesList> =>@@ -461,9 +483,12 @@ const SurveysSummarizeResponsesCreateSchema = () => {const SurveysSummarizeResponsesCreateBody = orvalSchemas.SurveysSummarizeResponsesCreateBody()const SurveysSummarizeResponsesCreateParams = orvalSchemas.SurveysSummarizeResponsesCreateParams()const SurveysSummarizeResponsesCreateQueryParams = orvalSchemas.SurveysSummarizeResponsesCreateQueryParams()- return SurveysSummarizeResponsesCreateParams.omit({ project_id: true })- .extend(SurveysSummarizeResponsesCreateQueryParams.shape)- .extend(SurveysSummarizeResponsesCreateBody.shape)+ return z.preprocess(+ normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),+ SurveysSummarizeResponsesCreateParams.omit({ project_id: true })+ .extend(SurveysSummarizeResponsesCreateQueryParams.shape)+ .extend(SurveysSummarizeResponsesCreateBody.shape)+ )}const surveysSummarizeResponsesCreate = (): ToolBase<diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-stats.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-stats.jsonindex a3d7a6335272..5c6d18cddfcd 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-stats.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-stats.json@@ -2,15 +2,11 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"date_from": {- "description": "Optional ISO timestamp for start date (e.g. 2024-01-01T00:00:00Z)",- "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)))$",+ "description": "Optional start date: an ISO 8601 timestamp (e.g. 2024-01-01T00:00:00Z) or a relative date such as -7d, -24h or -1m","type": "string"},"date_to": {- "description": "Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)",- "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)))$",+ "description": "Optional end date: an ISO 8601 timestamp (e.g. 2024-01-31T23:59:59Z) or a relative date such as -1d","type": "string"},"id": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-global-stats.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-global-stats.jsonindex e467f2971b35..bdbf74c56d39 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-global-stats.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-global-stats.json@@ -2,15 +2,11 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"date_from": {- "description": "Optional ISO timestamp for start date (e.g. 2024-01-01T00:00:00Z)",- "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)))$",+ "description": "Optional start date: an ISO 8601 timestamp (e.g. 2024-01-01T00:00:00Z) or a relative date such as -7d, -24h or -1m","type": "string"},"date_to": {- "description": "Optional ISO timestamp for end date (e.g. 2024-01-31T23:59:59Z)",- "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)))$",+ "description": "Optional end date: an ISO 8601 timestamp (e.g. 2024-01-31T23:59:59Z) or a relative date such as -1d","type": "string"}},diff --git a/services/mcp/tests/unit/survey-id-aliases.test.ts b/services/mcp/tests/unit/survey-id-aliases.test.tsnew file mode 100644index 000000000000..74f5fc34b9f1--- /dev/null+++ b/services/mcp/tests/unit/survey-id-aliases.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest'+import { z } from 'zod'++import { GENERATED_TOOLS as SURVEY_TOOLS } from '@/tools/generated/surveys'++const SURVEY_ID = '0199a1c0-0000-7000-8000-000000000000'+const OTHER_ID = '0199a1c0-0000-7000-8000-000000000001'++// Derived from the generated tools, so a new id-taking survey tool cannot ship without the aliases.+const SURVEY_ID_TOOLS = Object.entries(SURVEY_TOOLS)+ .filter(([, factory]) => {+ const json = z.toJSONSchema(factory().schema, { io: 'input', reused: 'inline' }) as {+ properties?: Record<string, unknown>+ }+ return Boolean(json.properties?.id)+ })+ .map(([name]) => name)+ .sort()++describe('survey id aliases', () => {+ it('finds the survey tools that take an id', () => {+ expect(SURVEY_ID_TOOLS).toEqual(+ expect.arrayContaining(['survey-get', 'survey-stats', 'survey-update', 'surveys-responses-list'])+ )+ })++ describe.each(SURVEY_ID_TOOLS)('%s', (toolName) => {+ const schema = SURVEY_TOOLS[toolName]!().schema++ it.each([+ ['id', { id: SURVEY_ID }],+ ['survey_id', { survey_id: SURVEY_ID }],+ ['surveyId', { surveyId: SURVEY_ID }],+ ['id over aliases on conflict', { id: SURVEY_ID, survey_id: OTHER_ID, surveyId: OTHER_ID }],+ ])('accepts %s', (_label, input) => {+ const result = schema.safeParse(input)+ expect(result.success, JSON.stringify(result.error?.issues)).toBe(true)+ const data = result.data as Record<string, unknown>+ expect(data.id).toEqual(SURVEY_ID)+ expect(data).not.toHaveProperty('survey_id')+ expect(data).not.toHaveProperty('surveyId')+ })++ it('still rejects a call with no identifier', () => {+ expect(schema.safeParse({}).success).toBe(false)+ })+ })+})