:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): add issue list/detail/events error tracking tools (#57052)
Catalin Irimie167490adece1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 745f7c24ee0e..11a308912f87 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3301,7 +3301,7 @@ snapshots:mcp-apps-error-tracking--chained-exceptions--light:hash: v1.k794b7964.389fb139ebca1a46d52bbde8fb206d19fca821f4246fbaeeec5cb6abac1edbe0.Tdry9M03t4ByyoywuZ8Ji3HdpO458gYKGWeSXtbvCBMmcp-apps-error-tracking--error-details--light:- hash: v1.k794b7964.15370fe6ee63046e8dde963d24a7cb1dc72d3f33ee3c063b99e7ab44bc4f527e.K95H1vX5WL6oT6pwRoUHaGotlgHnqcXZesFxjqoahqY+ hash: v1.k794b7964.74f9d68f76de7bb2b9a8fe2c9e9eb1d0e168e36ec968ea31db600fee9ceb9c5e.g8P9K2bwwae_R1V-A3RPR6mAzlfgAIvg97NX470Cz4Mmcp-apps-error-tracking--list--light:hash: v1.k794b7964.9aa5264a8942447254a8133097d32ff170bb770882f7c9e6986e9e8002ec2bfd.032Gz3ampq0eCejp_vtf7TYyket4mu5-jhhZWYeU-s4mcp-apps-error-tracking--python-stack-trace--light:diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex 39c69a17761d..d9e09452874c 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -63,6 +63,7 @@ from products.error_tracking.backend.api import (ErrorTrackingFingerprintViewSet,ErrorTrackingGroupingRuleViewSet,ErrorTrackingIssueViewSet,+ ErrorTrackingQueryViewSet,ErrorTrackingRecommendationViewSet,ErrorTrackingReleaseViewSet,ErrorTrackingSettingsViewSet,@@ -1005,6 +1006,13 @@ environments_router.register(["team_id"],)+environments_router.register(+ r"error_tracking/query",+ ErrorTrackingQueryViewSet,+ "environment_error_tracking_query",+ ["team_id"],+)+environments_router.register(r"error_tracking/external_references",ErrorTrackingExternalReferenceViewSet,diff --git a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambrindex c3c33d4047ff..652ad9924b86 100644--- a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr+++ b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr@@ -1143,19 +1143,6 @@'''# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.32- '''- SELECT "posthog_teamrevenueanalyticsconfig"."team_id",- "posthog_teamrevenueanalyticsconfig"."filter_test_accounts",- "posthog_teamrevenueanalyticsconfig"."notified_first_sync",- "posthog_teamrevenueanalyticsconfig"."events",- "posthog_teamrevenueanalyticsconfig"."goals",- "posthog_teamrevenueanalyticsconfig"."base_currency"- FROM "posthog_teamrevenueanalyticsconfig"- WHERE "posthog_teamrevenueanalyticsconfig"."team_id" = 99999- LIMIT 21- '''-# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.33'''SELECT "posthog_externaldatasource"."created_by_id","posthog_externaldatasource"."created_at",@@ -1189,7 +1176,7 @@AND "posthog_externaldatasource"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.34+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.33'''SELECT "posthog_datawarehousetable"."created_by_id","posthog_datawarehousetable"."created_at",@@ -1245,7 +1232,7 @@AND "posthog_externaldatasource"."access_method" IS NOT NULL))'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.35+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.34'''SELECT "posthog_datawarehousejoin"."created_by_id","posthog_datawarehousejoin"."created_at",@@ -1265,7 +1252,7 @@AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.36+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.35'''SELECT 1 AS "a"FROM "access_control_propertyaccesscontrol"@@ -1274,7 +1261,7 @@LIMIT 1'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.37+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.36'''SELECT 1 AS "a"FROM "access_control_propertyaccesscontrol"@@ -1283,7 +1270,7 @@LIMIT 1'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.38+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.37'''SELECT COUNT(*)FROM@@ -1292,7 +1279,7 @@WHERE "ee_single_session_summary"."team_id" = 99999) subquery'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.39+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.38'''SELECT "posthog_user"."id","posthog_user"."password",@@ -1335,7 +1322,7 @@LIMIT 21'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.4+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.39'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -1373,7 +1360,7 @@LIMIT 21'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.40+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.4'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -1411,7 +1398,7 @@LIMIT 21'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.41+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.40'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -1540,7 +1527,7 @@LIMIT 21'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.42+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.41'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -1587,7 +1574,7 @@LIMIT 21'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.43+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.42'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -1633,7 +1620,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.44+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.43'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -1678,7 +1665,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.45+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.44'''SELECT COUNT(*) AS "__count"FROM "posthog_sessionrecordingplaylist"@@ -1689,7 +1676,7 @@AND NOT "posthog_sessionrecordingplaylist"."deleted")'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.46+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.45'''SELECT COUNT(*) AS "__count"FROM "posthog_sessionrecordingplaylist"@@ -1700,7 +1687,7 @@AND NOT "posthog_sessionrecordingplaylist"."deleted")'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.47+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.46'''SELECT "posthog_sessionrecordingplaylist"."id","posthog_sessionrecordingplaylist"."short_id",@@ -1902,7 +1889,7 @@LIMIT 100'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.48+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.47'''SELECT "posthog_sessionrecordingplaylistitem"."playlist_id" AS "playlist_id",COUNT("posthog_sessionrecordingplaylistitem"."id") AS "c"@@ -1919,7 +1906,7 @@GROUP BY 1'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.49+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.48'''SELECT "posthog_sessionrecordingplaylistitem"."playlist_id" AS "playlist_id","posthog_sessionrecordingplaylistitem"."recording_id" AS "recording_id"@@ -1933,6 +1920,15 @@5 /* ... */))'''# ---+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.49+ '''+ SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"+ FROM "posthog_sessionrecordingviewed"+ WHERE ("posthog_sessionrecordingviewed"."team_id" = 99999+ AND "posthog_sessionrecordingviewed"."user_id" = 99999+ AND "posthog_sessionrecordingviewed"."session_id" IN ('00000000-0000-0000-0000-000000000000'))+ '''+# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.5'''SELECT "posthog_team"."id",@@ -2063,15 +2059,6 @@'''# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.50- '''- SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"- FROM "posthog_sessionrecordingviewed"- WHERE ("posthog_sessionrecordingviewed"."team_id" = 99999- AND "posthog_sessionrecordingviewed"."user_id" = 99999- AND "posthog_sessionrecordingviewed"."session_id" IN ('00000000-0000-0000-0000-000000000000'))- '''-# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.51'''SELECT COUNT(*) AS "__count"FROM "posthog_sessionrecordingviewed"@@ -2079,7 +2066,7 @@AND "posthog_sessionrecordingviewed"."user_id" = 99999)'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.52+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.51'''SELECT COUNT(*)FROM@@ -2091,7 +2078,7 @@AND NOT ("posthog_comment"."item_id" IS NULL))) subquery'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.53+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.52'''SELECT COUNT(*)FROM@@ -2102,7 +2089,7 @@AND NOT ("posthog_sharingconfiguration"."recording_id" IS NULL))) subquery'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.54+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.53'''SELECT COUNT(*)FROM@@ -2117,7 +2104,7 @@AND "posthog_exportedasset"."export_context" IS NOT NULL))) subquery'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.55+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.54'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -2182,7 +2169,7 @@ORDER BY "posthog_datawarehousesavedquery"."name" ASC'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.56+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.55'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -2239,7 +2226,7 @@AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.57+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.56'''SELECT "posthog_externaldatasource"."created_by_id","posthog_externaldatasource"."created_at",@@ -2273,7 +2260,7 @@AND "posthog_externaldatasource"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.58+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.57'''SELECT "posthog_datawarehousetable"."created_by_id","posthog_datawarehousetable"."created_at",@@ -2329,7 +2316,7 @@AND "posthog_externaldatasource"."access_method" IS NOT NULL))'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.59+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.58'''SELECT "posthog_datawarehousejoin"."created_by_id","posthog_datawarehousejoin"."created_at",@@ -2349,6 +2336,15 @@AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))'''# ---+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.59+ '''+ SELECT 1 AS "a"+ FROM "access_control_propertyaccesscontrol"+ WHERE ("access_control_propertyaccesscontrol"."team_id" = 99999+ AND NOT ("access_control_propertyaccesscontrol"."property_definition_id" IS NULL))+ LIMIT 1+ '''+# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.6'''SELECT "posthog_organizationmembership"."id",@@ -2407,11 +2403,11 @@# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.61'''- SELECT 1 AS "a"- FROM "access_control_propertyaccesscontrol"- WHERE ("access_control_propertyaccesscontrol"."team_id" = 99999- AND NOT ("access_control_propertyaccesscontrol"."property_definition_id" IS NULL))- LIMIT 1+ SELECT COUNT(*)+ FROM+ (SELECT DISTINCT "ee_single_session_summary"."session_id" AS "session_id"+ FROM "ee_single_session_summary"+ WHERE "ee_single_session_summary"."team_id" = 99999) subquery'''# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.62diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex cd95ec8e584c..a527b15aaec3 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -452,6 +452,8 @@ SPECTACULAR_SETTINGS = {"workflow_variable",],"AssigneeTypeEnum": ["user", "role"],+ "ErrorTrackingIssueOrderByEnum": ["last_seen", "first_seen", "occurrences", "users", "sessions"],+ "OrderByEnum": ["latest", "earliest"],"PropertyGroupTypeEnum": ["cohort", "person", "group"],"ExistenceOperatorEnum": ["is_set", "is_not_set"],"TaskExecutionModeEnum": ["interactive", "background"],diff --git a/products/error_tracking/backend/api/__init__.py b/products/error_tracking/backend/api/__init__.pyindex 0c01cc46af95..ab4c58e0f8f9 100644--- a/products/error_tracking/backend/api/__init__.py+++ b/products/error_tracking/backend/api/__init__.py@@ -4,6 +4,7 @@ from .fingerprints import ErrorTrackingFingerprintViewSetfrom .git_provider_file_link_resolver import GitProviderFileLinksViewSetfrom .grouping_rules import ErrorTrackingGroupingRuleViewSetfrom .issues import ErrorTrackingIssueViewSet+from .query import ErrorTrackingQueryViewSetfrom .recommendations import ErrorTrackingRecommendationViewSetfrom .releases import ErrorTrackingReleaseViewSetfrom .settings import ErrorTrackingSettingsViewSet@@ -16,6 +17,7 @@ from .symbol_sets import ErrorTrackingSymbolSetViewSet__all__ = ["ErrorTrackingExternalReferenceViewSet","ErrorTrackingIssueViewSet",+ "ErrorTrackingQueryViewSet","ErrorTrackingRecommendationViewSet","ErrorTrackingStackFrameViewSet","ErrorTrackingSymbolSetViewSet",diff --git a/products/error_tracking/backend/api/query.py b/products/error_tracking/backend/api/query.pynew file mode 100644index 000000000000..68fc9e47b57a--- /dev/null+++ b/products/error_tracking/backend/api/query.py@@ -0,0 +1,249 @@+from __future__ import annotations++from typing import Literal, cast++import structlog+from drf_spectacular.utils import OpenApiResponse+from rest_framework import status, viewsets+from rest_framework.response import Response++from posthog.schema import DateRange, ErrorTrackingIssueAssignee, ErrorTrackingQuery, EventsQuery, ProductKey++from posthog.api.documentation import extend_schema+from posthog.api.mixins import ValidatedRequest, validated_request+from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.utils import action+from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.hogql_queries.events_query_runner import EventsQueryRunner++from products.error_tracking.backend.hogql_queries.error_tracking_query_runner import ErrorTrackingQueryRunner+from products.error_tracking.backend.models import ErrorTrackingIssue++from .query_serializers import (+ ErrorTrackingIssueDetailSerializer,+ ErrorTrackingIssueEventsQueryRequestSerializer,+ ErrorTrackingIssueEventsResponseSerializer,+ ErrorTrackingIssueQueryRequestSerializer,+ ErrorTrackingIssuesListQueryRequestSerializer,+ ErrorTrackingIssuesListResponseSerializer,+)+from .query_utils import (+ CONTEXT_EVENT_SELECTS,+ EVENT_SELECTS,+ ISSUE_FIELDS,+ LIST_ISSUE_FIELDS,+ build_date_range,+ build_event_where,+ build_impact,+ build_issue_filters,+ build_issue_where,+ build_property_group,+ build_search_query,+ build_sparkline,+ build_top_in_app_frame,+ compact_dict,+ extract_latest_release,+ get_page_info,+ map_context_event_properties,+ map_event_row,+ pick_fields,+)++logger = structlog.get_logger(__name__)+++@extend_schema(tags=[ProductKey.ERROR_TRACKING])+class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):+ scope_object = "error_tracking"++ @validated_request(+ request_serializer=ErrorTrackingIssuesListQueryRequestSerializer,+ responses={200: OpenApiResponse(response=ErrorTrackingIssuesListResponseSerializer)},+ operation_id="error_tracking_query_issues_list_create",+ summary="List compact error tracking issues",+ description="List error tracking issues with typed filters and compact aggregate counts.",+ )+ @action(methods=["POST"], detail=False, url_path="issues", required_scopes=["error_tracking:read"])+ def issues(self, request: ValidatedRequest, **kwargs: object) -> Response:+ params = dict(request.validated_data)+ filters = build_issue_filters(params)+ limit = cast(int, params.get("limit", 25))+ offset = cast(int, params.get("offset", 0))+ assignee = params.get("assignee")+ person_id = params.get("personId")+ query = ErrorTrackingQuery(+ kind="ErrorTrackingQuery",+ dateRange=DateRange(**build_date_range(params.get("dateRange"))),+ status=cast(str, params.get("status", "active")),+ assignee=ErrorTrackingIssueAssignee(**assignee) if isinstance(assignee, dict) else None,+ filterTestAccounts=cast(bool, params.get("filterTestAccounts", True)),+ searchQuery=build_search_query(params),+ filterGroup=build_property_group(filters),+ orderBy=cast(str, params.get("orderBy", "occurrences")),+ orderDirection=cast(Literal["ASC", "DESC"], params.get("orderDirection", "DESC")),+ limit=limit,+ offset=offset,+ volumeResolution=cast(int, params.get("volumeResolution", 0)),+ personId=str(person_id) if person_id is not None else None,+ withAggregations=True,+ withFirstEvent=False,+ withLastEvent=False,+ tags={"productKey": "error_tracking"},+ )+ with tags_context(product=Product.ERROR_TRACKING, feature=Feature.QUERY):+ data = ErrorTrackingQueryRunner(team=self.team, query=query).calculate().model_dump(mode="json")+ raw_results_value = data.get("results")+ raw_results: list[object] = raw_results_value if isinstance(raw_results_value, list) else []+ results = [pick_fields(cast(dict[str, object], issue), LIST_ISSUE_FIELDS) for issue in raw_results[:limit]]+ has_more, next_offset = get_page_info(data, limit, offset)+ payload: dict[str, object] = {"results": results, "hasMore": has_more, "limit": limit, "offset": offset}+ if next_offset is not None:+ payload["nextOffset"] = next_offset+ return Response(payload)++ @validated_request(+ request_serializer=ErrorTrackingIssueQueryRequestSerializer,+ responses={+ 200: OpenApiResponse(response=ErrorTrackingIssueDetailSerializer),+ 404: OpenApiResponse(description="Issue not found"),+ },+ operation_id="error_tracking_query_issue_create",+ summary="Get compact error tracking issue details",+ description="Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional sparkline.",+ )+ @action(methods=["POST"], detail=False, url_path="issue", required_scopes=["error_tracking:read"])+ def issue(self, request: ValidatedRequest, **kwargs: object) -> Response:+ params = dict(request.validated_data)+ issue_id = str(params["issueId"])+ date_range = build_date_range(params.get("dateRange"))+ include_sparkline = cast(bool, params.get("includeSparkline", False))+ volume_resolution = cast(int, params.get("volumeResolution", 0))+ if include_sparkline and volume_resolution <= 0:+ volume_resolution = 12+ issue_model = ErrorTrackingIssue.objects.filter(team=self.team, id=issue_id).first()+ if issue_model is None:+ return Response(status=status.HTTP_404_NOT_FOUND)+ query = ErrorTrackingQuery(+ kind="ErrorTrackingQuery",+ issueId=issue_id,+ dateRange=DateRange(**date_range),+ filterTestAccounts=cast(bool, params.get("filterTestAccounts", True)),+ volumeResolution=volume_resolution,+ limit=1,+ orderBy="last_seen",+ orderDirection="DESC",+ withAggregations=True,+ withFirstEvent=False,+ withLastEvent=False,+ tags={"productKey": "error_tracking"},+ )+ with tags_context(product=Product.ERROR_TRACKING, feature=Feature.QUERY):+ data = ErrorTrackingQueryRunner(team=self.team, query=query).calculate().model_dump(mode="json")+ raw_results_value = data.get("results")+ raw_results: list[object] = raw_results_value if isinstance(raw_results_value, list) else []+ if not raw_results:+ payload: dict[str, object] = compact_dict(+ {+ "id": str(issue_model.id),+ "name": issue_model.name,+ "description": issue_model.description,+ "status": issue_model.status,+ }+ )+ payload["impact"] = {}+ if include_sparkline:+ payload["sparkline"] = []+ return Response(payload)+ issue = cast(dict[str, object], raw_results[0])+ event_properties: dict[str, object] = {}+ try:+ context_event_query = EventsQuery(+ kind="EventsQuery",+ event="$exception",+ select=CONTEXT_EVENT_SELECTS,+ where=build_issue_where(issue_id),+ filterTestAccounts=cast(bool, params.get("filterTestAccounts", True)),+ after=date_range.get("date_from"),+ before=date_range.get("date_to"),+ orderBy=["timestamp DESC"],+ limit=1,+ tags={"productKey": "error_tracking"},+ )+ with tags_context(product=Product.ERROR_TRACKING, feature=Feature.QUERY):+ event_data = (+ EventsQueryRunner(team=self.team, query=context_event_query).calculate().model_dump(mode="json")+ )+ if event_data.get("error"):+ logger.warning(+ "error_tracking_issue_context_query_failed",+ issue_id=issue_id,+ team_id=self.team.pk,+ error=event_data.get("error"),+ )+ else:+ event_properties = map_context_event_properties(event_data)+ except Exception:+ logger.warning(+ "error_tracking_issue_context_query_failed",+ issue_id=issue_id,+ team_id=self.team.pk,+ exc_info=True,+ )+ payload = compact_dict(+ {+ **pick_fields(issue, ISSUE_FIELDS),+ "top_in_app_frame": build_top_in_app_frame(issue, event_properties),+ "latest_release": extract_latest_release(event_properties),+ "impact": build_impact(issue),+ "sparkline": build_sparkline(issue) if include_sparkline else None,+ }+ )+ return Response(payload)++ @validated_request(+ request_serializer=ErrorTrackingIssueEventsQueryRequestSerializer,+ responses={+ 200: OpenApiResponse(response=ErrorTrackingIssueEventsResponseSerializer),+ 404: OpenApiResponse(description="Issue not found"),+ },+ operation_id="error_tracking_query_issue_events_create",+ summary="List sampled exception events for an error tracking issue",+ description="Fetch sampled exception events, stack traces, browser/SDK context, URL, and $session_id values for one issue.",+ )+ @action(methods=["POST"], detail=False, url_path="issue_events", required_scopes=["error_tracking:read"])+ def issue_events(self, request: ValidatedRequest, **kwargs: object) -> Response:+ params = dict(request.validated_data)+ issue_id = str(params["issueId"])+ limit = cast(int, params.get("limit", 1))+ offset = cast(int, params.get("offset", 0))+ if not ErrorTrackingIssue.objects.filter(team=self.team, id=issue_id).exists():+ return Response(status=status.HTTP_404_NOT_FOUND)+ date_range = build_date_range(params.get("dateRange"))+ query = EventsQuery(+ kind="EventsQuery",+ event="$exception",+ select=EVENT_SELECTS,+ where=build_event_where(issue_id, cast(str | None, params.get("searchQuery"))),+ properties=cast(list[dict[str, object]], params.get("filterGroup", [])),+ filterTestAccounts=cast(bool, params.get("filterTestAccounts", True)),+ after=date_range.get("date_from"),+ before=date_range.get("date_to"),+ orderBy=[f"timestamp {params.get('orderDirection', 'DESC')}"],+ limit=limit,+ offset=offset,+ tags={"productKey": "error_tracking"},+ )+ with tags_context(product=Product.ERROR_TRACKING, feature=Feature.QUERY):+ data = EventsQueryRunner(team=self.team, query=query).calculate().model_dump(mode="json")+ raw_columns = data.get("columns")+ columns = [str(column) for column in raw_columns] if isinstance(raw_columns, list) else EVENT_SELECTS+ raw_results_value = data.get("results")+ raw_results: list[object] = raw_results_value if isinstance(raw_results_value, list) else []+ verbosity = cast(str, params.get("verbosity", "summary"))+ only_app_frames = cast(bool, params.get("onlyAppFrames", True))+ results = [map_event_row(row, columns, verbosity, only_app_frames) for row in raw_results[:limit]]+ has_more, next_offset = get_page_info(data, limit, offset)+ payload: dict[str, object] = {"results": results, "hasMore": has_more, "limit": limit, "offset": offset}+ if next_offset is not None:+ payload["nextOffset"] = next_offset+ return Response(payload)diff --git a/products/error_tracking/backend/api/query_serializers.py b/products/error_tracking/backend/api/query_serializers.pynew file mode 100644index 000000000000..97cb350b4b8b--- /dev/null+++ b/products/error_tracking/backend/api/query_serializers.py@@ -0,0 +1,311 @@+from __future__ import annotations++from typing import cast++from rest_framework import serializers++from posthog.api.documentation import PropertyItemSerializer, extend_schema_field++STRING_OR_STRING_LIST_SCHEMA = {+ "oneOf": [+ {"type": "string"},+ {"type": "array", "items": {"type": "string"}, "minItems": 1},+ ]+}++JSON_OBJECT_SCHEMA = {"type": "object", "additionalProperties": True}+++@extend_schema_field(STRING_OR_STRING_LIST_SCHEMA)+class StringOrStringListField(serializers.Field):+ def to_internal_value(self, data: object) -> str | list[str]:+ if isinstance(data, str):+ return data+ if isinstance(data, list) and data and all(isinstance(item, str) for item in data):+ return cast(list[str], data)+ raise serializers.ValidationError("Expected a string or a non-empty list of strings.")++ def to_representation(self, value: object) -> str | list[str]:+ if isinstance(value, str):+ return value+ if isinstance(value, list):+ return [str(item) for item in value]+ return str(value)+++@extend_schema_field(+ {+ "oneOf": [{"type": "string"}, {"type": "integer"}],+ }+)+class StringOrIntegerField(serializers.Field):+ def to_internal_value(self, data: object) -> str | int:+ if isinstance(data, bool):+ raise serializers.ValidationError("Expected a string or integer.")+ if isinstance(data, int | str):+ return data+ raise serializers.ValidationError("Expected a string or integer.")++ def to_representation(self, value: object) -> str | int:+ return value if isinstance(value, int | str) else str(value)+++@extend_schema_field(JSON_OBJECT_SCHEMA)+class JSONObjectField(serializers.JSONField):+ pass+++class ErrorTrackingDateRangeSerializer(serializers.Serializer):+ date_from = serializers.CharField(+ required=False,+ help_text="Start of the date range as an ISO timestamp or relative date such as -7d. Defaults to -7d.",+ )+ date_to = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="End of the date range as an ISO timestamp or relative date. Defaults to now when omitted.",+ )+++def validate_filter_group(value: list[dict[str, object]]) -> list[dict[str, object]]:+ for item in value:+ if item.get("type") == "hogql":+ raise serializers.ValidationError("HogQL property filters are not supported here.")+ return value+++class ErrorTrackingAssigneeSerializer(serializers.Serializer):+ id = StringOrIntegerField(help_text="User ID or role UUID to filter by.")+ type = serializers.ChoiceField(choices=["user", "role"], help_text="Assignee target type: user or role.")+++class ErrorTrackingIssuesListQueryRequestSerializer(serializers.Serializer):+ dateRange = ErrorTrackingDateRangeSerializer(+ required=False,+ help_text="Date range for issue aggregates. Defaults to the last 7 days.",+ )+ status = serializers.ChoiceField(+ choices=["archived", "active", "resolved", "pending_release", "suppressed", "all"],+ required=False,+ default="active",+ help_text="Filter by issue status. Defaults to active.",+ )+ assignee = ErrorTrackingAssigneeSerializer(+ required=False,+ allow_null=True,+ help_text="Filter by issue assignee. Omit to include all assignees.",+ )+ filterTestAccounts = serializers.BooleanField(+ required=False,+ default=True,+ help_text="When true, exclude internal/test account data from results. Defaults to true.",+ )+ searchQuery = serializers.CharField(+ required=False,+ max_length=500,+ help_text="Free-text search across exception types, values, stack frames, and email fields.",+ )+ filterGroup = serializers.ListField(+ child=PropertyItemSerializer(),+ required=False,+ default=list,+ help_text="Advanced flat AND property filters. Prefer typed shortcut fields when they fit. HogQL filters are rejected.",+ )+ orderBy = serializers.ChoiceField(+ choices=["last_seen", "first_seen", "occurrences", "users", "sessions"],+ required=False,+ default="occurrences",+ help_text="Field used to sort issues. Defaults to occurrences.",+ )+ orderDirection = serializers.ChoiceField(+ choices=["ASC", "DESC"], required=False, default="DESC", help_text="Sort direction. Defaults to DESC."+ )+ limit = serializers.IntegerField(required=False, min_value=1, max_value=100, default=25, help_text="Page size.")+ offset = serializers.IntegerField(required=False, min_value=0, default=0, help_text="Pagination offset.")+ volumeResolution = serializers.IntegerField(+ required=False,+ min_value=0,+ max_value=200,+ default=0,+ help_text="Number of volume buckets. Defaults to 0 for compact aggregate counts.",+ )+ library = StringOrStringListField(+ required=False, help_text="Filter by SDK/library value from event $lib, for example posthog-js."+ )+ release = serializers.CharField(+ required=False,+ max_length=500,+ help_text="Filter by exact release ID, version, or git commit ID captured in $exception_releases.",+ )+ fingerprint = StringOrStringListField(+ required=False, help_text="Filter by exact exception fingerprint hash, not fuzzy search."+ )+ user = serializers.CharField(required=False, max_length=500, help_text="Search user/email text.")+ personId = serializers.UUIDField(required=False, help_text="Filter by exact PostHog person UUID.")+ url = serializers.CharField(required=False, max_length=1000, help_text="Filter by current URL substring.")+ filePath = serializers.CharField(+ required=False, max_length=1000, help_text="Search stack-frame source/file path text."+ )++ def validate_filterGroup(self, value: list[dict[str, object]]) -> list[dict[str, object]]:+ return validate_filter_group(value)+++class ErrorTrackingIssueQueryRequestSerializer(serializers.Serializer):+ issueId = serializers.UUIDField(help_text="Error tracking issue ID.")+ dateRange = ErrorTrackingDateRangeSerializer(+ required=False,+ help_text="Date range for issue impact and latest-event metadata. Defaults to the last 7 days.",+ )+ filterTestAccounts = serializers.BooleanField(+ required=False,+ default=True,+ help_text="When true, exclude internal/test account data from results. Defaults to true.",+ )+ volumeResolution = serializers.IntegerField(+ required=False, min_value=0, max_value=200, default=0, help_text="Volume buckets. Maximum 200."+ )+ includeSparkline = serializers.BooleanField(+ required=False,+ default=False,+ help_text="Set true to include a compact numeric occurrence sparkline. Defaults to false.",+ )+++class ErrorTrackingIssueEventsQueryRequestSerializer(serializers.Serializer):+ issueId = serializers.UUIDField(help_text="Error tracking issue ID.")+ dateRange = ErrorTrackingDateRangeSerializer(+ required=False,+ help_text="Date range for sampled exception events. Defaults to the last 7 days.",+ )+ filterTestAccounts = serializers.BooleanField(+ required=False,+ default=True,+ help_text="When true, exclude internal/test account data from results. Defaults to true.",+ )+ filterGroup = serializers.ListField(+ child=PropertyItemSerializer(),+ required=False,+ default=list,+ help_text="Advanced flat AND property filters applied to sampled events. HogQL filters are rejected.",+ )+ searchQuery = serializers.CharField(+ required=False,+ max_length=500,+ help_text="Search exception types, exception values, and current URL among sampled events.",+ )+ orderDirection = serializers.ChoiceField(+ choices=["ASC", "DESC"], required=False, default="DESC", help_text="Timestamp sort direction. Defaults to DESC."+ )+ limit = serializers.IntegerField(required=False, min_value=1, max_value=20, default=1, help_text="Page size.")+ offset = serializers.IntegerField(required=False, min_value=0, default=0, help_text="Pagination offset.")+ verbosity = serializers.ChoiceField(+ choices=["summary", "stack", "raw"],+ required=False,+ default="summary",+ help_text="Controls exception detail size: summary, stack, or raw. Defaults to summary.",+ )+ onlyAppFrames = serializers.BooleanField(+ required=False,+ default=True,+ help_text="When true, include only stack frames marked in_app. Defaults to true.",+ )++ def validate_filterGroup(self, value: list[dict[str, object]]) -> list[dict[str, object]]:+ return validate_filter_group(value)+++class ErrorTrackingAssigneeResponseSerializer(serializers.Serializer):+ id = StringOrIntegerField(required=False, allow_null=True, help_text="Assignee user ID or role UUID.")+ type = serializers.CharField(required=False, allow_null=True, help_text="Assignee type.")+++class ErrorTrackingVolumeBucketSerializer(serializers.Serializer):+ label = serializers.CharField(help_text="Bucket timestamp label.") # type: ignore[assignment]+ value = serializers.FloatField(required=False, allow_null=True, help_text="Occurrence count for the bucket.")+++class ErrorTrackingImpactSerializer(serializers.Serializer):+ occurrences = serializers.FloatField(required=False, help_text="Exception occurrence count.")+ users = serializers.FloatField(required=False, help_text="Unique user count.")+ sessions = serializers.FloatField(required=False, help_text="Unique session count.")+++class ErrorTrackingAggregationsSerializer(ErrorTrackingImpactSerializer):+ volumeRange = serializers.ListField(+ child=serializers.FloatField(), required=False, help_text="Occurrence counts per volume bucket."+ )+ volume_buckets = serializers.ListField(+ child=ErrorTrackingVolumeBucketSerializer(), required=False, help_text="Labeled volume buckets."+ )+++class ErrorTrackingIssueListItemSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="Error tracking issue ID.")+ name = serializers.CharField(required=False, allow_null=True, help_text="Issue name.")+ description = serializers.CharField(required=False, allow_null=True, help_text="Issue description.")+ status = serializers.CharField(required=False, help_text="Issue status.")+ first_seen = serializers.DateTimeField(required=False, allow_null=True, help_text="First seen timestamp.")+ last_seen = serializers.DateTimeField(required=False, allow_null=True, help_text="Last seen timestamp.")+ library = serializers.CharField(required=False, allow_null=True, help_text="SDK/library associated with the issue.")+ source = serializers.CharField( # type: ignore[assignment]+ required=False, allow_null=True, help_text="Top source/file associated with the issue."+ )+ assignee = ErrorTrackingAssigneeResponseSerializer(required=False, allow_null=True, help_text="Issue assignee.")+ aggregations = ErrorTrackingAggregationsSerializer(required=False, allow_null=True, help_text="Aggregate counts.")+++class ErrorTrackingIssuesListResponseSerializer(serializers.Serializer):+ results = ErrorTrackingIssueListItemSerializer(many=True, help_text="Issue rows.")+ hasMore = serializers.BooleanField(help_text="Whether more results are available.")+ limit = serializers.IntegerField(help_text="Page size.")+ offset = serializers.IntegerField(help_text="Current offset.")+ nextOffset = serializers.IntegerField(+ required=False, help_text="Offset to fetch the next page when hasMore is true."+ )+++class ErrorTrackingTopFrameSerializer(serializers.Serializer):+ function = serializers.CharField(required=False, help_text="Frame function name.")+ source = serializers.CharField(required=False, help_text="Frame source, filename, or module.") # type: ignore[assignment]+ line = serializers.IntegerField(required=False, help_text="Line number.")+ column = serializers.IntegerField(required=False, help_text="Column number.")+ in_app = serializers.BooleanField(required=False, help_text="Whether the frame is an application frame.")+++class ErrorTrackingLatestReleaseSerializer(serializers.Serializer):+ version = serializers.CharField(required=False, help_text="Release version.")+ project = serializers.CharField(required=False, help_text="Release project/library.")+ timestamp = serializers.CharField(required=False, help_text="Release timestamp.")+ commit_id = serializers.CharField(required=False, help_text="Git commit ID.")+ branch = serializers.CharField(required=False, help_text="Git branch.")+ repo_name = serializers.CharField(required=False, help_text="Git repository name.")+++class ErrorTrackingIssueDetailSerializer(ErrorTrackingIssueListItemSerializer):+ function = serializers.CharField(+ required=False, allow_null=True, help_text="Top function associated with the issue."+ )+ top_in_app_frame = ErrorTrackingTopFrameSerializer(required=False, help_text="Top in_app application frame.")+ latest_release = ErrorTrackingLatestReleaseSerializer(required=False, help_text="Latest release metadata.")+ impact = ErrorTrackingImpactSerializer(required=False, help_text="Compact impact counts.")+ sparkline = serializers.ListField(+ child=serializers.FloatField(), required=False, help_text="Optional compact occurrence sparkline."+ )+++class ErrorTrackingEventSerializer(serializers.Serializer):+ uuid = serializers.CharField(required=False, help_text="Event UUID.")+ distinct_id = serializers.CharField(required=False, help_text="Event distinct ID.")+ timestamp = serializers.DateTimeField(required=False, help_text="Event timestamp.")+ properties = JSONObjectField(required=False, help_text="Normalized sampled exception event properties.")+++class ErrorTrackingIssueEventsResponseSerializer(serializers.Serializer):+ results = ErrorTrackingEventSerializer(many=True, help_text="Sampled exception events.")+ hasMore = serializers.BooleanField(help_text="Whether more results are available.")+ limit = serializers.IntegerField(help_text="Page size.")+ offset = serializers.IntegerField(help_text="Current offset.")+ nextOffset = serializers.IntegerField(+ required=False, help_text="Offset to fetch the next page when hasMore is true."+ )diff --git a/products/error_tracking/backend/api/query_utils.py b/products/error_tracking/backend/api/query_utils.pynew file mode 100644index 000000000000..b466cbe0cf83--- /dev/null+++ b/products/error_tracking/backend/api/query_utils.py@@ -0,0 +1,437 @@+from __future__ import annotations++import json+from typing import cast++from posthog.hogql.escape_sql import escape_hogql_string++MAX_NORMALIZED_TEXT_CHARS = 1000++ISSUE_FIELDS = [+ "id",+ "name",+ "description",+ "status",+ "first_seen",+ "last_seen",+ "library",+ "source",+ "function",+ "assignee",+]++LIST_ISSUE_FIELDS = [+ "id",+ "name",+ "description",+ "status",+ "first_seen",+ "last_seen",+ "library",+ "source",+ "assignee",+ "aggregations",+]++CONTEXT_EVENT_SELECTS = ["properties.$exception_list", "properties.$exception_releases"]+EVENT_PROPERTY_SELECTS = [+ "properties.$exception_types",+ "properties.$exception_values",+ "properties.$exception_list",+ "properties.$exception_fingerprint",+ "properties.$exception_issue_id",+ "properties.$session_id",+ "properties.$lib",+ "properties.$browser",+ "properties.$browser_version",+ "properties.$os",+ "properties.$os_version",+ "properties.$current_url",+]+EVENT_SELECTS = ["uuid", "timestamp", "distinct_id", *EVENT_PROPERTY_SELECTS]+EVENT_SEARCH_PROPERTIES = ["properties.$exception_types", "properties.$exception_values", "properties.$current_url"]+PROPERTY_COLUMN_NAMES = {+ select.removeprefix("properties.") for select in [*CONTEXT_EVENT_SELECTS, *EVENT_PROPERTY_SELECTS]+}+++def compact_dict(record: dict[str, object]) -> dict[str, object]:+ """Remove empty response fields while intentionally preserving 0 and false values."""+ return {+ key: value for key, value in record.items() if value is not None and value != [] and value != {} and value != ""+ }+++def escape_hogql_like_pattern(value: str) -> str:+ pattern = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")+ return escape_hogql_string(f"%{pattern}%")+++def as_list(value: str | list[str]) -> list[str]:+ return value if isinstance(value, list) else [value]+++def build_date_range(raw_date_range: object) -> dict[str, object]:+ date_range: dict[str, object] = {"date_from": "-7d"}+ if isinstance(raw_date_range, dict):+ date_range.update({str(key): value for key, value in raw_date_range.items()})+ return date_range+++def add_event_filter(filters: list[dict[str, object]], key: str, operator: str, value: str | list[str]) -> None:+ filters.append(+ {"type": "event", "key": key, "operator": operator, "value": as_list(value) if operator == "exact" else value}+ )+++def add_release_filter(filters: list[dict[str, object]], release: str) -> None:+ escaped_release = escape_hogql_string(release)+ releases_json = "ifNull(nullIf(JSONExtractRaw(properties, '$exception_releases'), ''), '{}')"+ filters.append(+ {+ "type": "hogql",+ "key": f"position(toString(properties.$exception_releases), {escaped_release}) > 0",+ }+ )+ filters.append(+ {+ "type": "hogql",+ "key": (+ f"arrayExists(r -> (r.1 = {escaped_release} "+ f"OR JSONExtractString(r.2, 'version') = {escaped_release} "+ f"OR JSONExtractString(JSONExtractRaw(r.2, 'metadata'), 'git', 'commit_id') = {escaped_release}), "+ f"JSONExtractKeysAndValuesRaw({releases_json}))"+ ),+ }+ )+++def build_issue_filters(params: dict[str, object]) -> list[dict[str, object]]:+ filters = [dict(item) for item in cast(list[dict[str, object]], params.get("filterGroup", []))]+ library = params.get("library")+ if isinstance(library, str | list):+ add_event_filter(filters, "$lib", "exact", cast(str | list[str], library))+ release = params.get("release")+ if isinstance(release, str):+ add_release_filter(filters, release)+ fingerprint = params.get("fingerprint")+ if isinstance(fingerprint, str | list):+ add_event_filter(filters, "$exception_fingerprint", "exact", cast(str | list[str], fingerprint))+ url = params.get("url")+ if isinstance(url, str):+ add_event_filter(filters, "$current_url", "icontains", url)+ return filters+++def build_property_group(filters: list[dict[str, object]]) -> dict[str, object] | None:+ if not filters:+ return None+ return {"type": "AND", "values": [{"type": "AND", "values": filters}]}+++def build_search_query(params: dict[str, object]) -> str | None:+ terms = [+ value.strip()+ for value in [params.get("searchQuery"), params.get("user"), params.get("filePath")]+ if isinstance(value, str) and value.strip()+ ]+ return " ".join(terms) if terms else None+++def get_page_info(data: dict[str, object], limit: int, offset: int) -> tuple[bool, int | None]:+ results = data.get("results")+ row_count = len(results) if isinstance(results, list) else 0+ has_more = bool(data.get("hasMore")) or row_count > limit+ return has_more, offset + limit if has_more else None+++def pick_fields(record: dict[str, object], fields: list[str]) -> dict[str, object]:+ return {field: record[field] for field in fields if field in record}+++def to_number(value: object) -> float | None:+ if isinstance(value, bool) or not isinstance(value, int | float):+ return None+ return float(value)+++def parse_jsonish(value: object) -> object:+ parsed = value+ for _ in range(2):+ if not isinstance(parsed, str):+ return parsed+ trimmed = parsed.strip()+ if not trimmed or trimmed[0] not in {"[", "{", '"'}:+ return parsed+ try:+ parsed = json.loads(trimmed)+ except json.JSONDecodeError:+ return parsed+ return parsed+++def truncate_text(value: object, verbosity: str) -> object:+ if verbosity == "raw" or not isinstance(value, str) or len(value) <= MAX_NORMALIZED_TEXT_CHARS:+ return value+ suffix = f"… [truncated from {len(value)} chars]"+ return f"{value[: MAX_NORMALIZED_TEXT_CHARS - len(suffix)]}{suffix}"+++def as_record(value: object) -> dict[str, object] | None:+ return cast(dict[str, object], value) if isinstance(value, dict) else None+++def strip_non_raw_fields(record: dict[str, object]) -> dict[str, object]:+ return {key: value for key, value in record.items() if key not in {"junk_drawer", "raw_id"}}+++def normalize_frame(frame: object, verbosity: str, only_app_frames: bool) -> dict[str, object] | None:+ frame_record = as_record(parse_jsonish(frame))+ if frame_record is None:+ return None+ if only_app_frames and frame_record.get("in_app") is not True:+ return None+ base_frame = frame_record if verbosity == "raw" else strip_non_raw_fields(frame_record)+ normalized = {+ **base_frame,+ "mangled_name": frame_record.get("mangled_name") or frame_record.get("function") or frame_record.get("name"),+ "source": frame_record.get("source") or frame_record.get("filename") or frame_record.get("abs_path"),+ "line": frame_record.get("line") or frame_record.get("lineno"),+ "column": frame_record.get("column") or frame_record.get("colno"),+ }+ return compact_dict(normalized)+++def normalize_stacktrace(stacktrace: object, verbosity: str, only_app_frames: bool) -> dict[str, object] | None:+ stacktrace_record = as_record(parse_jsonish(stacktrace))+ if stacktrace_record is None:+ return None+ raw_frames = stacktrace_record.get("frames")+ frames = (+ [+ normalized+ for frame in cast(list[object], raw_frames)+ if (normalized := normalize_frame(frame, verbosity, only_app_frames)) is not None+ ]+ if isinstance(raw_frames, list)+ else None+ )+ base_stacktrace = stacktrace_record if verbosity == "raw" else strip_non_raw_fields(stacktrace_record)+ return compact_dict({**base_stacktrace, "frames": frames})+++def normalize_exception(exception: object, verbosity: str, only_app_frames: bool) -> dict[str, object] | None:+ exception_record = as_record(parse_jsonish(exception))+ if exception_record is None:+ return None+ summary = compact_dict(+ {+ "type": exception_record.get("type") or exception_record.get("exception_type"),+ "value": truncate_text(+ exception_record.get("value")+ or exception_record.get("message")+ or exception_record.get("exception_message"),+ verbosity,+ ),+ "module": exception_record.get("module"),+ "mechanism": exception_record.get("mechanism"),+ }+ )+ if verbosity == "summary":+ return summary+ stacktrace = normalize_stacktrace(exception_record.get("stacktrace"), verbosity, only_app_frames)+ if verbosity == "raw":+ return compact_dict({**exception_record, "stacktrace": stacktrace})+ return compact_dict({**summary, "stacktrace": stacktrace})+++def normalize_exception_list(value: object, verbosity: str, only_app_frames: bool) -> object:+ parsed = parse_jsonish(value)+ record = as_record(parsed)+ exceptions = parsed if isinstance(parsed, list) else record.get("values") if record else None+ if not isinstance(exceptions, list):+ return parsed+ return [+ normalized+ for exception in exceptions+ if (normalized := normalize_exception(exception, verbosity, only_app_frames)) is not None+ ]+++def normalize_string_array(value: object, verbosity: str = "summary", truncate_items: bool = False) -> object:+ parsed = parse_jsonish(value)+ if not isinstance(parsed, list):+ return parsed+ return [truncate_text(item, verbosity) for item in parsed] if truncate_items else parsed+++def normalize_error_property(name: str, value: object, verbosity: str, only_app_frames: bool) -> object:+ if name == "$exception_list":+ return normalize_exception_list(value, verbosity, only_app_frames)+ if name == "$exception_releases":+ return parse_jsonish(value)+ if name == "$exception_types":+ return normalize_string_array(value)+ if name == "$exception_values":+ return normalize_string_array(value, verbosity, True)+ return value+++def property_name(select: str) -> str | None:+ if select.startswith("properties."):+ return select.removeprefix("properties.")+ return select if select in PROPERTY_COLUMN_NAMES else None+++def map_event_row(row: object, columns: list[str], verbosity: str, only_app_frames: bool) -> dict[str, object]:+ if isinstance(row, list):+ values = row+ else:+ record = as_record(row)+ values = [record.get(column) if record else None for column in columns]+ event: dict[str, object] = {"properties": {}}+ properties = cast(dict[str, object], event["properties"])+ for index, column in enumerate(columns):+ value = values[index] if isinstance(values, list) and index < len(values) else None+ if value is None:+ continue+ prop = property_name(column)+ if prop:+ properties[prop] = normalize_error_property(prop, value, verbosity, only_app_frames)+ else:+ event[column] = value+ return event+++def map_context_event_properties(data: dict[str, object]) -> dict[str, object]:+ rows = data.get("results")+ row = rows[0] if isinstance(rows, list) and rows else None+ if row is None:+ return {}+ raw_columns = data.get("columns")+ columns = [str(column) for column in raw_columns] if isinstance(raw_columns, list) else CONTEXT_EVENT_SELECTS+ return cast(dict[str, object], map_event_row(row, columns, "stack", True)["properties"])+++def get_frames(exception_list: object) -> list[dict[str, object]]:+ if not isinstance(exception_list, list):+ return []+ frames: list[dict[str, object]] = []+ for exception in exception_list:+ exception_record = as_record(exception)+ if exception_record is None:+ continue+ stacktrace = as_record(exception_record.get("stacktrace"))+ exception_frames = stacktrace.get("frames") if stacktrace else None+ if isinstance(exception_frames, list):+ frames.extend(frame for frame in exception_frames if isinstance(frame, dict))+ return frames+++def get_frame_value(frame: dict[str, object], keys: list[str]) -> object:+ for key in keys:+ value = frame.get(key)+ if value is not None and value != "":+ return value+ return None+++def build_top_in_app_frame(issue: dict[str, object], event_properties: dict[str, object]) -> dict[str, object]:+ top_frame = next(+ (+ frame+ for frame in reversed(get_frames(event_properties.get("$exception_list")))+ if frame.get("in_app") is True+ ),+ None,+ )+ if top_frame is None:+ return {}+ frame_function = get_frame_value(top_frame, ["function", "mangled_name", "name"])+ fallback_function = issue.get("function") if isinstance(issue.get("function"), str) else None+ function = frame_function if isinstance(frame_function, str) and frame_function != "?" else fallback_function+ frame_source = get_frame_value(top_frame, ["source", "filename", "abs_path", "module"])+ fallback_source = issue.get("source") if isinstance(issue.get("source"), str) else None+ return compact_dict(+ {+ "function": function,+ "source": frame_source or fallback_source,+ "line": get_frame_value(top_frame, ["line", "lineno"]),+ "column": get_frame_value(top_frame, ["column", "colno"]),+ "in_app": True,+ }+ )+++def extract_latest_release(event_properties: dict[str, object]) -> dict[str, object]:+ releases = event_properties.get("$exception_releases")+ release_values = (+ releases if isinstance(releases, list) else list(releases.values()) if isinstance(releases, dict) else []+ )+ records = [record for value in release_values if (record := as_record(value)) is not None]+ records.sort(key=lambda record: str(record.get("timestamp") or record.get("created_at") or ""), reverse=True)+ release = records[0] if records else None+ if release is None:+ return {}+ metadata = as_record(release.get("metadata"))+ git = as_record(metadata.get("git") if metadata else None)+ return compact_dict(+ {+ "version": release.get("version"),+ "project": release.get("project"),+ "timestamp": release.get("timestamp") or release.get("created_at"),+ "commit_id": git.get("commit_id") if git else None,+ "branch": git.get("branch") if git else None,+ "repo_name": git.get("repo_name") if git else None,+ }+ )+++def build_impact(issue: dict[str, object]) -> dict[str, object]:+ aggregations = as_record(issue.get("aggregations")) or {}+ return compact_dict(+ {+ "occurrences": to_number(aggregations.get("occurrences")),+ "users": to_number(aggregations.get("users")),+ "sessions": to_number(aggregations.get("sessions")),+ }+ )+++def build_sparkline(issue: dict[str, object]) -> list[float] | None:+ aggregations = as_record(issue.get("aggregations")) or {}+ volume_range = aggregations.get("volumeRange")+ if isinstance(volume_range, list):+ numeric_values: list[float] = []+ for value in volume_range:+ numeric_value = to_number(value)+ if numeric_value is None:+ return None+ numeric_values.append(numeric_value)+ return numeric_values+ volume_buckets = aggregations.get("volume_buckets")+ if isinstance(volume_buckets, list):+ numeric_values = []+ for bucket in volume_buckets:+ record = as_record(bucket)+ if record is None:+ continue+ value = to_number(record.get("value"))+ if value is not None:+ numeric_values.append(value)+ return numeric_values or None+ return None+++def build_issue_where(issue_id: str) -> list[str]:+ escaped_issue_id = escape_hogql_string(issue_id)+ return [f"(issue_id = {escaped_issue_id} OR properties.$exception_issue_id = {escaped_issue_id})"]+++def build_event_where(issue_id: str, search_query: str | None) -> list[str]:+ where = build_issue_where(issue_id)+ if search_query:+ search = escape_hogql_like_pattern(search_query)+ chunks = [f"ilike(toString({prop}), {search})" for prop in EVENT_SEARCH_PROPERTIES]+ where.append(f"({' OR '.join(chunks)})")+ return wherediff --git a/products/error_tracking/backend/api/test/test_query_api.py b/products/error_tracking/backend/api/test/test_query_api.pynew file mode 100644index 000000000000..d09ba25fa23a--- /dev/null+++ b/products/error_tracking/backend/api/test/test_query_api.py@@ -0,0 +1,435 @@+from __future__ import annotations++from freezegun import freeze_time+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events+from unittest.mock import patch++from django.utils.timezone import now++from dateutil.relativedelta import relativedelta++from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags++from products.error_tracking.backend.api.query_utils import (+ build_event_where,+ build_issue_filters,+ build_search_query,+ build_sparkline,+)+from products.error_tracking.backend.models import (+ ErrorTrackingIssue,+ ErrorTrackingIssueAssignment,+ ErrorTrackingIssueFingerprintV2,+)+++class FakeQueryResponse:+ def __init__(self, data: dict[str, object]) -> None:+ self.data = data++ def model_dump(self, *, mode: str = "json") -> dict[str, object]:+ return self.data+++def test_issue_event_search_escapes_like_wildcards_and_quotes() -> None:+ where = build_event_where("issue-id", r"a%_'\\")[1]++ assert r"\%" in where+ assert r"\_" in where+ assert r"\'" in where+ assert r"\\" in where+++def test_search_query_preserves_quotes() -> None:+ assert build_search_query({"searchQuery": "can't read property"}) == "can't read property"+ assert build_search_query({"searchQuery": '"cannot read"', "filePath": "src/app.ts"}) == '"cannot read" src/app.ts'+++def test_release_filter_adds_substring_prefilter() -> None:+ filters = build_issue_filters({"release": "2026.04.24"})++ assert filters[0] == {+ "type": "hogql",+ "key": "position(toString(properties.$exception_releases), '2026.04.24') > 0",+ }+ assert "JSONExtractKeysAndValuesRaw" in str(filters[1]["key"])+++def test_build_sparkline_accepts_float_values() -> None:+ assert build_sparkline({"aggregations": {"volumeRange": [1.0, 2.5]}}) == [1.0, 2.5]+++class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):+ issue_id = "01936e7f-d7ff-7314-b2d4-7627981e34f0"+ fingerprint = "issue-fingerprint"++ @classmethod+ def setUpClass(cls) -> None:+ from ee.clickhouse.materialized_columns.columns import get_materialized_columns, materialize++ if ("$exception_issue_id", "properties") not in get_materialized_columns("events"):+ materialize("events", "$exception_issue_id", is_nullable=True)+ super().setUpClass()++ def setUp(self) -> None:+ super().setUp()+ _create_person(team=self.team, distinct_ids=["user-1"], is_identified=True)+ flush_persons_and_events()++ def create_issue(self, issue_id: str | None = None, fingerprint: str | None = None) -> ErrorTrackingIssue:+ issue = ErrorTrackingIssue.objects.create(id=issue_id or self.issue_id, team=self.team, name="TypeError")+ ErrorTrackingIssueFingerprintV2.objects.create(+ team=self.team, issue=issue, fingerprint=fingerprint or self.fingerprint+ )+ return issue++ def create_exception_event(+ self,+ *,+ issue_id: str | None = None,+ fingerprint: str | None = None,+ properties: dict[str, object] | None = None,+ ) -> None:+ resolved_issue_id = issue_id or self.issue_id+ resolved_fingerprint = fingerprint or self.fingerprint+ _create_event(+ distinct_id="user-1",+ event="$exception",+ team=self.team,+ properties={+ "$exception_issue_id": resolved_issue_id,+ "$exception_fingerprint": resolved_fingerprint,+ "$exception_types": ["TypeError"],+ "$exception_values": ["Cannot read properties of undefined"],+ **(properties or {}),+ },+ timestamp=now() - relativedelta(hours=1),+ )++ @freeze_time("2026-04-24T12:00:00Z")+ def test_issues_list_accepts_typed_filters_and_matches_release_precisely(self) -> None:+ self.create_issue()+ self.create_exception_event(+ properties={+ "$lib": "posthog-js",+ "$browser": "Chrome",+ "$current_url": "https://example.test/checkout",+ "$exception_releases": {+ "release-id-1": {+ "version": "2026.04.24",+ "project": "posthog-js",+ "timestamp": "2026-04-24T10:00:00Z",+ "metadata": {"git": {"commit_id": "commit-123", "branch": "main"}},+ }+ },+ }+ )+ flush_persons_and_events()++ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issues",+ data={+ "status": "all",+ "dateRange": {"date_from": "-1d", "date_to": "2026-04-25T00:00:00Z"},+ "library": "posthog-js",+ "release": "2026.04.24",+ "fingerprint": self.fingerprint,+ "url": "/checkout",+ "filterGroup": [{"key": "$browser", "type": "event", "operator": "exact", "value": ["Chrome"]}],+ },+ format="json",+ )++ assert response.status_code == 200+ assert [row["id"] for row in response.json()["results"]] == [self.issue_id]++ project_response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issues",+ data={+ "status": "all",+ "dateRange": {"date_from": "-1d", "date_to": "2026-04-25T00:00:00Z"},+ "release": "posthog-js",+ },+ format="json",+ )++ assert project_response.status_code == 200+ assert project_response.json()["results"] == []++ def test_rejects_hogql_property_filters(self) -> None:+ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issues",+ data={"filterGroup": [{"key": "1 = 1", "type": "hogql", "value": "1"}]},+ format="json",+ )++ assert response.status_code == 400+ assert "HogQL property filters are not supported here" in str(response.json())++ def test_rejects_invalid_person_id(self) -> None:+ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issues",+ data={"personId": "not-a-uuid"},+ format="json",+ )++ assert response.status_code == 400++ def test_rejects_large_volume_resolution(self) -> None:+ list_response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issues",+ data={"volumeResolution": 201},+ format="json",+ )+ detail_response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issue",+ data={"issueId": self.issue_id, "volumeResolution": 201},+ format="json",+ )++ assert list_response.status_code == 400+ assert detail_response.status_code == 400++ @freeze_time("2026-04-24T12:00:00Z")+ def test_issues_list_filters_by_assignee(self) -> None:+ self.create_issue()+ self.create_exception_event()+ ErrorTrackingIssueAssignment.objects.create(issue_id=self.issue_id, user=self.user, team=self.team)+ flush_persons_and_events()++ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issues",+ data={+ "status": "all",+ "dateRange": {"date_from": "-1d", "date_to": "2026-04-25T00:00:00Z"},+ "assignee": {"type": "user", "id": self.user.pk},+ },+ format="json",+ )++ assert response.status_code == 200+ assert [row["id"] for row in response.json()["results"]] == [self.issue_id]++ def test_issues_list_tags_clickhouse_queries(self) -> None:+ observed_tags: list[tuple[object, object]] = []++ def calculate(_runner: object) -> FakeQueryResponse:+ tags = get_query_tags()+ observed_tags.append((tags.product, tags.feature))+ return FakeQueryResponse({"results": [], "hasMore": False, "limit": 25, "offset": 0})++ with patch("products.error_tracking.backend.api.query.ErrorTrackingQueryRunner.calculate", calculate):+ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issues",+ data={"limit": 1},+ format="json",+ )++ assert response.status_code == 200+ assert observed_tags == [(Product.ERROR_TRACKING, Feature.QUERY)]++ def test_issue_detail_tags_clickhouse_queries(self) -> None:+ self.create_issue()+ observed_tags: list[tuple[object, object]] = []++ def calculate_issue(_runner: object) -> FakeQueryResponse:+ tags = get_query_tags()+ observed_tags.append((tags.product, tags.feature))+ return FakeQueryResponse(+ {+ "results": [+ {"id": self.issue_id, "name": "TypeError", "description": "Cannot read", "status": "active"}+ ]+ }+ )++ def calculate_event(_runner: object) -> FakeQueryResponse:+ tags = get_query_tags()+ observed_tags.append((tags.product, tags.feature))+ return FakeQueryResponse({"columns": [], "results": []})++ with (+ patch("products.error_tracking.backend.api.query.ErrorTrackingQueryRunner.calculate", calculate_issue),+ patch("products.error_tracking.backend.api.query.EventsQueryRunner.calculate", calculate_event),+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issue",+ data={"issueId": self.issue_id},+ format="json",+ )++ assert response.status_code == 200+ assert observed_tags == [(Product.ERROR_TRACKING, Feature.QUERY), (Product.ERROR_TRACKING, Feature.QUERY)]++ @freeze_time("2026-04-24T12:00:00Z")+ def test_issue_detail_returns_impact_top_frame_and_latest_release(self) -> None:+ self.create_issue()+ self.create_exception_event(+ properties={+ "$exception_list": [+ {+ "type": "TypeError",+ "value": "Cannot read properties of undefined",+ "stacktrace": {+ "frames": [+ {+ "function": "vendorLoad",+ "filename": "https://cdn.example.test/vendor.js",+ "lineno": 12,+ "colno": 3,+ "in_app": False,+ },+ {+ "function": "loadIssue",+ "filename": "https://example.test/app.js",+ "lineno": 42,+ "colno": 9,+ "in_app": True,+ },+ ]+ },+ }+ ],+ "$exception_releases": {+ "release-id-1": {+ "version": "2026.04.24",+ "project": "posthog-js",+ "timestamp": "2026-04-24T10:00:00Z",+ "metadata": {"git": {"commit_id": "commit-123", "branch": "main"}},+ }+ },+ }+ )+ flush_persons_and_events()++ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issue",+ data={"issueId": self.issue_id, "dateRange": {"date_from": "-1d", "date_to": "2026-04-25T00:00:00Z"}},+ format="json",+ )++ assert response.status_code == 200+ data = response.json()+ assert data["id"] == self.issue_id+ assert data["impact"] == {"occurrences": 1, "users": 1, "sessions": 0}+ assert data["top_in_app_frame"] == {+ "function": "loadIssue",+ "source": "https://example.test/app.js",+ "line": 42,+ "column": 9,+ "in_app": True,+ }+ assert data["latest_release"]["version"] == "2026.04.24"+ assert data["latest_release"]["commit_id"] == "commit-123"++ @freeze_time("2026-04-24T12:00:00Z")+ def test_issue_detail_returns_without_context_when_context_query_fails(self) -> None:+ self.create_issue()+ self.create_exception_event()+ flush_persons_and_events()++ with patch("products.error_tracking.backend.api.query.EventsQueryRunner") as events_query_runner:+ events_query_runner.side_effect = RuntimeError("boom")+ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issue",+ data={"issueId": self.issue_id, "dateRange": {"date_from": "-1d", "date_to": "2026-04-25T00:00:00Z"}},+ format="json",+ )++ assert response.status_code == 200+ assert response.json()["id"] == self.issue_id+ assert "top_in_app_frame" not in response.json()++ @freeze_time("2026-04-24T12:00:00Z")+ def test_issue_detail_distinguishes_missing_issue_from_empty_date_range(self) -> None:+ self.create_issue()++ empty_range_response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issue",+ data={+ "issueId": self.issue_id,+ "dateRange": {"date_from": "2026-04-23T00:00:00Z", "date_to": "2026-04-23T01:00:00Z"},+ },+ format="json",+ )+ missing_response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issue",+ data={"issueId": "00000000-0000-0000-0000-000000000000"},+ format="json",+ )++ assert empty_range_response.status_code == 200+ assert empty_range_response.json()["impact"] == {}+ assert missing_response.status_code == 404++ def test_issue_events_returns_404_for_foreign_issue(self) -> None:+ other_team = self.create_team_with_organization(organization=self.organization)+ other_issue = ErrorTrackingIssue.objects.create(+ id="01936e80-7e11-7fd1-b0d1-f6f90c9b42bb", team=other_team, name="Other team issue"+ )++ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issue_events",+ data={"issueId": str(other_issue.id)},+ format="json",+ )++ assert response.status_code == 404++ def test_issue_events_tags_clickhouse_queries(self) -> None:+ self.create_issue()+ observed_tags: list[tuple[object, object]] = []++ def calculate(_runner: object) -> FakeQueryResponse:+ tags = get_query_tags()+ observed_tags.append((tags.product, tags.feature))+ return FakeQueryResponse({"columns": [], "results": [], "hasMore": False, "limit": 1, "offset": 0})++ with patch("products.error_tracking.backend.api.query.EventsQueryRunner.calculate", calculate):+ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issue_events",+ data={"issueId": self.issue_id},+ format="json",+ )++ assert response.status_code == 200+ assert observed_tags == [(Product.ERROR_TRACKING, Feature.QUERY)]++ @freeze_time("2026-04-24T12:00:00Z")+ def test_issue_events_returns_plural_exception_arrays_and_truncates_summary_text(self) -> None:+ long_text = "x" * 1200+ self.create_issue()+ self.create_exception_event(+ properties={+ "$session_id": "session-id-1",+ "$exception_values": [long_text],+ "$exception_list": [{"type": "TypeError", "value": long_text, "stacktrace": {"frames": []}}],+ }+ )+ flush_persons_and_events()++ summary_response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issue_events",+ data={"issueId": self.issue_id, "dateRange": {"date_from": "-1d", "date_to": "2026-04-25T00:00:00Z"}},+ format="json",+ )+ raw_response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issue_events",+ data={+ "issueId": self.issue_id,+ "dateRange": {"date_from": "-1d", "date_to": "2026-04-25T00:00:00Z"},+ "verbosity": "raw",+ },+ format="json",+ )++ assert summary_response.status_code == 200+ assert raw_response.status_code == 200+ summary_event = summary_response.json()["results"][0]+ raw_event = raw_response.json()["results"][0]+ assert summary_event["properties"]["$exception_types"] == ["TypeError"]+ assert "[truncated from 1200 chars]" in summary_event["properties"]["$exception_values"][0]+ assert "[truncated from 1200 chars]" in summary_event["properties"]["$exception_list"][0]["value"]+ assert raw_event["properties"]["$exception_values"][0] == long_text+ assert raw_event["properties"]["$exception_list"][0]["value"] == long_text+ assert summary_event["properties"]["$session_id"] == "session-id-1"diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.tsindex d6d70ba7dc1c..273270ffbcf7 100644--- a/products/error_tracking/frontend/generated/api.schemas.ts+++ b/products/error_tracking/frontend/generated/api.schemas.ts@@ -803,6 +803,554 @@ export interface ErrorTrackingIssueSplitResponseApi {new_issue_ids: string[]}+export interface ErrorTrackingDateRangeApi {+ /** Start of the date range as an ISO timestamp or relative date such as -7d. Defaults to -7d. */+ date_from?: string+ /**+ * End of the date range as an ISO timestamp or relative date. Defaults to now when omitted.+ * @nullable+ */+ date_to?: string | null+}++export interface ErrorTrackingIssueQueryRequestApi {+ /** Error tracking issue ID. */+ issueId: string+ /** Date range for issue impact and latest-event metadata. Defaults to the last 7 days. */+ dateRange?: ErrorTrackingDateRangeApi+ /** When true, exclude internal/test account data from results. Defaults to true. */+ filterTestAccounts?: boolean+ /**+ * Volume buckets. Maximum 200.+ * @minimum 0+ * @maximum 200+ */+ volumeResolution?: number+ /** Set true to include a compact numeric occurrence sparkline. Defaults to false. */+ includeSparkline?: boolean+}++export interface ErrorTrackingAssigneeResponseApi {+ /** Assignee user ID or role UUID. */+ id?: string | number | null+ /**+ * Assignee type.+ * @nullable+ */+ type?: string | null+}++export interface ErrorTrackingVolumeBucketApi {+ /** Bucket timestamp label. */+ label: string+ /**+ * Occurrence count for the bucket.+ * @nullable+ */+ value?: number | null+}++export interface ErrorTrackingAggregationsApi {+ /** Exception occurrence count. */+ occurrences?: number+ /** Unique user count. */+ users?: number+ /** Unique session count. */+ sessions?: number+ /** Occurrence counts per volume bucket. */+ volumeRange?: number[]+ /** Labeled volume buckets. */+ volume_buckets?: ErrorTrackingVolumeBucketApi[]+}++export interface ErrorTrackingTopFrameApi {+ /** Frame function name. */+ function?: string+ /** Frame source, filename, or module. */+ source?: string+ /** Line number. */+ line?: number+ /** Column number. */+ column?: number+ /** Whether the frame is an application frame. */+ in_app?: boolean+}++export interface ErrorTrackingLatestReleaseApi {+ /** Release version. */+ version?: string+ /** Release project/library. */+ project?: string+ /** Release timestamp. */+ timestamp?: string+ /** Git commit ID. */+ commit_id?: string+ /** Git branch. */+ branch?: string+ /** Git repository name. */+ repo_name?: string+}++export interface ErrorTrackingImpactApi {+ /** Exception occurrence count. */+ occurrences?: number+ /** Unique user count. */+ users?: number+ /** Unique session count. */+ sessions?: number+}++export interface ErrorTrackingIssueDetailApi {+ /** Error tracking issue ID. */+ id: string+ /**+ * Issue name.+ * @nullable+ */+ name?: string | null+ /**+ * Issue description.+ * @nullable+ */+ description?: string | null+ /** Issue status. */+ status?: string+ /**+ * First seen timestamp.+ * @nullable+ */+ first_seen?: string | null+ /**+ * Last seen timestamp.+ * @nullable+ */+ last_seen?: string | null+ /**+ * SDK/library associated with the issue.+ * @nullable+ */+ library?: string | null+ /**+ * Top source/file associated with the issue.+ * @nullable+ */+ source?: string | null+ /** Issue assignee. */+ assignee?: ErrorTrackingAssigneeResponseApi | null+ /** Aggregate counts. */+ aggregations?: ErrorTrackingAggregationsApi | null+ /**+ * Top function associated with the issue.+ * @nullable+ */+ function?: string | null+ /** Top in_app application frame. */+ top_in_app_frame?: ErrorTrackingTopFrameApi+ /** Latest release metadata. */+ latest_release?: ErrorTrackingLatestReleaseApi+ /** Compact impact counts. */+ impact?: ErrorTrackingImpactApi+ /** Optional compact occurrence sparkline. */+ sparkline?: number[]+}++/**+ * * `exact` - exact+ * `is_not` - is_not+ * `icontains` - icontains+ * `not_icontains` - not_icontains+ * `regex` - regex+ * `not_regex` - not_regex+ * `gt` - gt+ * `lt` - lt+ * `gte` - gte+ * `lte` - lte+ * `is_set` - is_set+ * `is_not_set` - is_not_set+ * `is_date_exact` - is_date_exact+ * `is_date_after` - is_date_after+ * `is_date_before` - is_date_before+ * `in` - in+ * `not_in` - not_in+ */+export type PropertyItemOperatorEnumApi = (typeof PropertyItemOperatorEnumApi)[keyof typeof PropertyItemOperatorEnumApi]++export const PropertyItemOperatorEnumApi = {+ Exact: 'exact',+ IsNot: 'is_not',+ Icontains: 'icontains',+ NotIcontains: 'not_icontains',+ Regex: 'regex',+ NotRegex: 'not_regex',+ Gt: 'gt',+ Lt: 'lt',+ Gte: 'gte',+ Lte: 'lte',+ IsSet: 'is_set',+ IsNotSet: 'is_not_set',+ IsDateExact: 'is_date_exact',+ IsDateAfter: 'is_date_after',+ IsDateBefore: 'is_date_before',+ In: 'in',+ NotIn: 'not_in',+} as const++export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]++export const BlankEnumApi = {+ '': '',+} as const++export type NullEnumApi = (typeof NullEnumApi)[keyof typeof NullEnumApi]++export const NullEnumApi = {} as const++/**+ * * `event` - event+ * `event_metadata` - event_metadata+ * `feature` - feature+ * `person` - person+ * `cohort` - cohort+ * `element` - element+ * `static-cohort` - static-cohort+ * `dynamic-cohort` - dynamic-cohort+ * `precalculated-cohort` - precalculated-cohort+ * `group` - group+ * `recording` - recording+ * `log_entry` - log_entry+ * `behavioral` - behavioral+ * `session` - session+ * `hogql` - hogql+ * `data_warehouse` - data_warehouse+ * `data_warehouse_person_property` - data_warehouse_person_property+ * `error_tracking_issue` - error_tracking_issue+ * `log` - log+ * `log_attribute` - log_attribute+ * `log_resource_attribute` - log_resource_attribute+ * `span` - span+ * `span_attribute` - span_attribute+ * `span_resource_attribute` - span_resource_attribute+ * `revenue_analytics` - revenue_analytics+ * `flag` - flag+ * `workflow_variable` - workflow_variable+ */+export type PropertyFilterTypeEnumApi = (typeof PropertyFilterTypeEnumApi)[keyof typeof PropertyFilterTypeEnumApi]++export const PropertyFilterTypeEnumApi = {+ Event: 'event',+ EventMetadata: 'event_metadata',+ Feature: 'feature',+ Person: 'person',+ Cohort: 'cohort',+ Element: 'element',+ StaticCohort: 'static-cohort',+ DynamicCohort: 'dynamic-cohort',+ PrecalculatedCohort: 'precalculated-cohort',+ Group: 'group',+ Recording: 'recording',+ LogEntry: 'log_entry',+ Behavioral: 'behavioral',+ Session: 'session',+ Hogql: 'hogql',+ DataWarehouse: 'data_warehouse',+ DataWarehousePersonProperty: 'data_warehouse_person_property',+ ErrorTrackingIssue: 'error_tracking_issue',+ Log: 'log',+ LogAttribute: 'log_attribute',+ LogResourceAttribute: 'log_resource_attribute',+ Span: 'span',+ SpanAttribute: 'span_attribute',+ SpanResourceAttribute: 'span_resource_attribute',+ RevenueAnalytics: 'revenue_analytics',+ Flag: 'flag',+ WorkflowVariable: 'workflow_variable',+} as const++export interface PropertyItemApi {+ /** Key of the property you're filtering on. For example `email` or `$current_url` */+ key: string+ /** Value of your filter. For example `[email protected]` or `https://example.com/test/`. Can be an array for an OR query, like `["[email protected]","[email protected]"]` */+ value: string | number | boolean | (string | number)[]+ operator?: PropertyItemOperatorEnumApi | BlankEnumApi | NullEnumApi | null+ type?: PropertyFilterTypeEnumApi | BlankEnumApi+}++/**+ * * `ASC` - ASC+ * `DESC` - DESC+ */+export type OrderDirectionEnumApi = (typeof OrderDirectionEnumApi)[keyof typeof OrderDirectionEnumApi]++export const OrderDirectionEnumApi = {+ Asc: 'ASC',+ Desc: 'DESC',+} as const++/**+ * * `summary` - summary+ * `stack` - stack+ * `raw` - raw+ */+export type VerbosityEnumApi = (typeof VerbosityEnumApi)[keyof typeof VerbosityEnumApi]++export const VerbosityEnumApi = {+ Summary: 'summary',+ Stack: 'stack',+ Raw: 'raw',+} as const++export interface ErrorTrackingIssueEventsQueryRequestApi {+ /** Error tracking issue ID. */+ issueId: string+ /** Date range for sampled exception events. Defaults to the last 7 days. */+ dateRange?: ErrorTrackingDateRangeApi+ /** When true, exclude internal/test account data from results. Defaults to true. */+ filterTestAccounts?: boolean+ /** Advanced flat AND property filters applied to sampled events. HogQL filters are rejected. */+ filterGroup?: PropertyItemApi[]+ /**+ * Search exception types, exception values, and current URL among sampled events.+ * @maxLength 500+ */+ searchQuery?: string+ /** Timestamp sort direction. Defaults to DESC.++* `ASC` - ASC+* `DESC` - DESC */+ orderDirection?: OrderDirectionEnumApi+ /**+ * Page size.+ * @minimum 1+ * @maximum 20+ */+ limit?: number+ /**+ * Pagination offset.+ * @minimum 0+ */+ offset?: number+ /** Controls exception detail size: summary, stack, or raw. Defaults to summary.++* `summary` - summary+* `stack` - stack+* `raw` - raw */+ verbosity?: VerbosityEnumApi+ /** When true, include only stack frames marked in_app. Defaults to true. */+ onlyAppFrames?: boolean+}++/**+ * Normalized sampled exception event properties.+ */+export type ErrorTrackingEventApiProperties = { [key: string]: unknown }++export interface ErrorTrackingEventApi {+ /** Event UUID. */+ uuid?: string+ /** Event distinct ID. */+ distinct_id?: string+ /** Event timestamp. */+ timestamp?: string+ /** Normalized sampled exception event properties. */+ properties?: ErrorTrackingEventApiProperties+}++export interface ErrorTrackingIssueEventsResponseApi {+ /** Sampled exception events. */+ results: ErrorTrackingEventApi[]+ /** Whether more results are available. */+ hasMore: boolean+ /** Page size. */+ limit: number+ /** Current offset. */+ offset: number+ /** Offset to fetch the next page when hasMore is true. */+ nextOffset?: number+}++/**+ * * `archived` - archived+ * `active` - active+ * `resolved` - resolved+ * `pending_release` - pending_release+ * `suppressed` - suppressed+ * `all` - all+ */+export type ErrorTrackingIssuesListQueryRequestStatusEnumApi =+ (typeof ErrorTrackingIssuesListQueryRequestStatusEnumApi)[keyof typeof ErrorTrackingIssuesListQueryRequestStatusEnumApi]++export const ErrorTrackingIssuesListQueryRequestStatusEnumApi = {+ Archived: 'archived',+ Active: 'active',+ Resolved: 'resolved',+ PendingRelease: 'pending_release',+ Suppressed: 'suppressed',+ All: 'all',+} as const++export interface ErrorTrackingAssigneeApi {+ /** User ID or role UUID to filter by. */+ id: string | number+ /** Assignee target type: user or role.++* `user` - user+* `role` - role */+ type: AssigneeTypeEnumApi+}++/**+ * * `last_seen` - last_seen+ * `first_seen` - first_seen+ * `occurrences` - occurrences+ * `users` - users+ * `sessions` - sessions+ */+export type ErrorTrackingIssueOrderByEnumApi =+ (typeof ErrorTrackingIssueOrderByEnumApi)[keyof typeof ErrorTrackingIssueOrderByEnumApi]++export const ErrorTrackingIssueOrderByEnumApi = {+ LastSeen: 'last_seen',+ FirstSeen: 'first_seen',+ Occurrences: 'occurrences',+ Users: 'users',+ Sessions: 'sessions',+} as const++export interface ErrorTrackingIssuesListQueryRequestApi {+ /** Date range for issue aggregates. Defaults to the last 7 days. */+ dateRange?: ErrorTrackingDateRangeApi+ /** Filter by issue status. Defaults to active.++* `archived` - archived+* `active` - active+* `resolved` - resolved+* `pending_release` - pending_release+* `suppressed` - suppressed+* `all` - all */+ status?: ErrorTrackingIssuesListQueryRequestStatusEnumApi+ /** Filter by issue assignee. Omit to include all assignees. */+ assignee?: ErrorTrackingAssigneeApi | null+ /** When true, exclude internal/test account data from results. Defaults to true. */+ filterTestAccounts?: boolean+ /**+ * Free-text search across exception types, values, stack frames, and email fields.+ * @maxLength 500+ */+ searchQuery?: string+ /** Advanced flat AND property filters. Prefer typed shortcut fields when they fit. HogQL filters are rejected. */+ filterGroup?: PropertyItemApi[]+ /** Field used to sort issues. Defaults to occurrences.++* `last_seen` - last_seen+* `first_seen` - first_seen+* `occurrences` - occurrences+* `users` - users+* `sessions` - sessions */+ orderBy?: ErrorTrackingIssueOrderByEnumApi+ /** Sort direction. Defaults to DESC.++* `ASC` - ASC+* `DESC` - DESC */+ orderDirection?: OrderDirectionEnumApi+ /**+ * Page size.+ * @minimum 1+ * @maximum 100+ */+ limit?: number+ /**+ * Pagination offset.+ * @minimum 0+ */+ offset?: number+ /**+ * Number of volume buckets. Defaults to 0 for compact aggregate counts.+ * @minimum 0+ * @maximum 200+ */+ volumeResolution?: number+ /** Filter by SDK/library value from event $lib, for example posthog-js. */+ library?: string | string[]+ /**+ * Filter by exact release ID, version, or git commit ID captured in $exception_releases.+ * @maxLength 500+ */+ release?: string+ /** Filter by exact exception fingerprint hash, not fuzzy search. */+ fingerprint?: string | string[]+ /**+ * Search user/email text.+ * @maxLength 500+ */+ user?: string+ /** Filter by exact PostHog person UUID. */+ personId?: string+ /**+ * Filter by current URL substring.+ * @maxLength 1000+ */+ url?: string+ /**+ * Search stack-frame source/file path text.+ * @maxLength 1000+ */+ filePath?: string+}++export interface ErrorTrackingIssueListItemApi {+ /** Error tracking issue ID. */+ id: string+ /**+ * Issue name.+ * @nullable+ */+ name?: string | null+ /**+ * Issue description.+ * @nullable+ */+ description?: string | null+ /** Issue status. */+ status?: string+ /**+ * First seen timestamp.+ * @nullable+ */+ first_seen?: string | null+ /**+ * Last seen timestamp.+ * @nullable+ */+ last_seen?: string | null+ /**+ * SDK/library associated with the issue.+ * @nullable+ */+ library?: string | null+ /**+ * Top source/file associated with the issue.+ * @nullable+ */+ source?: string | null+ /** Issue assignee. */+ assignee?: ErrorTrackingAssigneeResponseApi | null+ /** Aggregate counts. */+ aggregations?: ErrorTrackingAggregationsApi | null+}++export interface ErrorTrackingIssuesListResponseApi {+ /** Issue rows. */+ results: ErrorTrackingIssueListItemApi[]+ /** Whether more results are available. */+ hasMore: boolean+ /** Page size. */+ limit: number+ /** Current offset. */+ offset: number+ /** Offset to fetch the next page when hasMore is true. */+ nextOffset?: number+}+export type ErrorTrackingRecommendationApiMeta = { [key: string]: unknown }export interface ErrorTrackingRecommendationApi {diff --git a/products/error_tracking/frontend/generated/api.ts b/products/error_tracking/frontend/generated/api.tsindex 900417e63e9f..e1f5beb2c5c0 100644--- a/products/error_tracking/frontend/generated/api.ts+++ b/products/error_tracking/frontend/generated/api.ts@@ -22,12 +22,18 @@ import type {ErrorTrackingGroupingRuleApi,ErrorTrackingGroupingRuleCreateRequestApi,ErrorTrackingGroupingRuleListResponseApi,+ ErrorTrackingIssueDetailApi,+ ErrorTrackingIssueEventsQueryRequestApi,+ ErrorTrackingIssueEventsResponseApi,ErrorTrackingIssueFullApi,ErrorTrackingIssueMergeRequestApi,ErrorTrackingIssueMergeResponseApi,+ ErrorTrackingIssueQueryRequestApi,ErrorTrackingIssueSplitRequestApi,ErrorTrackingIssueSplitResponseApi,ErrorTrackingIssuesListParams,+ ErrorTrackingIssuesListQueryRequestApi,+ ErrorTrackingIssuesListResponseApi,ErrorTrackingRecommendationApi,ErrorTrackingRecommendationsListParams,ErrorTrackingReleaseApi,@@ -804,6 +810,69 @@ export const errorTrackingIssuesValuesRetrieve = async (projectId: string, optio})}+/**+ * Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional sparkline.+ * @summary Get compact error tracking issue details+ */+export const getErrorTrackingQueryIssueCreateUrl = (projectId: string) => {+ return `/api/environments/${projectId}/error_tracking/query/issue/`+}++export const errorTrackingQueryIssueCreate = async (+ projectId: string,+ errorTrackingIssueQueryRequestApi: ErrorTrackingIssueQueryRequestApi,+ options?: RequestInit+): Promise<ErrorTrackingIssueDetailApi> => {+ return apiMutator<ErrorTrackingIssueDetailApi>(getErrorTrackingQueryIssueCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(errorTrackingIssueQueryRequestApi),+ })+}++/**+ * Fetch sampled exception events, stack traces, browser/SDK context, URL, and $session_id values for one issue.+ * @summary List sampled exception events for an error tracking issue+ */+export const getErrorTrackingQueryIssueEventsCreateUrl = (projectId: string) => {+ return `/api/environments/${projectId}/error_tracking/query/issue_events/`+}++export const errorTrackingQueryIssueEventsCreate = async (+ projectId: string,+ errorTrackingIssueEventsQueryRequestApi: ErrorTrackingIssueEventsQueryRequestApi,+ options?: RequestInit+): Promise<ErrorTrackingIssueEventsResponseApi> => {+ return apiMutator<ErrorTrackingIssueEventsResponseApi>(getErrorTrackingQueryIssueEventsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(errorTrackingIssueEventsQueryRequestApi),+ })+}++/**+ * List error tracking issues with typed filters and compact aggregate counts.+ * @summary List compact error tracking issues+ */+export const getErrorTrackingQueryIssuesListCreateUrl = (projectId: string) => {+ return `/api/environments/${projectId}/error_tracking/query/issues/`+}++export const errorTrackingQueryIssuesListCreate = async (+ projectId: string,+ errorTrackingIssuesListQueryRequestApi: ErrorTrackingIssuesListQueryRequestApi,+ options?: RequestInit+): Promise<ErrorTrackingIssuesListResponseApi> => {+ return apiMutator<ErrorTrackingIssuesListResponseApi>(getErrorTrackingQueryIssuesListCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(errorTrackingIssuesListQueryRequestApi),+ })+}+export const getErrorTrackingRecommendationsListUrl = (projectId: string,params?: ErrorTrackingRecommendationsListParamsdiff --git a/products/error_tracking/frontend/generated/api.zod.ts b/products/error_tracking/frontend/generated/api.zod.tsindex feabd8d3c2a3..f882cbe1b38b 100644--- a/products/error_tracking/frontend/generated/api.zod.ts+++ b/products/error_tracking/frontend/generated/api.zod.ts@@ -296,6 +296,430 @@ export const ErrorTrackingIssuesBulkCreateBody = /* @__PURE__ */ zod.object({),})+/**+ * Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional sparkline.+ * @summary Get compact error tracking issue details+ */+export const errorTrackingQueryIssueCreateBodyFilterTestAccountsDefault = true+export const errorTrackingQueryIssueCreateBodyVolumeResolutionDefault = 0+export const errorTrackingQueryIssueCreateBodyVolumeResolutionMin = 0+export const errorTrackingQueryIssueCreateBodyVolumeResolutionMax = 200++export const errorTrackingQueryIssueCreateBodyIncludeSparklineDefault = false++export const ErrorTrackingQueryIssueCreateBody = /* @__PURE__ */ zod.object({+ issueId: zod.uuid().describe('Error tracking issue ID.'),+ dateRange: zod+ .object({+ date_from: zod+ .string()+ .optional()+ .describe('Start of the date range as an ISO timestamp or relative date such as -7d. Defaults to -7d.'),+ date_to: zod+ .string()+ .nullish()+ .describe('End of the date range as an ISO timestamp or relative date. Defaults to now when omitted.'),+ })+ .optional()+ .describe('Date range for issue impact and latest-event metadata. Defaults to the last 7 days.'),+ filterTestAccounts: zod+ .boolean()+ .default(errorTrackingQueryIssueCreateBodyFilterTestAccountsDefault)+ .describe('When true, exclude internal/test account data from results. Defaults to true.'),+ volumeResolution: zod+ .number()+ .min(errorTrackingQueryIssueCreateBodyVolumeResolutionMin)+ .max(errorTrackingQueryIssueCreateBodyVolumeResolutionMax)+ .default(errorTrackingQueryIssueCreateBodyVolumeResolutionDefault)+ .describe('Volume buckets. Maximum 200.'),+ includeSparkline: zod+ .boolean()+ .default(errorTrackingQueryIssueCreateBodyIncludeSparklineDefault)+ .describe('Set true to include a compact numeric occurrence sparkline. Defaults to false.'),+})++/**+ * Fetch sampled exception events, stack traces, browser/SDK context, URL, and $session_id values for one issue.+ * @summary List sampled exception events for an error tracking issue+ */+export const errorTrackingQueryIssueEventsCreateBodyFilterTestAccountsDefault = true+export const errorTrackingQueryIssueEventsCreateBodyFilterGroupItemOperatorDefault = `exact`+export const errorTrackingQueryIssueEventsCreateBodyFilterGroupItemTypeDefault = `event`+export const errorTrackingQueryIssueEventsCreateBodySearchQueryMax = 500++export const errorTrackingQueryIssueEventsCreateBodyOrderDirectionDefault = `DESC`+export const errorTrackingQueryIssueEventsCreateBodyLimitDefault = 1+export const errorTrackingQueryIssueEventsCreateBodyLimitMax = 20++export const errorTrackingQueryIssueEventsCreateBodyOffsetDefault = 0+export const errorTrackingQueryIssueEventsCreateBodyOffsetMin = 0++export const errorTrackingQueryIssueEventsCreateBodyVerbosityDefault = `summary`+export const errorTrackingQueryIssueEventsCreateBodyOnlyAppFramesDefault = true++export const ErrorTrackingQueryIssueEventsCreateBody = /* @__PURE__ */ zod.object({+ issueId: zod.uuid().describe('Error tracking issue ID.'),+ dateRange: zod+ .object({+ date_from: zod+ .string()+ .optional()+ .describe('Start of the date range as an ISO timestamp or relative date such as -7d. Defaults to -7d.'),+ date_to: zod+ .string()+ .nullish()+ .describe('End of the date range as an ISO timestamp or relative date. Defaults to now when omitted.'),+ })+ .optional()+ .describe('Date range for sampled exception events. Defaults to the last 7 days.'),+ filterTestAccounts: zod+ .boolean()+ .default(errorTrackingQueryIssueEventsCreateBodyFilterTestAccountsDefault)+ .describe('When true, exclude internal/test account data from results. Defaults to true.'),+ filterGroup: zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe("Key of the property you're filtering on. For example `email` or `$current_url`"),+ value: zod+ .union([+ zod.string(),+ zod.number(),+ zod.boolean(),+ zod.array(zod.union([zod.string(), zod.number()])),+ ])+ .describe(+ 'Value of your filter. For example `[email protected]` or `https://example.com/test/`. Can be an array for an OR query, like `[\"[email protected]\",\"[email protected]\"]`'+ ),+ operator: zod+ .union([+ zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'regex',+ 'not_regex',+ 'gt',+ 'lt',+ 'gte',+ 'lte',+ 'is_set',+ 'is_not_set',+ 'is_date_exact',+ 'is_date_after',+ 'is_date_before',+ 'in',+ 'not_in',+ ])+ .describe(+ '* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `gte` - gte\n* `lte` - lte\n* `is_set` - is_set\n* `is_not_set` - is_not_set\n* `is_date_exact` - is_date_exact\n* `is_date_after` - is_date_after\n* `is_date_before` - is_date_before\n* `in` - in\n* `not_in` - not_in'+ ),+ zod.enum(['']),+ zod.literal(null),+ ])+ .default(errorTrackingQueryIssueEventsCreateBodyFilterGroupItemOperatorDefault),+ type: zod+ .union([+ zod+ .enum([+ 'event',+ 'event_metadata',+ 'feature',+ 'person',+ 'cohort',+ 'element',+ 'static-cohort',+ 'dynamic-cohort',+ 'precalculated-cohort',+ 'group',+ 'recording',+ 'log_entry',+ 'behavioral',+ 'session',+ 'hogql',+ 'data_warehouse',+ 'data_warehouse_person_property',+ 'error_tracking_issue',+ 'log',+ 'log_attribute',+ 'log_resource_attribute',+ 'span',+ 'span_attribute',+ 'span_resource_attribute',+ 'revenue_analytics',+ 'flag',+ 'workflow_variable',+ ])+ .describe(+ '* `event` - event\n* `event_metadata` - event_metadata\n* `feature` - feature\n* `person` - person\n* `cohort` - cohort\n* `element` - element\n* `static-cohort` - static-cohort\n* `dynamic-cohort` - dynamic-cohort\n* `precalculated-cohort` - precalculated-cohort\n* `group` - group\n* `recording` - recording\n* `log_entry` - log_entry\n* `behavioral` - behavioral\n* `session` - session\n* `hogql` - hogql\n* `data_warehouse` - data_warehouse\n* `data_warehouse_person_property` - data_warehouse_person_property\n* `error_tracking_issue` - error_tracking_issue\n* `log` - log\n* `log_attribute` - log_attribute\n* `log_resource_attribute` - log_resource_attribute\n* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute\n* `revenue_analytics` - revenue_analytics\n* `flag` - flag\n* `workflow_variable` - workflow_variable'+ ),+ zod.enum(['']),+ ])+ .default(errorTrackingQueryIssueEventsCreateBodyFilterGroupItemTypeDefault),+ })+ )+ .optional()+ .describe('Advanced flat AND property filters applied to sampled events. HogQL filters are rejected.'),+ searchQuery: zod+ .string()+ .max(errorTrackingQueryIssueEventsCreateBodySearchQueryMax)+ .optional()+ .describe('Search exception types, exception values, and current URL among sampled events.'),+ orderDirection: zod+ .enum(['ASC', 'DESC'])+ .describe('* `ASC` - ASC\n* `DESC` - DESC')+ .default(errorTrackingQueryIssueEventsCreateBodyOrderDirectionDefault)+ .describe('Timestamp sort direction. Defaults to DESC.\n\n* `ASC` - ASC\n* `DESC` - DESC'),+ limit: zod+ .number()+ .min(1)+ .max(errorTrackingQueryIssueEventsCreateBodyLimitMax)+ .default(errorTrackingQueryIssueEventsCreateBodyLimitDefault)+ .describe('Page size.'),+ offset: zod+ .number()+ .min(errorTrackingQueryIssueEventsCreateBodyOffsetMin)+ .default(errorTrackingQueryIssueEventsCreateBodyOffsetDefault)+ .describe('Pagination offset.'),+ verbosity: zod+ .enum(['summary', 'stack', 'raw'])+ .describe('* `summary` - summary\n* `stack` - stack\n* `raw` - raw')+ .default(errorTrackingQueryIssueEventsCreateBodyVerbosityDefault)+ .describe(+ 'Controls exception detail size: summary, stack, or raw. Defaults to summary.\n\n* `summary` - summary\n* `stack` - stack\n* `raw` - raw'+ ),+ onlyAppFrames: zod+ .boolean()+ .default(errorTrackingQueryIssueEventsCreateBodyOnlyAppFramesDefault)+ .describe('When true, include only stack frames marked in_app. Defaults to true.'),+})++/**+ * List error tracking issues with typed filters and compact aggregate counts.+ * @summary List compact error tracking issues+ */+export const errorTrackingQueryIssuesListCreateBodyStatusDefault = `active`+export const errorTrackingQueryIssuesListCreateBodyFilterTestAccountsDefault = true+export const errorTrackingQueryIssuesListCreateBodySearchQueryMax = 500++export const errorTrackingQueryIssuesListCreateBodyFilterGroupItemOperatorDefault = `exact`+export const errorTrackingQueryIssuesListCreateBodyFilterGroupItemTypeDefault = `event`+export const errorTrackingQueryIssuesListCreateBodyOrderByDefault = `occurrences`+export const errorTrackingQueryIssuesListCreateBodyOrderDirectionDefault = `DESC`+export const errorTrackingQueryIssuesListCreateBodyLimitDefault = 25+export const errorTrackingQueryIssuesListCreateBodyLimitMax = 100++export const errorTrackingQueryIssuesListCreateBodyOffsetDefault = 0+export const errorTrackingQueryIssuesListCreateBodyOffsetMin = 0++export const errorTrackingQueryIssuesListCreateBodyVolumeResolutionDefault = 0+export const errorTrackingQueryIssuesListCreateBodyVolumeResolutionMin = 0+export const errorTrackingQueryIssuesListCreateBodyVolumeResolutionMax = 200++export const errorTrackingQueryIssuesListCreateBodyReleaseMax = 500++export const errorTrackingQueryIssuesListCreateBodyUserMax = 500++export const errorTrackingQueryIssuesListCreateBodyUrlMax = 1000++export const errorTrackingQueryIssuesListCreateBodyFilePathMax = 1000++export const ErrorTrackingQueryIssuesListCreateBody = /* @__PURE__ */ zod.object({+ dateRange: zod+ .object({+ date_from: zod+ .string()+ .optional()+ .describe('Start of the date range as an ISO timestamp or relative date such as -7d. Defaults to -7d.'),+ date_to: zod+ .string()+ .nullish()+ .describe('End of the date range as an ISO timestamp or relative date. Defaults to now when omitted.'),+ })+ .optional()+ .describe('Date range for issue aggregates. Defaults to the last 7 days.'),+ status: zod+ .enum(['archived', 'active', 'resolved', 'pending_release', 'suppressed', 'all'])+ .describe(+ '* `archived` - archived\n* `active` - active\n* `resolved` - resolved\n* `pending_release` - pending_release\n* `suppressed` - suppressed\n* `all` - all'+ )+ .default(errorTrackingQueryIssuesListCreateBodyStatusDefault)+ .describe(+ 'Filter by issue status. Defaults to active.\n\n* `archived` - archived\n* `active` - active\n* `resolved` - resolved\n* `pending_release` - pending_release\n* `suppressed` - suppressed\n* `all` - all'+ ),+ assignee: zod+ .object({+ id: zod.union([zod.string(), zod.number()]).describe('User ID or role UUID to filter by.'),+ type: zod+ .enum(['user', 'role'])+ .describe('* `user` - user\n* `role` - role')+ .describe('Assignee target type: user or role.\n\n* `user` - user\n* `role` - role'),+ })+ .nullish()+ .describe('Filter by issue assignee. Omit to include all assignees.'),+ filterTestAccounts: zod+ .boolean()+ .default(errorTrackingQueryIssuesListCreateBodyFilterTestAccountsDefault)+ .describe('When true, exclude internal/test account data from results. Defaults to true.'),+ searchQuery: zod+ .string()+ .max(errorTrackingQueryIssuesListCreateBodySearchQueryMax)+ .optional()+ .describe('Free-text search across exception types, values, stack frames, and email fields.'),+ filterGroup: zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe("Key of the property you're filtering on. For example `email` or `$current_url`"),+ value: zod+ .union([+ zod.string(),+ zod.number(),+ zod.boolean(),+ zod.array(zod.union([zod.string(), zod.number()])),+ ])+ .describe(+ 'Value of your filter. For example `[email protected]` or `https://example.com/test/`. Can be an array for an OR query, like `[\"[email protected]\",\"[email protected]\"]`'+ ),+ operator: zod+ .union([+ zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'regex',+ 'not_regex',+ 'gt',+ 'lt',+ 'gte',+ 'lte',+ 'is_set',+ 'is_not_set',+ 'is_date_exact',+ 'is_date_after',+ 'is_date_before',+ 'in',+ 'not_in',+ ])+ .describe(+ '* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `gte` - gte\n* `lte` - lte\n* `is_set` - is_set\n* `is_not_set` - is_not_set\n* `is_date_exact` - is_date_exact\n* `is_date_after` - is_date_after\n* `is_date_before` - is_date_before\n* `in` - in\n* `not_in` - not_in'+ ),+ zod.enum(['']),+ zod.literal(null),+ ])+ .default(errorTrackingQueryIssuesListCreateBodyFilterGroupItemOperatorDefault),+ type: zod+ .union([+ zod+ .enum([+ 'event',+ 'event_metadata',+ 'feature',+ 'person',+ 'cohort',+ 'element',+ 'static-cohort',+ 'dynamic-cohort',+ 'precalculated-cohort',+ 'group',+ 'recording',+ 'log_entry',+ 'behavioral',+ 'session',+ 'hogql',+ 'data_warehouse',+ 'data_warehouse_person_property',+ 'error_tracking_issue',+ 'log',+ 'log_attribute',+ 'log_resource_attribute',+ 'span',+ 'span_attribute',+ 'span_resource_attribute',+ 'revenue_analytics',+ 'flag',+ 'workflow_variable',+ ])+ .describe(+ '* `event` - event\n* `event_metadata` - event_metadata\n* `feature` - feature\n* `person` - person\n* `cohort` - cohort\n* `element` - element\n* `static-cohort` - static-cohort\n* `dynamic-cohort` - dynamic-cohort\n* `precalculated-cohort` - precalculated-cohort\n* `group` - group\n* `recording` - recording\n* `log_entry` - log_entry\n* `behavioral` - behavioral\n* `session` - session\n* `hogql` - hogql\n* `data_warehouse` - data_warehouse\n* `data_warehouse_person_property` - data_warehouse_person_property\n* `error_tracking_issue` - error_tracking_issue\n* `log` - log\n* `log_attribute` - log_attribute\n* `log_resource_attribute` - log_resource_attribute\n* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute\n* `revenue_analytics` - revenue_analytics\n* `flag` - flag\n* `workflow_variable` - workflow_variable'+ ),+ zod.enum(['']),+ ])+ .default(errorTrackingQueryIssuesListCreateBodyFilterGroupItemTypeDefault),+ })+ )+ .optional()+ .describe(+ 'Advanced flat AND property filters. Prefer typed shortcut fields when they fit. HogQL filters are rejected.'+ ),+ orderBy: zod+ .enum(['last_seen', 'first_seen', 'occurrences', 'users', 'sessions'])+ .describe(+ '* `last_seen` - last_seen\n* `first_seen` - first_seen\n* `occurrences` - occurrences\n* `users` - users\n* `sessions` - sessions'+ )+ .default(errorTrackingQueryIssuesListCreateBodyOrderByDefault)+ .describe(+ 'Field used to sort issues. Defaults to occurrences.\n\n* `last_seen` - last_seen\n* `first_seen` - first_seen\n* `occurrences` - occurrences\n* `users` - users\n* `sessions` - sessions'+ ),+ orderDirection: zod+ .enum(['ASC', 'DESC'])+ .describe('* `ASC` - ASC\n* `DESC` - DESC')+ .default(errorTrackingQueryIssuesListCreateBodyOrderDirectionDefault)+ .describe('Sort direction. Defaults to DESC.\n\n* `ASC` - ASC\n* `DESC` - DESC'),+ limit: zod+ .number()+ .min(1)+ .max(errorTrackingQueryIssuesListCreateBodyLimitMax)+ .default(errorTrackingQueryIssuesListCreateBodyLimitDefault)+ .describe('Page size.'),+ offset: zod+ .number()+ .min(errorTrackingQueryIssuesListCreateBodyOffsetMin)+ .default(errorTrackingQueryIssuesListCreateBodyOffsetDefault)+ .describe('Pagination offset.'),+ volumeResolution: zod+ .number()+ .min(errorTrackingQueryIssuesListCreateBodyVolumeResolutionMin)+ .max(errorTrackingQueryIssuesListCreateBodyVolumeResolutionMax)+ .default(errorTrackingQueryIssuesListCreateBodyVolumeResolutionDefault)+ .describe('Number of volume buckets. Defaults to 0 for compact aggregate counts.'),+ library: zod+ .union([zod.string(), zod.array(zod.string()).min(1)])+ .optional()+ .describe('Filter by SDK/library value from event $lib, for example posthog-js.'),+ release: zod+ .string()+ .max(errorTrackingQueryIssuesListCreateBodyReleaseMax)+ .optional()+ .describe('Filter by exact release ID, version, or git commit ID captured in $exception_releases.'),+ fingerprint: zod+ .union([zod.string(), zod.array(zod.string()).min(1)])+ .optional()+ .describe('Filter by exact exception fingerprint hash, not fuzzy search.'),+ user: zod+ .string()+ .max(errorTrackingQueryIssuesListCreateBodyUserMax)+ .optional()+ .describe('Search user/email text.'),+ personId: zod.uuid().optional().describe('Filter by exact PostHog person UUID.'),+ url: zod+ .string()+ .max(errorTrackingQueryIssuesListCreateBodyUrlMax)+ .optional()+ .describe('Filter by current URL substring.'),+ filePath: zod+ .string()+ .max(errorTrackingQueryIssuesListCreateBodyFilePathMax)+ .optional()+ .describe('Search stack-frame source/file path text.'),+})+export const ErrorTrackingSettingsUpdateSettingsPartialUpdateBody = /* @__PURE__ */ zod.object({project_rate_limit_value: zod.number()diff --git a/products/error_tracking/mcp/apps/ErrorDetailsView.tsx b/products/error_tracking/mcp/apps/ErrorDetailsView.tsxindex 4eaf5f3b39aa..d13480545cc9 100644--- a/products/error_tracking/mcp/apps/ErrorDetailsView.tsx+++ b/products/error_tracking/mcp/apps/ErrorDetailsView.tsx@@ -16,15 +16,23 @@ export interface ErrorDetailsData {_posthogUrl?: string}+function firstString(value: unknown): string | undefined {+ if (typeof value === 'string') {+ return value+ }+ if (Array.isArray(value) && typeof value[0] === 'string') {+ return value[0]+ }+ return undefined+}+function extractExceptions(properties: Record<string, unknown>): ExceptionData[] {- // Primary source: $exception_list (structured exception data)if (Array.isArray(properties.$exception_list) && properties.$exception_list.length > 0) {return properties.$exception_list as ExceptionData[]}- // Fallback: construct from individual properties- const type = properties.$exception_type as string | undefined- const value = (properties.$exception_message ?? properties.$exception_value) as string | undefined+ const type = firstString(properties.$exception_types)+ const value = firstString(properties.$exception_values)if (type || value) {return [{ type: type ?? 'Error', value: value ?? '' }]}@@ -51,8 +59,8 @@ export function ErrorDetailsView({ data }: { data: ErrorDetailsData }): ReactEleconst properties = event.properties ?? {}const exceptions = extractExceptions(properties)- const exceptionType = (properties.$exception_type as string) ?? exceptions[0]?.type ?? 'Error'- const exceptionMessage = (properties.$exception_message as string) ?? exceptions[0]?.value ?? ''+ const exceptionType = firstString(properties.$exception_types) ?? exceptions[0]?.type ?? 'Error'+ const exceptionMessage = firstString(properties.$exception_values) ?? exceptions[0]?.value ?? ''return (<div className="p-4">@@ -62,11 +70,6 @@ export function ErrorDetailsView({ data }: { data: ErrorDetailsData }): ReactEle<Badge variant="danger" size="md">{exceptionType}</Badge>- {properties.$exception_synthetic && (- <Badge variant="neutral" size="sm">- Synthetic- </Badge>- )}</div><span className="text-sm text-text-primary">{exceptionMessage}</span></Stack>@@ -99,6 +102,9 @@ export function ErrorDetailsView({ data }: { data: ErrorDetailsData }): ReactEle...(properties.$current_url? [{ label: 'URL', value: properties.$current_url as string }]: []),+ ...(properties.$session_id+ ? [{ label: 'Session ID', value: properties.$session_id as string }]+ : []),]}/></Card>diff --git a/products/error_tracking/mcp/apps/ErrorTracking.stories.tsx b/products/error_tracking/mcp/apps/ErrorTracking.stories.tsxindex 3980e1b75577..d27b64f28f0c 100644--- a/products/error_tracking/mcp/apps/ErrorTracking.stories.tsx+++ b/products/error_tracking/mcp/apps/ErrorTracking.stories.tsx@@ -227,14 +227,15 @@ const sampleErrorDetails: ErrorDetailsData = {timestamp: '2025-12-15T14:30:00Z',properties: {$exception_list: [jsException],- $exception_type: 'TypeError',- $exception_message: 'Cannot read properties of undefined (reading "map")',+ $exception_types: ['TypeError'],+ $exception_values: ['Cannot read properties of undefined (reading "map")'],$browser: 'Chrome',$browser_version: '120.0',$os: 'macOS',$os_version: '14.2',$lib: 'posthog-js',$current_url: 'https://app.posthog.com/dashboard/1',+ $session_id: '019b4f6d-4a76-7000-8000-000000000001',},},],diff --git a/products/error_tracking/mcp/prompts/query-error-tracking-issue-events.md b/products/error_tracking/mcp/prompts/query-error-tracking-issue-events.mdnew file mode 100644index 000000000000..d1d018af85cd--- /dev/null+++ b/products/error_tracking/mcp/prompts/query-error-tracking-issue-events.md@@ -0,0 +1,19 @@+Fetch sampled `$exception` events for one Error tracking issue.++Use this when the user asks for concrete examples, stack traces, affected URLs, browser/OS/library context, or Session replay links for a specific issue.++Returns sampled events with plural exception fields (`$exception_types`, `$exception_values`), normalized `$exception_list`, `$exception_fingerprint`, `$exception_issue_id`, `$session_id`, `$lib`, browser/OS fields, and `$current_url`.++# Parameters++- `issueId`: required Error tracking issue UUID.+- `dateRange`: time range for sampled events. Defaults to last 7 days.+- `searchQuery`: search exception types, values, and current URL.+- `filterGroup`: advanced flat AND property filters applied to sampled events.+- `verbosity`: `summary` (default), `stack`, or `raw`. Use `raw` only when exact untruncated exception payloads are needed.+- `onlyAppFrames`: defaults to true to reduce vendor-frame noise.+- `limit`: defaults to 1 and maxes at 20. Keep low unless the user asks for multiple examples.++# Session recordings++When `$session_id` is present and the user asks what happened before the error, call `query-session-recordings-list` with `session_ids` to fetch matching recordings. Use multiple `$session_id` values in one call when available.diff --git a/products/error_tracking/mcp/prompts/query-error-tracking-issue.md b/products/error_tracking/mcp/prompts/query-error-tracking-issue.mdnew file mode 100644index 000000000000..e84a212e5207--- /dev/null+++ b/products/error_tracking/mcp/prompts/query-error-tracking-issue.md@@ -0,0 +1,16 @@+Get compact details for one Error tracking issue.++Use this after `query-error-tracking-issues-list` when you have an `issueId` and need issue status, name/description, first/last seen timestamps, assignee, compact impact counts, top in-app frame, and latest release metadata.++Defaults are intentionally useful: last 7 days, test accounts filtered out, aggregate impact included, and no sparkline unless requested.++# Parameters++- `issueId`: required Error tracking issue UUID.+- `dateRange`: time range for impact counts and latest-event metadata. Defaults to last 7 days.+- `includeSparkline`: set true only if a trend/sparkline helps answer the user. When true, `volumeResolution` defaults to 12 if not provided.+- `volumeResolution`: number of volume buckets when sparkline data is needed.++# Next steps++Use `query-error-tracking-issue-events` with the same `issueId` when the user needs concrete event examples, stack traces, browser/OS/URL context, or `$session_id` values for Session replay.diff --git a/products/error_tracking/mcp/prompts/query-error-tracking-issues-list.md b/products/error_tracking/mcp/prompts/query-error-tracking-issues-list.mdnew file mode 100644index 000000000000..81ab384e7a73--- /dev/null+++ b/products/error_tracking/mcp/prompts/query-error-tracking-issues-list.md@@ -0,0 +1,28 @@+List and filter Error tracking issues. Returns compact issue rows with aggregate impact counts (`occurrences`, `users`, `sessions`) and optional volume buckets.++Use this first when the user asks which errors are happening, which errors are most common, or wants to narrow issues by status, release, library, fingerprint, URL, user, person, or properties.++Defaults are intentionally useful: active issues, last 7 days, sorted by occurrences, test accounts filtered out, and compact aggregate counts.++Be minimalist. Only add filters needed to answer the user’s question. Do not add "is set" filters unless the user explicitly asks for them.++# Common filters++- `status`: `active`, `resolved`, `suppressed`, `pending_release`, `archived`, or `all`. Defaults to `active`.+- `searchQuery`: free-text search for exception names, values, stack frames, and email text.+- `library`: exact `$lib` match, for example `posthog-js`.+- `release`: exact release ID, release version, or git commit ID captured in `$exception_releases`. This intentionally does not match project name, branch, or timestamp fragments.+- `fingerprint`: exact `$exception_fingerprint` match.+- `url`: substring match on `$current_url`.+- `personId`: exact PostHog person UUID.+- `user`: user/email text search.+- `filePath`: stack-frame file/source text search.+- `filterGroup`: advanced flat AND property filters. Prefer typed fields above when they fit.++Use `dateRange` for time, not property filters. Omit `date_to` for now.++# Next steps++- Use `query-error-tracking-issue` with `issueId` to inspect one issue.+- Use `query-error-tracking-issue-events` with `issueId` to fetch sampled exception events, stack traces, URLs, and `$session_id` values.+- If the user asks what people were doing before the error, use `$session_id` values from issue events with `query-session-recordings-list` and its `session_ids` parameter.diff --git a/products/error_tracking/mcp/prompts/query-error-tracking-issues.md b/products/error_tracking/mcp/prompts/query-error-tracking-issues.mddeleted file mode 100644index cc2c0ef0e45f..000000000000--- a/products/error_tracking/mcp/prompts/query-error-tracking-issues.md+++ /dev/null@@ -1,189 +0,0 @@-Query error tracking issues to find, filter, and inspect errors in the project. Returns aggregated metrics per issue including occurrence count, affected users, sessions, and volume data.--Use 'read-data-schema' to discover available events, actions, and properties for filters.--This is a unified query tool — use it both to list issues and to get details on a specific issue:--- **List issues**: omit `issueId` to get a filtered, sorted list of error tracking issues.-- **Get issue details**: provide `issueId` to get aggregated metrics for a single issue.--Use `error-tracking-issues-retrieve` to get the full issue model (description, assignee, external references) and `error-tracking-issues-partial-update` to change status or assignee.--CRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.--# Data narrowing--## Property filters--Use property filters via the `filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question. Avoid adding them if the question can be addressed without additional filtering and always use the minimum set of property filters needed.--IMPORTANT: Do not check if a property is set unless the user explicitly asks for it.--When using a property filter, you should:--- **Prioritize properties directly related to the context or objective of the user's query.** Avoid using properties for identification like IDs. Instead, prioritize filtering based on general properties like `$browser`, `$os`, or `$geoip_country_code`.-- **Ensure that you find both the property group and name.** Property groups should be one of the following: event, person, session, group.-- After selecting a property, **validate that the property value accurately reflects the intended criteria**.-- **Find the suitable operator for type** (e.g., `contains`, `is set`).-- If the operator requires a value, use the `read-data-schema` tool to find the property values.--Infer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.--Supported operators for the String type are:--- equals (exact)-- doesn't equal (is_not)-- contains (icontains)-- doesn't contain (not_icontains)-- matches regex (regex)-- doesn't match regex (not_regex)-- is set-- is not set--Supported operators for the Numeric type are:--- equals (exact)-- doesn't equal (is_not)-- greater than (gt)-- less than (lt)-- is set-- is not set--Supported operators for the DateTime type are:--- equals (is_date_exact)-- doesn't equal (is_not for existence check)-- before (is_date_before)-- after (is_date_after)-- is set-- is not set--Supported operators for the Boolean type are:--- equals-- doesn't equal-- is set-- is not set--All operators take a single value except for `equals` and `doesn't equal` which can take one or more values (as an array).--## Time period--You should not filter events by time using property filters. Instead, use the `dateRange` field. If the question doesn't mention time, the default is the last 7 days.--# Parameters--## issueId (optional)--When provided, returns aggregated metrics for a single error tracking issue. When omitted, returns a paginated list of issues matching the filters.--## status--Filter by issue status. Available values: `active`, `resolved`, `suppressed`, `pending_release`, `archived`, `all`. Defaults to `active`.--## orderBy--Field to sort results by: `occurrences`, `last_seen`, `first_seen`, `users`, `sessions`. Defaults to `occurrences`.--## searchQuery--Free-text search across exception type, message, and stack frames. Use this when the user is looking for a specific error by name or message content.--## assignee--Filter issues by assignee. The value is a user ID. Use this when the user asks to see errors assigned to a specific person.--## filterGroup--A flat list of property filters to narrow results. Each filter specifies a property key, operator, type (event/person/session/group), and value. See the "Property filters" section above for usage guidelines and supported operators.--## volumeResolution--Controls the granularity of the volume chart data returned with each issue. Use `1` (default) for list views where you want a volume sparkline. Use `0` when you only need aggregate counts without volume data.--## dateRange--Date range to filter results. Defaults to the last 7 days (`-7d`).--- `date_from`: Start of the range. Accepts ISO 8601 timestamps (e.g., `2024-01-15T00:00:00Z`) or relative formats: `-7d`, `-2w`, `-1m`, `-1h`, `-1mStart`, `-1yStart`.-- `date_to`: End of the range. Same format. Omit or null for "now".--## limit / offset--Pagination controls. `limit` defaults to 50.--# Examples--## List all active errors sorted by occurrence count--```json-{}-```--All defaults apply: `status: "active"`, `orderBy: "occurrences"`, `dateRange: { "date_from": "-7d" }`.--## Search for a specific error--```json-{- "searchQuery": "TypeError: Cannot read property",- "limit": 10-}-```--## Get details for a specific issue--```json-{- "issueId": "01234567-89ab-cdef-0123-456789abcdef",- "volumeResolution": 0-}-```--## List resolved errors from the last 30 days--```json-{- "status": "resolved",- "dateRange": { "date_from": "-30d" },- "orderBy": "last_seen"-}-```--## Find most recent errors--```json-{- "orderBy": "first_seen",- "orderDirection": "DESC",- "dateRange": { "date_from": "-24h" }-}-```--## Errors from Chrome users only--```json-{- "filterGroup": [{ "key": "$browser", "operator": "exact", "type": "event", "value": ["Chrome"] }]-}-```--## Errors from US users in the last 30 days--```json-{- "filterGroup": [{ "key": "$geoip_country_code", "operator": "exact", "type": "event", "value": ["US"] }],- "dateRange": { "date_from": "-30d" }-}-```--# Session recordings--Each error issue is linked to sessions via `$session_id` on the underlying `$exception` events. When a user asks "what were they doing," "can I see what happened," or wants visual context for an error, fetch the session recording.--If you have specific `$session_id` values from event data, use `query-session-recordings-list` with the `session_ids` parameter to fetch multiple recordings in a single call. Otherwise, use `query-session-recordings-list` with an event filter for `$exception` matching the error. If a specific person is involved, also filter by `person_uuid` to see all their sessions. If no person context is available, filter by `$exception` alone to find all sessions with that error. Use `date_from` to match the issue's time range — e.g., if the error was first seen 10 days ago, set `date_from` accordingly so recordings from that period are included.--# Reminders--- Ensure that any properties included are directly relevant to the context and objectives of the user's question. Avoid unnecessary or unrelated details.-- Avoid overcomplicating the response with excessive property filters. Focus on the simplest solution.diff --git a/products/error_tracking/mcp/tools.yaml b/products/error_tracking/mcp/tools.yamlindex 27ef265a53bc..9625c49d9c9e 100644--- a/products/error_tracking/mcp/tools.yaml+++ b/products/error_tracking/mcp/tools.yaml@@ -16,7 +16,8 @@ ui_apps:view_prop: issueerror-issue-list:type: list- detail_tool: error-tracking-issues-retrieve+ detail_tool: query-error-tracking-issue+ detail_args: '{ issueId: item.id }'click_prop: onIssueClicktools:error-tracking-assignment-rules-create:@@ -154,7 +155,7 @@ tools:enabled: falseerror-tracking-issues-list:operation: error_tracking_issues_list- enabled: true+ enabled: falsescopes:- error_tracking:readannotations:@@ -205,7 +206,7 @@ tools:ui_app: error-issueerror-tracking-issues-retrieve:operation: error_tracking_issues_retrieve- enabled: true+ enabled: falsescopes:- error_tracking:readannotations:@@ -432,9 +433,8 @@ tools:error-tracking-symbol-sets-update:operation: error_tracking_symbol_sets_updateenabled: false-wrappers:- query-error-tracking-issues:- schema_ref: AssistantErrorTrackingQuery+ query-error-tracking-issue:+ operation: error_tracking_query_issue_createenabled: truescopes:- error_tracking:read@@ -442,17 +442,49 @@ wrappers:readOnly: truedestructive: falseidempotent: true- title: Query error tracking issues- description_file: ./prompts/query-error-tracking-issues.md- system_prompt_hint: Error filtering and aggregation (error-tracking category)- ui_resource_uri: ui://posthog/error-issue-list.html- property_defaults:- limit: 50- orderBy: occurrences- volumeResolution: 1- dateRange:- date_from: -7d- filterTestAccounts: true- status: active- orderDirection: DESC- url_prefix: /error_tracking+ enrich_url: '{params.issueId}'+ title: Query error tracking issue+ description_file: ./prompts/query-error-tracking-issue.md+ system_prompt_hint: Error issue details and impact (error-tracking category)+ ui_app: error-issue+ query-error-tracking-issue-events:+ operation: error_tracking_query_issue_events_create+ enabled: true+ scopes:+ - error_tracking:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ enrich_url: '{params.issueId}'+ title: Query error tracking issue events+ description_file: ./prompts/query-error-tracking-issue-events.md+ system_prompt_hint: Error event samples, stack traces, and session IDs (error-tracking category)+ ui_app: error-details+ query-error-tracking-issues-list:+ operation: error_tracking_query_issues_list_create+ enabled: true+ scopes:+ - error_tracking:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ enrich_url: '{id}'+ list: true+ title: Query error tracking issues list+ description_file: ./prompts/query-error-tracking-issues-list.md+ system_prompt_hint: Error issue filtering and aggregation (error-tracking category)+ ui_app: error-issue-list+ response:+ include:+ - id+ - name+ - description+ - status+ - first_seen+ - last_seen+ - library+ - source+ - assignee+ - aggregationsdiff --git a/products/product_analytics/skills/investigate-metric/SKILL.md b/products/product_analytics/skills/investigate-metric/SKILL.mdindex b05f01ea614b..c393348550ad 100644--- a/products/product_analytics/skills/investigate-metric/SKILL.md+++ b/products/product_analytics/skills/investigate-metric/SKILL.md@@ -33,7 +33,7 @@ Targets PostHog MCP v2. Typed query tools accept the query body directly — pas| `posthog:insight-get` / `-query` | Fetch a saved insight's metadata / data |Plus the standard PostHog tools the playbooks reference by name (`feature-flag-get-all`,-`experiment-get-all`, `annotations-list`, `error-tracking-issues-list`, `query-logs`,+`experiment-get-all`, `annotations-list`, `query-error-tracking-issues-list`, `query-logs`,`query-session-recordings-list`, `cohorts-list/-create`, `annotation-create`,`insight-create`).diff --git a/products/product_analytics/skills/investigate-metric/references/common-causes.md b/products/product_analytics/skills/investigate-metric/references/common-causes.mdindex c636ead3e0c2..b310409b4c14 100644--- a/products/product_analytics/skills/investigate-metric/references/common-causes.md+++ b/products/product_analytics/skills/investigate-metric/references/common-causes.md@@ -49,7 +49,7 @@ this directly.JS error on a Safari release, mobile crash on a specific OS, regional CDN issue.- Breakdown on `$browser`, `$browser_version`, `$os`, `$device_type`, `$geoip_country_code`.-- Cross-check with `posthog:error-tracking-issues-list`.+- Cross-check with `posthog:query-error-tracking-issues-list`.## Rate limit / upstream outagediff --git a/products/product_analytics/skills/investigate-metric/references/funnel-playbook.md b/products/product_analytics/skills/investigate-metric/references/funnel-playbook.mdindex 2421f1ea9e71..f0788539b9eb 100644--- a/products/product_analytics/skills/investigate-metric/references/funnel-playbook.md+++ b/products/product_analytics/skills/investigate-metric/references/funnel-playbook.md@@ -48,7 +48,7 @@ diff — users present in the first but not the second are the drop-offs.## 4. Errors / logs-Filter `posthog:error-tracking-issues-list` and `posthog:query-logs` to the surface+Filter `posthog:query-error-tracking-issues-list` and `posthog:query-logs` to the surfacewhere step N lives — a 500 on the submit endpoint can plausibly cause failures; aconsole warning elsewhere usually can't.diff --git a/products/product_analytics/skills/investigate-metric/references/paths-playbook.md b/products/product_analytics/skills/investigate-metric/references/paths-playbook.mdindex 6038f61da700..7411fa55e935 100644--- a/products/product_analytics/skills/investigate-metric/references/paths-playbook.md+++ b/products/product_analytics/skills/investigate-metric/references/paths-playbook.md@@ -46,5 +46,5 @@ browsers / countries / plans is evidence the change is segment-specific.## 5. Recordings + errorsPull session recordings for users on the new dominant edge — usually surfaces the UI-change faster than more queries. Cross-check `error-tracking-issues-list` for errors on+change faster than more queries. Cross-check `query-error-tracking-issues-list` for errors onthe page where users diverge.diff --git a/products/product_analytics/skills/investigate-metric/references/shared-patterns.md b/products/product_analytics/skills/investigate-metric/references/shared-patterns.mdindex 4dfa3a20fdeb..57a1187f5068 100644--- a/products/product_analytics/skills/investigate-metric/references/shared-patterns.md+++ b/products/product_analytics/skills/investigate-metric/references/shared-patterns.md@@ -143,7 +143,7 @@ running more queries. Fetch individual ones with `posthog:session-recording-get`## Error / logs cross-check-Run `posthog:error-tracking-issues-list` and `posthog:query-logs` for the anomaly window.+Run `posthog:query-error-tracking-issues-list` and `posthog:query-logs` for the anomaly window.A correlated error is a candidate, not a conclusion — confirm three things:1. **Timing** — error volume aligns with the metric movement.diff --git a/products/product_analytics/skills/investigate-metric/references/trend-playbook.md b/products/product_analytics/skills/investigate-metric/references/trend-playbook.mdindex e345d3e9ba5d..7fe21717bec0 100644--- a/products/product_analytics/skills/investigate-metric/references/trend-playbook.md+++ b/products/product_analytics/skills/investigate-metric/references/trend-playbook.md@@ -36,7 +36,7 @@ moved). For UI-shaped drops, pull session recordings for the same segment.## 4. Errors / logs-`posthog:error-tracking-issues-list` and `posthog:query-logs` for the window. Confirm+`posthog:query-error-tracking-issues-list` and `posthog:query-logs` for the window. Confirmtiming, plausible mechanism, and user overlap before treating as the cause.## 5. Cohort compositiondiff --git a/products/replay/skills/finding-replay-for-issue/SKILL.md b/products/replay/skills/finding-replay-for-issue/SKILL.mdindex 0a75d8032f0c..dedabfd73d81 100644--- a/products/replay/skills/finding-replay-for-issue/SKILL.md+++ b/products/replay/skills/finding-replay-for-issue/SKILL.md@@ -17,13 +17,13 @@ or duplicate occurrences. This skill picks the most useful one.## Available tools-| Tool | Purpose |-| ---------------------------------------- | ----------------------------------------------------- |-| `posthog:error-tracking-issues-retrieve` | Get issue details (fingerprint, status, volume) |-| `posthog:execute-sql` | Query exception events to find linked sessions |-| `posthog:query-session-recordings-list` | Fetch recording metadata for candidate sessions |-| `posthog:session-recording-get` | Get full details for the selected recording |-| `posthog:session-recording-summarize` | AI summary of the selected recording (optional, slow) |+| Tool | Purpose |+| --------------------------------------- | ----------------------------------------------------- |+| `posthog:query-error-tracking-issue` | Get issue details (fingerprint, status, volume) |+| `posthog:execute-sql` | Query exception events to find linked sessions |+| `posthog:query-session-recordings-list` | Fetch recording metadata for candidate sessions |+| `posthog:session-recording-get` | Get full details for the selected recording |+| `posthog:session-recording-summarize` | AI summary of the selected recording (optional, slow) |## Workflow@@ -32,9 +32,9 @@ or duplicate occurrences. This skill picks the most useful one.Fetch the error tracking issue to understand what you're looking for:```json-posthog:error-tracking-issues-retrieve+posthog:query-error-tracking-issue{- "id": "<issue_id>"+ "issueId": "<issue_id>"}```diff --git a/products/replay/skills/investigating-replay/SKILL.md b/products/replay/skills/investigating-replay/SKILL.mdindex 1eca32b1091c..607d002281fa 100644--- a/products/replay/skills/investigating-replay/SKILL.md+++ b/products/replay/skills/investigating-replay/SKILL.md@@ -7,7 +7,7 @@ description: >what happened — who the user was, what they did, what errors occurred,and whether there are related error tracking issues. Replaces the manualchain of session-recording-get, persons-retrieve, execute-sql, and- error-tracking-issues-list.+ query-error-tracking-issues-list.---# Investigating a session recording@@ -18,13 +18,13 @@ ask for each piece.## Available tools-| Tool | Purpose |-| ------------------------------------- | ------------------------------------------------ |-| `posthog:session-recording-get` | Recording metadata (duration, counts, status) |-| `posthog:persons-retrieve` | Person profile (properties, distinct IDs) |-| `posthog:execute-sql` | Query events, errors, and page views in session |-| `posthog:error-tracking-issues-list` | Find error tracking issues linked to the session |-| `posthog:session-recording-summarize` | AI-generated summary (slow, ~5 min, optional) |+| Tool | Purpose |+| ------------------------------------------ | ------------------------------------------------ |+| `posthog:session-recording-get` | Recording metadata (duration, counts, status) |+| `posthog:persons-retrieve` | Person profile (properties, distinct IDs) |+| `posthog:execute-sql` | Query events, errors, and page views in session |+| `posthog:query-error-tracking-issues-list` | Find error tracking issues linked to the session |+| `posthog:session-recording-summarize` | AI-generated summary (slow, ~5 min, optional) |## Workflow@@ -110,9 +110,9 @@ If fingerprints are found, search for the corresponding error tracking issuesto provide links and status:```json-posthog:error-tracking-issues-list+posthog:query-error-tracking-issues-list{- "search": "<exception_type or message>"+ "searchQuery": "<exception_type or message>"}```diff --git a/products/signals/skills/inbox-exploration/SKILL.md b/products/signals/skills/inbox-exploration/SKILL.mdindex 4e52c2726bd9..40014c75e991 100644--- a/products/signals/skills/inbox-exploration/SKILL.md+++ b/products/signals/skills/inbox-exploration/SKILL.md@@ -36,8 +36,8 @@ For deeper investigation, hand off to other skills and tools:search across signals, or to inspect every signal that contributed to a report.- **PostHog's product-specific MCP tools** — when a report points at a specific error, log line,session, person, or time range, reach for the matching domain tool to pull richer context:- - Error tracking: `query-error-tracking-issues`, `error-tracking-issues-retrieve` for- error-tracking-sourced reports+ - Error tracking: `query-error-tracking-issues-list`, `query-error-tracking-issue`,+ `query-error-tracking-issue-events` for error-tracking-sourced reports- Logs: `query-logs`, `logs-count-ranges` to find log activity around the issue- Session replays: `query-session-recordings-list`, `session-recording-get` to findrecordings of affected usersdiff --git a/services/mcp/README.md b/services/mcp/README.mdindex 6b2b26fde11a..e2875b8192bf 100644--- a/services/mcp/README.md+++ b/services/mcp/README.md@@ -227,7 +227,7 @@ Created experiment 'Pricing page test':**What happens:**-1. The `query-error-tracking-issues` tool fetches error groups sorted by occurrence count+1. The `query-error-tracking-issues-list` tool fetches error groups sorted by occurrence count2. Returns error details including affected user counts**Expected output:**diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 716347ec8cf2..1413614fd39d 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1278,21 +1278,6 @@"readOnlyHint": true}},- "error-tracking-issues-list": {- "description": "List all error tracking issues in the project. Returns issues with id, status, name, first seen timestamp, and assignee info.",- "category": "Error tracking",- "feature": "error_tracking",- "summary": "List error tracking issues",- "title": "List error tracking issues",- "required_scopes": ["error_tracking:read"],- "new_mcp": true,- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": true- }- },"error-tracking-issues-merge-create": {"description": "Merge one or more error tracking issues into an existing target issue. Provide the target issue as `id` and the issues to merge into it as `ids`.","category": "Error tracking",@@ -1323,21 +1308,6 @@"readOnlyHint": false}},- "error-tracking-issues-retrieve": {- "description": "Get a specific error tracking issue by ID. Returns full issue details including status, description, volume, and metadata. After retrieving an issue, consider using `query-session-recordings-list` with an event filter for `$exception` to find session recordings of users who hit this error.",- "category": "Error tracking",- "feature": "error_tracking",- "summary": "Get error tracking issue",- "title": "Get error tracking issue",- "required_scopes": ["error_tracking:read"],- "new_mcp": true,- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": true- }- },"error-tracking-issues-split-create": {"description": "Split one or more fingerprints out of an existing error tracking issue into new issues. Provide the source issue as `id` and the fingerprints to split as `fingerprints`, where each entry includes a required `fingerprint` and optional `name` or `description`.","category": "Error tracking",@@ -3810,12 +3780,44 @@},"feature_flag": "tracing"},- "query-error-tracking-issues": {- "description": "Query error tracking issues to find, filter, and inspect errors in the project. Returns aggregated metrics per issue including occurrence count, affected users, sessions, and volume data.\n\nUse 'read-data-schema' to discover available events, actions, and properties for filters.\n\nThis is a unified query tool — use it both to list issues and to get details on a specific issue:\n\n- **List issues**: omit `issueId` to get a filtered, sorted list of error tracking issues.\n- **Get issue details**: provide `issueId` to get aggregated metrics for a single issue.\n\nUse `error-tracking-issues-retrieve` to get the full issue model (description, assignee, external references) and `error-tracking-issues-partial-update` to change status or assignee.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question. Avoid adding them if the question can be addressed without additional filtering and always use the minimum set of property filters needed.\n\nIMPORTANT: Do not check if a property is set unless the user explicitly asks for it.\n\nWhen using a property filter, you should:\n\n- **Prioritize properties directly related to the context or objective of the user's query.** Avoid using properties for identification like IDs. Instead, prioritize filtering based on general properties like `$browser`, `$os`, or `$geoip_country_code`.\n- **Ensure that you find both the property group and name.** Property groups should be one of the following: event, person, session, group.\n- After selecting a property, **validate that the property value accurately reflects the intended criteria**.\n- **Find the suitable operator for type** (e.g., `contains`, `is set`).\n- If the operator requires a value, use the `read-data-schema` tool to find the property values.\n\nInfer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.\n\nSupported operators for the String type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- contains (icontains)\n- doesn't contain (not_icontains)\n- matches regex (regex)\n- doesn't match regex (not_regex)\n- is set\n- is not set\n\nSupported operators for the Numeric type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- greater than (gt)\n- less than (lt)\n- is set\n- is not set\n\nSupported operators for the DateTime type are:\n\n- equals (is_date_exact)\n- doesn't equal (is_not for existence check)\n- before (is_date_before)\n- after (is_date_after)\n- is set\n- is not set\n\nSupported operators for the Boolean type are:\n\n- equals\n- doesn't equal\n- is set\n- is not set\n\nAll operators take a single value except for `equals` and `doesn't equal` which can take one or more values (as an array).\n\n## Time period\n\nYou should not filter events by time using property filters. Instead, use the `dateRange` field. If the question doesn't mention time, the default is the last 7 days.\n\n# Parameters\n\n## issueId (optional)\n\nWhen provided, returns aggregated metrics for a single error tracking issue. When omitted, returns a paginated list of issues matching the filters.\n\n## status\n\nFilter by issue status. Available values: `active`, `resolved`, `suppressed`, `pending_release`, `archived`, `all`. Defaults to `active`.\n\n## orderBy\n\nField to sort results by: `occurrences`, `last_seen`, `first_seen`, `users`, `sessions`. Defaults to `occurrences`.\n\n## searchQuery\n\nFree-text search across exception type, message, and stack frames. Use this when the user is looking for a specific error by name or message content.\n\n## assignee\n\nFilter issues by assignee. The value is a user ID. Use this when the user asks to see errors assigned to a specific person.\n\n## filterGroup\n\nA flat list of property filters to narrow results. Each filter specifies a property key, operator, type (event/person/session/group), and value. See the \"Property filters\" section above for usage guidelines and supported operators.\n\n## volumeResolution\n\nControls the granularity of the volume chart data returned with each issue. Use `1` (default) for list views where you want a volume sparkline. Use `0` when you only need aggregate counts without volume data.\n\n## dateRange\n\nDate range to filter results. Defaults to the last 7 days (`-7d`).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps (e.g., `2024-01-15T00:00:00Z`) or relative formats: `-7d`, `-2w`, `-1m`, `-1h`, `-1mStart`, `-1yStart`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## limit / offset\n\nPagination controls. `limit` defaults to 50.\n\n# Examples\n\n## List all active errors sorted by occurrence count\n\n```json\n{}\n```\n\nAll defaults apply: `status: \"active\"`, `orderBy: \"occurrences\"`, `dateRange: { \"date_from\": \"-7d\" }`.\n\n## Search for a specific error\n\n```json\n{\n \"searchQuery\": \"TypeError: Cannot read property\",\n \"limit\": 10\n}\n```\n\n## Get details for a specific issue\n\n```json\n{\n \"issueId\": \"01234567-89ab-cdef-0123-456789abcdef\",\n \"volumeResolution\": 0\n}\n```\n\n## List resolved errors from the last 30 days\n\n```json\n{\n \"status\": \"resolved\",\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"orderBy\": \"last_seen\"\n}\n```\n\n## Find most recent errors\n\n```json\n{\n \"orderBy\": \"first_seen\",\n \"orderDirection\": \"DESC\",\n \"dateRange\": { \"date_from\": \"-24h\" }\n}\n```\n\n## Errors from Chrome users only\n\n```json\n{\n \"filterGroup\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Chrome\"] }]\n}\n```\n\n## Errors from US users in the last 30 days\n\n```json\n{\n \"filterGroup\": [{ \"key\": \"$geoip_country_code\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"US\"] }],\n \"dateRange\": { \"date_from\": \"-30d\" }\n}\n```\n\n# Session recordings\n\nEach error issue is linked to sessions via `$session_id` on the underlying `$exception` events. When a user asks \"what were they doing,\" \"can I see what happened,\" or wants visual context for an error, fetch the session recording.\n\nIf you have specific `$session_id` values from event data, use `query-session-recordings-list` with the `session_ids` parameter to fetch multiple recordings in a single call. Otherwise, use `query-session-recordings-list` with an event filter for `$exception` matching the error. If a specific person is involved, also filter by `person_uuid` to see all their sessions. If no person context is available, filter by `$exception` alone to find all sessions with that error. Use `date_from` to match the issue's time range — e.g., if the error was first seen 10 days ago, set `date_from` accordingly so recordings from that period are included.\n\n# Reminders\n\n- Ensure that any properties included are directly relevant to the context and objectives of the user's question. Avoid unnecessary or unrelated details.\n- Avoid overcomplicating the response with excessive property filters. Focus on the simplest solution.",+ "query-error-tracking-issue": {+ "description": "Get compact details for one Error tracking issue.\n\nUse this after `query-error-tracking-issues-list` when you have an `issueId` and need issue status, name/description, first/last seen timestamps, assignee, compact impact counts, top in-app frame, and latest release metadata.\n\nDefaults are intentionally useful: last 7 days, test accounts filtered out, aggregate impact included, and no sparkline unless requested.\n\n# Parameters\n\n- `issueId`: required Error tracking issue UUID.\n- `dateRange`: time range for impact counts and latest-event metadata. Defaults to last 7 days.\n- `includeSparkline`: set true only if a trend/sparkline helps answer the user. When true, `volumeResolution` defaults to 12 if not provided.\n- `volumeResolution`: number of volume buckets when sparkline data is needed.\n\n# Next steps\n\nUse `query-error-tracking-issue-events` with the same `issueId` when the user needs concrete event examples, stack traces, browser/OS/URL context, or `$session_id` values for Session replay.",+ "category": "Error tracking",+ "feature": "error_tracking",+ "summary": "Query error tracking issue",+ "title": "Query error tracking issue",+ "required_scopes": ["error_tracking:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "system_prompt_hint": "Error issue details and impact (error-tracking category)"+ },+ "query-error-tracking-issue-events": {+ "description": "Fetch sampled `$exception` events for one Error tracking issue.\n\nUse this when the user asks for concrete examples, stack traces, affected URLs, browser/OS/library context, or Session replay links for a specific issue.\n\nReturns sampled events with plural exception fields (`$exception_types`, `$exception_values`), normalized `$exception_list`, `$exception_fingerprint`, `$exception_issue_id`, `$session_id`, `$lib`, browser/OS fields, and `$current_url`.\n\n# Parameters\n\n- `issueId`: required Error tracking issue UUID.\n- `dateRange`: time range for sampled events. Defaults to last 7 days.\n- `searchQuery`: search exception types, values, and current URL.\n- `filterGroup`: advanced flat AND property filters applied to sampled events.\n- `verbosity`: `summary` (default), `stack`, or `raw`. Use `raw` only when exact untruncated exception payloads are needed.\n- `onlyAppFrames`: defaults to true to reduce vendor-frame noise.\n- `limit`: defaults to 1 and maxes at 20. Keep low unless the user asks for multiple examples.\n\n# Session recordings\n\nWhen `$session_id` is present and the user asks what happened before the error, call `query-session-recordings-list` with `session_ids` to fetch matching recordings. Use multiple `$session_id` values in one call when available.",+ "category": "Error tracking",+ "feature": "error_tracking",+ "summary": "Query error tracking issue events",+ "title": "Query error tracking issue events",+ "required_scopes": ["error_tracking:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "system_prompt_hint": "Error event samples, stack traces, and session IDs (error-tracking category)"+ },+ "query-error-tracking-issues-list": {+ "description": "List and filter Error tracking issues. Returns compact issue rows with aggregate impact counts (`occurrences`, `users`, `sessions`) and optional volume buckets.\n\nUse this first when the user asks which errors are happening, which errors are most common, or wants to narrow issues by status, release, library, fingerprint, URL, user, person, or properties.\n\nDefaults are intentionally useful: active issues, last 7 days, sorted by occurrences, test accounts filtered out, and compact aggregate counts.\n\nBe minimalist. Only add filters needed to answer the user’s question. Do not add \"is set\" filters unless the user explicitly asks for them.\n\n# Common filters\n\n- `status`: `active`, `resolved`, `suppressed`, `pending_release`, `archived`, or `all`. Defaults to `active`.\n- `searchQuery`: free-text search for exception names, values, stack frames, and email text.\n- `library`: exact `$lib` match, for example `posthog-js`.\n- `release`: exact release ID, release version, or git commit ID captured in `$exception_releases`. This intentionally does not match project name, branch, or timestamp fragments.\n- `fingerprint`: exact `$exception_fingerprint` match.\n- `url`: substring match on `$current_url`.\n- `personId`: exact PostHog person UUID.\n- `user`: user/email text search.\n- `filePath`: stack-frame file/source text search.\n- `filterGroup`: advanced flat AND property filters. Prefer typed fields above when they fit.\n\nUse `dateRange` for time, not property filters. Omit `date_to` for now.\n\n# Next steps\n\n- Use `query-error-tracking-issue` with `issueId` to inspect one issue.\n- Use `query-error-tracking-issue-events` with `issueId` to fetch sampled exception events, stack traces, URLs, and `$session_id` values.\n- If the user asks what people were doing before the error, use `$session_id` values from issue events with `query-session-recordings-list` and its `session_ids` parameter.","category": "Error tracking","feature": "error_tracking",- "summary": "Query error tracking issues",- "title": "Query error tracking issues",+ "summary": "Query error tracking issues list",+ "title": "Query error tracking issues list","required_scopes": ["error_tracking:read"],"new_mcp": true,"annotations": {@@ -3824,7 +3826,7 @@"openWorldHint": true,"readOnlyHint": true},- "system_prompt_hint": "Error filtering and aggregation (error-tracking category)"+ "system_prompt_hint": "Error issue filtering and aggregation (error-tracking category)"},"query-funnel": {"description": "Run a funnel query to analyze conversion rates through a sequence of steps. Funnel insights help understand user behavior as users navigate through a product. A funnel consists of a sequence of at least two events or actions, where some users progress to the next step while others drop off. Funnels use percentages as the primary aggregation type.\n\nUse 'read-data-schema' to discover available events, actions, and properties for filters and breakdowns.\n\nIMPORTANT: Funnels REQUIRE AT LEAST TWO series (events or actions).\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Track first-time conversions with special math aggregations.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using first_time_for_user math).\n\nCRITICAL: Be minimalist. Only include filters, breakdowns, and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters to narrow results. Only include property filters when they are essential to directly answer the user's question. Avoid adding them if the question can be addressed without additional segmentation and always use the minimum set of property filters needed.\n\nIMPORTANT: Do not check if a property is set unless the user explicitly asks for it.\n\nWhen using a property filter, you should:\n\n- **Prioritize properties directly related to the context or objective of the user's query.** Avoid using properties for identification like IDs. Instead, prioritize filtering based on general properties like `paidCustomer` or `icp_score`.\n- **Ensure that you find both the property group and name.** Property groups should be one of the following: event, person, session, group.\n- After selecting a property, **validate that the property value accurately reflects the intended criteria**.\n- **Find the suitable operator for type** (e.g., `contains`, `is set`).\n- If the operator requires a value, use the `read-data-schema` tool to find the property values.\n- You set logical operators to combine multiple properties of a single series: AND or OR.\n\nInfer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.\n\nSupported operators for the String type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- contains (icontains)\n- doesn't contain (not_icontains)\n- matches regex (regex)\n- doesn't match regex (not_regex)\n- is set\n- is not set\n\nSupported operators for the Numeric type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- greater than (gt)\n- less than (lt)\n- is set\n- is not set\n\nSupported operators for the DateTime type are:\n\n- equals (is_date_exact)\n- doesn't equal (is_not for existence check)\n- before (is_date_before)\n- after (is_date_after)\n- is set\n- is not set\n\nSupported operators for the Boolean type are:\n\n- equals\n- doesn't equal\n- is set\n- is not set\n\nAll operators take a single value except for `equals` and `doesn't equal` which can take one or more values (as an array).\n\n## Time period\n\nYou should not filter events by time using property filters. Instead, use the `dateRange` field. If the question doesn't mention time, use last 30 days as a default time period.\n\n# Funnel guidelines\n\n## Exclusion steps\n\nUsers may want to use exclusion events to filter out conversions in which a particular event occurred between specific steps. These events should not be included in the main sequence. You should include start and end indexes (0-based) for each exclusion where the minimum `funnelFromStep` is 0 (first step) and the maximum `funnelToStep` is the number of steps minus one. Exclusion events cannot be actions, only events.\n\nIMPORTANT: Exclusion steps filter out conversions where the exclusion event occurred BETWEEN the specified steps. This does NOT exclude users who completed the event before the funnel started or after it ended.\n\nFor example, there is a sequence with three steps: sign up (step 0), finish onboarding (step 1), purchase (step 2). If the user wants to exclude all conversions in which users navigated away between sign up and finishing onboarding, the exclusion step will be `$pageleave` with `funnelFromStep: 0` and `funnelToStep: 1`.\n\n## Breakdown\n\nA breakdown is used to segment data by a single property value. They divide all defined funnel series into multiple subseries based on the values of the property. Include a breakdown **only when it is essential to directly answer the user's question**. You should not add a breakdown if the question can be addressed without additional segmentation.\n\nWhen using breakdowns, you should:\n\n- **Identify the property group** and name for a breakdown.\n- **Provide the property name** for a breakdown.\n- **Validate that the property value accurately reflects the intended criteria**.\n\nExamples of using a breakdown:\n\n- page views to sign up funnel by country: you need to find a property such as `$geoip_country_code` and set it as a breakdown.\n- conversion rate of users who have completed onboarding after signing up by an organization: you need to find a property such as `organization name` and set it as a breakdown.\n\n## Combining multiple events into a single step (`GroupNode`)\n\n**Use a `GroupNode`** when the user wants a single funnel step to match any of several events — e.g. \"Pageview OR Pageleave counts as one step\", or \"the user signed up via any of these channels\". Different filters per event are fine — put them on the inner nodes. Use separate steps instead when the user wants the events to occur in sequence. Only `OR` is supported.\n\nFunnel math (`first_time_for_user` etc.), `optionalInFunnel`, and step-wide property filters are not supported on a grouped step — filters must live on the inner nodes, and any math / optional handling must use a regular non-grouped step.\n\n**Where things live:**\n\n- On the group: only `name` (display label).\n- On each inner node: `event` (or action `id`), `properties`, `name` — all respected normally; per-node `properties` apply only to that node.\n\n### Example — funnel with a grouped step\n\nA 3-step funnel where the middle step matches either `$pageview` on Safari or `$pageleave` on Chrome:\n\n```json\n{\n \"kind\": \"FunnelsQuery\",\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"sign up\" },\n {\n \"kind\": \"GroupNode\",\n \"operator\": \"OR\",\n \"name\": \"Pageview on Safari, Pageleave on Chrome\",\n \"nodes\": [\n {\n \"kind\": \"EventsNode\",\n \"event\": \"$pageview\",\n \"name\": \"Pageview\",\n \"properties\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Safari\"] }]\n },\n {\n \"kind\": \"EventsNode\",\n \"event\": \"$pageleave\",\n \"name\": \"Pageleave\",\n \"properties\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Chrome\"] }]\n }\n ]\n },\n { \"kind\": \"EventsNode\", \"event\": \"purchase\" }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" }\n}\n```\n\n# Examples\n\n## Conversion from first event ingested to insight saved for organizations over 6 months\n\n```json\n{\n \"kind\": \"FunnelsQuery\",\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"first team event ingested\" },\n { \"kind\": \"EventsNode\", \"event\": \"insight saved\" }\n ],\n \"dateRange\": { \"date_from\": \"-6m\" },\n \"interval\": \"month\",\n \"aggregation_group_type_index\": 0,\n \"funnelsFilter\": {\n \"funnelOrderType\": \"ordered\",\n \"funnelVizType\": \"trends\",\n \"funnelWindowInterval\": 14,\n \"funnelWindowIntervalUnit\": \"day\"\n },\n \"filterTestAccounts\": true\n}\n```\n\n## Signup page CTA click rate within one hour, excluding page leaves, broken down by OS\n\n```json\n{\n \"kind\": \"FunnelsQuery\",\n \"series\": [\n {\n \"kind\": \"EventsNode\",\n \"event\": \"$pageview\",\n \"properties\": [{ \"key\": \"$current_url\", \"type\": \"event\", \"value\": \"signup\", \"operator\": \"icontains\" }]\n },\n {\n \"kind\": \"EventsNode\",\n \"event\": \"click subscribe button\",\n \"properties\": [{ \"key\": \"$current_url\", \"type\": \"event\", \"value\": \"signup\", \"operator\": \"icontains\" }]\n }\n ],\n \"dateRange\": { \"date_from\": \"-180d\" },\n \"interval\": \"week\",\n \"funnelsFilter\": {\n \"funnelWindowInterval\": 1,\n \"funnelWindowIntervalUnit\": \"hour\",\n \"funnelOrderType\": \"ordered\",\n \"exclusions\": [{ \"kind\": \"EventsNode\", \"event\": \"$pageleave\", \"funnelFromStep\": 0, \"funnelToStep\": 1 }]\n },\n \"breakdownFilter\": { \"breakdown_type\": \"event\", \"breakdown\": \"$os\" },\n \"filterTestAccounts\": true\n}\n```\n\n## Credit card purchase rate from viewing a product with strict ordering (no events in between)\n\n```json\n{\n \"kind\": \"FunnelsQuery\",\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"view product\" },\n {\n \"kind\": \"EventsNode\",\n \"event\": \"purchase\",\n \"properties\": [{ \"key\": \"paymentMethod\", \"type\": \"event\", \"value\": \"credit_card\", \"operator\": \"exact\" }]\n }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"funnelsFilter\": {\n \"funnelOrderType\": \"strict\",\n \"funnelWindowInterval\": 14,\n \"funnelWindowIntervalUnit\": \"day\"\n },\n \"filterTestAccounts\": true\n}\n```\n\n## View product to buy button to purchase, using actions and events\n\n```json\n{\n \"kind\": \"FunnelsQuery\",\n \"series\": [\n { \"kind\": \"ActionsNode\", \"id\": 8882, \"name\": \"view product\" },\n { \"kind\": \"EventsNode\", \"event\": \"click buy button\" },\n {\n \"kind\": \"ActionsNode\",\n \"id\": 573,\n \"name\": \"purchase\",\n \"properties\": [\n { \"key\": \"shipping_method\", \"value\": \"express_delivery\", \"operator\": \"icontains\", \"type\": \"event\" }\n ]\n }\n ],\n \"funnelsFilter\": { \"funnelVizType\": \"steps\" },\n \"filterTestAccounts\": true\n}\n```\n\n# Reminders\n\n- You MUST ALWAYS use AT LEAST TWO series (events or actions) in the funnel.\n- Ensure that any properties included are directly relevant to the context and objectives of the user's question. Avoid unnecessary or unrelated details.\n- Avoid overcomplicating the response with excessive property filters. Focus on the simplest solution.\n- The default funnel step order is `ordered` (events in sequence but with other events allowed in between). Use `strict` when events should happen consecutively with no events in between. Use `unordered` when order doesn't matter.\n- Exclusion events in funnels only exclude conversions where the event happened between the specified steps, not before or after the funnel.",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 219bc9f0c0ef..9e75cef05cea 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1324,21 +1324,6 @@"readOnlyHint": true}},- "error-tracking-issues-list": {- "description": "List all error tracking issues in the project. Returns issues with id, status, name, first seen timestamp, and assignee info.",- "category": "Error tracking",- "feature": "error_tracking",- "summary": "List error tracking issues",- "title": "List error tracking issues",- "required_scopes": ["error_tracking:read"],- "new_mcp": true,- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": true- }- },"error-tracking-issues-merge-create": {"description": "Merge one or more error tracking issues into an existing target issue. Provide the target issue as `id` and the issues to merge into it as `ids`.","category": "Error tracking",@@ -1369,21 +1354,6 @@"readOnlyHint": false}},- "error-tracking-issues-retrieve": {- "description": "Get a specific error tracking issue by ID. Returns full issue details including status, description, volume, and metadata. After retrieving an issue, consider using `query-session-recordings-list` with an event filter for `$exception` to find session recordings of users who hit this error.",- "category": "Error tracking",- "feature": "error_tracking",- "summary": "Get error tracking issue",- "title": "Get error tracking issue",- "required_scopes": ["error_tracking:read"],- "new_mcp": true,- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": true- }- },"error-tracking-issues-split-create": {"description": "Split one or more fingerprints out of an existing error tracking issue into new issues. Provide the source issue as `id` and the fingerprints to split as `fingerprints`, where each entry includes a required `fingerprint` and optional `name` or `description`.","category": "Error tracking",@@ -4168,12 +4138,44 @@},"feature_flag": "tracing"},- "query-error-tracking-issues": {- "description": "Query error tracking issues to find, filter, and inspect errors in the project. Returns aggregated metrics per issue including occurrence count, affected users, sessions, and volume data.\n\nUse 'read-data-schema' to discover available events, actions, and properties for filters.\n\nThis is a unified query tool — use it both to list issues and to get details on a specific issue:\n\n- **List issues**: omit `issueId` to get a filtered, sorted list of error tracking issues.\n- **Get issue details**: provide `issueId` to get aggregated metrics for a single issue.\n\nUse `error-tracking-issues-retrieve` to get the full issue model (description, assignee, external references) and `error-tracking-issues-partial-update` to change status or assignee.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question. Avoid adding them if the question can be addressed without additional filtering and always use the minimum set of property filters needed.\n\nIMPORTANT: Do not check if a property is set unless the user explicitly asks for it.\n\nWhen using a property filter, you should:\n\n- **Prioritize properties directly related to the context or objective of the user's query.** Avoid using properties for identification like IDs. Instead, prioritize filtering based on general properties like `$browser`, `$os`, or `$geoip_country_code`.\n- **Ensure that you find both the property group and name.** Property groups should be one of the following: event, person, session, group.\n- After selecting a property, **validate that the property value accurately reflects the intended criteria**.\n- **Find the suitable operator for type** (e.g., `contains`, `is set`).\n- If the operator requires a value, use the `read-data-schema` tool to find the property values.\n\nInfer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.\n\nSupported operators for the String type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- contains (icontains)\n- doesn't contain (not_icontains)\n- matches regex (regex)\n- doesn't match regex (not_regex)\n- is set\n- is not set\n\nSupported operators for the Numeric type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- greater than (gt)\n- less than (lt)\n- is set\n- is not set\n\nSupported operators for the DateTime type are:\n\n- equals (is_date_exact)\n- doesn't equal (is_not for existence check)\n- before (is_date_before)\n- after (is_date_after)\n- is set\n- is not set\n\nSupported operators for the Boolean type are:\n\n- equals\n- doesn't equal\n- is set\n- is not set\n\nAll operators take a single value except for `equals` and `doesn't equal` which can take one or more values (as an array).\n\n## Time period\n\nYou should not filter events by time using property filters. Instead, use the `dateRange` field. If the question doesn't mention time, the default is the last 7 days.\n\n# Parameters\n\n## issueId (optional)\n\nWhen provided, returns aggregated metrics for a single error tracking issue. When omitted, returns a paginated list of issues matching the filters.\n\n## status\n\nFilter by issue status. Available values: `active`, `resolved`, `suppressed`, `pending_release`, `archived`, `all`. Defaults to `active`.\n\n## orderBy\n\nField to sort results by: `occurrences`, `last_seen`, `first_seen`, `users`, `sessions`. Defaults to `occurrences`.\n\n## searchQuery\n\nFree-text search across exception type, message, and stack frames. Use this when the user is looking for a specific error by name or message content.\n\n## assignee\n\nFilter issues by assignee. The value is a user ID. Use this when the user asks to see errors assigned to a specific person.\n\n## filterGroup\n\nA flat list of property filters to narrow results. Each filter specifies a property key, operator, type (event/person/session/group), and value. See the \"Property filters\" section above for usage guidelines and supported operators.\n\n## volumeResolution\n\nControls the granularity of the volume chart data returned with each issue. Use `1` (default) for list views where you want a volume sparkline. Use `0` when you only need aggregate counts without volume data.\n\n## dateRange\n\nDate range to filter results. Defaults to the last 7 days (`-7d`).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps (e.g., `2024-01-15T00:00:00Z`) or relative formats: `-7d`, `-2w`, `-1m`, `-1h`, `-1mStart`, `-1yStart`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## limit / offset\n\nPagination controls. `limit` defaults to 50.\n\n# Examples\n\n## List all active errors sorted by occurrence count\n\n```json\n{}\n```\n\nAll defaults apply: `status: \"active\"`, `orderBy: \"occurrences\"`, `dateRange: { \"date_from\": \"-7d\" }`.\n\n## Search for a specific error\n\n```json\n{\n \"searchQuery\": \"TypeError: Cannot read property\",\n \"limit\": 10\n}\n```\n\n## Get details for a specific issue\n\n```json\n{\n \"issueId\": \"01234567-89ab-cdef-0123-456789abcdef\",\n \"volumeResolution\": 0\n}\n```\n\n## List resolved errors from the last 30 days\n\n```json\n{\n \"status\": \"resolved\",\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"orderBy\": \"last_seen\"\n}\n```\n\n## Find most recent errors\n\n```json\n{\n \"orderBy\": \"first_seen\",\n \"orderDirection\": \"DESC\",\n \"dateRange\": { \"date_from\": \"-24h\" }\n}\n```\n\n## Errors from Chrome users only\n\n```json\n{\n \"filterGroup\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Chrome\"] }]\n}\n```\n\n## Errors from US users in the last 30 days\n\n```json\n{\n \"filterGroup\": [{ \"key\": \"$geoip_country_code\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"US\"] }],\n \"dateRange\": { \"date_from\": \"-30d\" }\n}\n```\n\n# Session recordings\n\nEach error issue is linked to sessions via `$session_id` on the underlying `$exception` events. When a user asks \"what were they doing,\" \"can I see what happened,\" or wants visual context for an error, fetch the session recording.\n\nIf you have specific `$session_id` values from event data, use `query-session-recordings-list` with the `session_ids` parameter to fetch multiple recordings in a single call. Otherwise, use `query-session-recordings-list` with an event filter for `$exception` matching the error. If a specific person is involved, also filter by `person_uuid` to see all their sessions. If no person context is available, filter by `$exception` alone to find all sessions with that error. Use `date_from` to match the issue's time range — e.g., if the error was first seen 10 days ago, set `date_from` accordingly so recordings from that period are included.\n\n# Reminders\n\n- Ensure that any properties included are directly relevant to the context and objectives of the user's question. Avoid unnecessary or unrelated details.\n- Avoid overcomplicating the response with excessive property filters. Focus on the simplest solution.",+ "query-error-tracking-issue": {+ "description": "Get compact details for one Error tracking issue.\n\nUse this after `query-error-tracking-issues-list` when you have an `issueId` and need issue status, name/description, first/last seen timestamps, assignee, compact impact counts, top in-app frame, and latest release metadata.\n\nDefaults are intentionally useful: last 7 days, test accounts filtered out, aggregate impact included, and no sparkline unless requested.\n\n# Parameters\n\n- `issueId`: required Error tracking issue UUID.\n- `dateRange`: time range for impact counts and latest-event metadata. Defaults to last 7 days.\n- `includeSparkline`: set true only if a trend/sparkline helps answer the user. When true, `volumeResolution` defaults to 12 if not provided.\n- `volumeResolution`: number of volume buckets when sparkline data is needed.\n\n# Next steps\n\nUse `query-error-tracking-issue-events` with the same `issueId` when the user needs concrete event examples, stack traces, browser/OS/URL context, or `$session_id` values for Session replay.",+ "category": "Error tracking",+ "feature": "error_tracking",+ "summary": "Query error tracking issue",+ "title": "Query error tracking issue",+ "required_scopes": ["error_tracking:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "system_prompt_hint": "Error issue details and impact (error-tracking category)"+ },+ "query-error-tracking-issue-events": {+ "description": "Fetch sampled `$exception` events for one Error tracking issue.\n\nUse this when the user asks for concrete examples, stack traces, affected URLs, browser/OS/library context, or Session replay links for a specific issue.\n\nReturns sampled events with plural exception fields (`$exception_types`, `$exception_values`), normalized `$exception_list`, `$exception_fingerprint`, `$exception_issue_id`, `$session_id`, `$lib`, browser/OS fields, and `$current_url`.\n\n# Parameters\n\n- `issueId`: required Error tracking issue UUID.\n- `dateRange`: time range for sampled events. Defaults to last 7 days.\n- `searchQuery`: search exception types, values, and current URL.\n- `filterGroup`: advanced flat AND property filters applied to sampled events.\n- `verbosity`: `summary` (default), `stack`, or `raw`. Use `raw` only when exact untruncated exception payloads are needed.\n- `onlyAppFrames`: defaults to true to reduce vendor-frame noise.\n- `limit`: defaults to 1 and maxes at 20. Keep low unless the user asks for multiple examples.\n\n# Session recordings\n\nWhen `$session_id` is present and the user asks what happened before the error, call `query-session-recordings-list` with `session_ids` to fetch matching recordings. Use multiple `$session_id` values in one call when available.",+ "category": "Error tracking",+ "feature": "error_tracking",+ "summary": "Query error tracking issue events",+ "title": "Query error tracking issue events",+ "required_scopes": ["error_tracking:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "system_prompt_hint": "Error event samples, stack traces, and session IDs (error-tracking category)"+ },+ "query-error-tracking-issues-list": {+ "description": "List and filter Error tracking issues. Returns compact issue rows with aggregate impact counts (`occurrences`, `users`, `sessions`) and optional volume buckets.\n\nUse this first when the user asks which errors are happening, which errors are most common, or wants to narrow issues by status, release, library, fingerprint, URL, user, person, or properties.\n\nDefaults are intentionally useful: active issues, last 7 days, sorted by occurrences, test accounts filtered out, and compact aggregate counts.\n\nBe minimalist. Only add filters needed to answer the user’s question. Do not add \"is set\" filters unless the user explicitly asks for them.\n\n# Common filters\n\n- `status`: `active`, `resolved`, `suppressed`, `pending_release`, `archived`, or `all`. Defaults to `active`.\n- `searchQuery`: free-text search for exception names, values, stack frames, and email text.\n- `library`: exact `$lib` match, for example `posthog-js`.\n- `release`: exact release ID, release version, or git commit ID captured in `$exception_releases`. This intentionally does not match project name, branch, or timestamp fragments.\n- `fingerprint`: exact `$exception_fingerprint` match.\n- `url`: substring match on `$current_url`.\n- `personId`: exact PostHog person UUID.\n- `user`: user/email text search.\n- `filePath`: stack-frame file/source text search.\n- `filterGroup`: advanced flat AND property filters. Prefer typed fields above when they fit.\n\nUse `dateRange` for time, not property filters. Omit `date_to` for now.\n\n# Next steps\n\n- Use `query-error-tracking-issue` with `issueId` to inspect one issue.\n- Use `query-error-tracking-issue-events` with `issueId` to fetch sampled exception events, stack traces, URLs, and `$session_id` values.\n- If the user asks what people were doing before the error, use `$session_id` values from issue events with `query-session-recordings-list` and its `session_ids` parameter.","category": "Error tracking","feature": "error_tracking",- "summary": "Query error tracking issues",- "title": "Query error tracking issues",+ "summary": "Query error tracking issues list",+ "title": "Query error tracking issues list","required_scopes": ["error_tracking:read"],"new_mcp": true,"annotations": {@@ -4182,7 +4184,7 @@"openWorldHint": true,"readOnlyHint": true},- "system_prompt_hint": "Error filtering and aggregation (error-tracking category)"+ "system_prompt_hint": "Error issue filtering and aggregation (error-tracking category)"},"query-funnel": {"description": "Run a funnel query to analyze conversion rates through a sequence of steps. Funnel insights help understand user behavior as users navigate through a product. A funnel consists of a sequence of at least two events or actions, where some users progress to the next step while others drop off. Funnels use percentages as the primary aggregation type.\n\nUse 'read-data-schema' to discover available events, actions, and properties for filters and breakdowns.\n\nIMPORTANT: Funnels REQUIRE AT LEAST TWO series (events or actions).\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Track first-time conversions with special math aggregations.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using first_time_for_user math).\n\nCRITICAL: Be minimalist. Only include filters, breakdowns, and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters to narrow results. Only include property filters when they are essential to directly answer the user's question. Avoid adding them if the question can be addressed without additional segmentation and always use the minimum set of property filters needed.\n\nIMPORTANT: Do not check if a property is set unless the user explicitly asks for it.\n\nWhen using a property filter, you should:\n\n- **Prioritize properties directly related to the context or objective of the user's query.** Avoid using properties for identification like IDs. Instead, prioritize filtering based on general properties like `paidCustomer` or `icp_score`.\n- **Ensure that you find both the property group and name.** Property groups should be one of the following: event, person, session, group.\n- After selecting a property, **validate that the property value accurately reflects the intended criteria**.\n- **Find the suitable operator for type** (e.g., `contains`, `is set`).\n- If the operator requires a value, use the `read-data-schema` tool to find the property values.\n- You set logical operators to combine multiple properties of a single series: AND or OR.\n\nInfer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.\n\nSupported operators for the String type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- contains (icontains)\n- doesn't contain (not_icontains)\n- matches regex (regex)\n- doesn't match regex (not_regex)\n- is set\n- is not set\n\nSupported operators for the Numeric type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- greater than (gt)\n- less than (lt)\n- is set\n- is not set\n\nSupported operators for the DateTime type are:\n\n- equals (is_date_exact)\n- doesn't equal (is_not for existence check)\n- before (is_date_before)\n- after (is_date_after)\n- is set\n- is not set\n\nSupported operators for the Boolean type are:\n\n- equals\n- doesn't equal\n- is set\n- is not set\n\nAll operators take a single value except for `equals` and `doesn't equal` which can take one or more values (as an array).\n\n## Time period\n\nYou should not filter events by time using property filters. Instead, use the `dateRange` field. If the question doesn't mention time, use last 30 days as a default time period.\n\n# Funnel guidelines\n\n## Exclusion steps\n\nUsers may want to use exclusion events to filter out conversions in which a particular event occurred between specific steps. These events should not be included in the main sequence. You should include start and end indexes (0-based) for each exclusion where the minimum `funnelFromStep` is 0 (first step) and the maximum `funnelToStep` is the number of steps minus one. Exclusion events cannot be actions, only events.\n\nIMPORTANT: Exclusion steps filter out conversions where the exclusion event occurred BETWEEN the specified steps. This does NOT exclude users who completed the event before the funnel started or after it ended.\n\nFor example, there is a sequence with three steps: sign up (step 0), finish onboarding (step 1), purchase (step 2). If the user wants to exclude all conversions in which users navigated away between sign up and finishing onboarding, the exclusion step will be `$pageleave` with `funnelFromStep: 0` and `funnelToStep: 1`.\n\n## Breakdown\n\nA breakdown is used to segment data by a single property value. They divide all defined funnel series into multiple subseries based on the values of the property. Include a breakdown **only when it is essential to directly answer the user's question**. You should not add a breakdown if the question can be addressed without additional segmentation.\n\nWhen using breakdowns, you should:\n\n- **Identify the property group** and name for a breakdown.\n- **Provide the property name** for a breakdown.\n- **Validate that the property value accurately reflects the intended criteria**.\n\nExamples of using a breakdown:\n\n- page views to sign up funnel by country: you need to find a property such as `$geoip_country_code` and set it as a breakdown.\n- conversion rate of users who have completed onboarding after signing up by an organization: you need to find a property such as `organization name` and set it as a breakdown.\n\n## Combining multiple events into a single step (`GroupNode`)\n\n**Use a `GroupNode`** when the user wants a single funnel step to match any of several events — e.g. \"Pageview OR Pageleave counts as one step\", or \"the user signed up via any of these channels\". Different filters per event are fine — put them on the inner nodes. Use separate steps instead when the user wants the events to occur in sequence. Only `OR` is supported.\n\nFunnel math (`first_time_for_user` etc.), `optionalInFunnel`, and step-wide property filters are not supported on a grouped step — filters must live on the inner nodes, and any math / optional handling must use a regular non-grouped step.\n\n**Where things live:**\n\n- On the group: only `name` (display label).\n- On each inner node: `event` (or action `id`), `properties`, `name` — all respected normally; per-node `properties` apply only to that node.\n\n### Example — funnel with a grouped step\n\nA 3-step funnel where the middle step matches either `$pageview` on Safari or `$pageleave` on Chrome:\n\n```json\n{\n \"kind\": \"FunnelsQuery\",\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"sign up\" },\n {\n \"kind\": \"GroupNode\",\n \"operator\": \"OR\",\n \"name\": \"Pageview on Safari, Pageleave on Chrome\",\n \"nodes\": [\n {\n \"kind\": \"EventsNode\",\n \"event\": \"$pageview\",\n \"name\": \"Pageview\",\n \"properties\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Safari\"] }]\n },\n {\n \"kind\": \"EventsNode\",\n \"event\": \"$pageleave\",\n \"name\": \"Pageleave\",\n \"properties\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Chrome\"] }]\n }\n ]\n },\n { \"kind\": \"EventsNode\", \"event\": \"purchase\" }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" }\n}\n```\n\n# Examples\n\n## Conversion from first event ingested to insight saved for organizations over 6 months\n\n```json\n{\n \"kind\": \"FunnelsQuery\",\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"first team event ingested\" },\n { \"kind\": \"EventsNode\", \"event\": \"insight saved\" }\n ],\n \"dateRange\": { \"date_from\": \"-6m\" },\n \"interval\": \"month\",\n \"aggregation_group_type_index\": 0,\n \"funnelsFilter\": {\n \"funnelOrderType\": \"ordered\",\n \"funnelVizType\": \"trends\",\n \"funnelWindowInterval\": 14,\n \"funnelWindowIntervalUnit\": \"day\"\n },\n \"filterTestAccounts\": true\n}\n```\n\n## Signup page CTA click rate within one hour, excluding page leaves, broken down by OS\n\n```json\n{\n \"kind\": \"FunnelsQuery\",\n \"series\": [\n {\n \"kind\": \"EventsNode\",\n \"event\": \"$pageview\",\n \"properties\": [{ \"key\": \"$current_url\", \"type\": \"event\", \"value\": \"signup\", \"operator\": \"icontains\" }]\n },\n {\n \"kind\": \"EventsNode\",\n \"event\": \"click subscribe button\",\n \"properties\": [{ \"key\": \"$current_url\", \"type\": \"event\", \"value\": \"signup\", \"operator\": \"icontains\" }]\n }\n ],\n \"dateRange\": { \"date_from\": \"-180d\" },\n \"interval\": \"week\",\n \"funnelsFilter\": {\n \"funnelWindowInterval\": 1,\n \"funnelWindowIntervalUnit\": \"hour\",\n \"funnelOrderType\": \"ordered\",\n \"exclusions\": [{ \"kind\": \"EventsNode\", \"event\": \"$pageleave\", \"funnelFromStep\": 0, \"funnelToStep\": 1 }]\n },\n \"breakdownFilter\": { \"breakdown_type\": \"event\", \"breakdown\": \"$os\" },\n \"filterTestAccounts\": true\n}\n```\n\n## Credit card purchase rate from viewing a product with strict ordering (no events in between)\n\n```json\n{\n \"kind\": \"FunnelsQuery\",\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"view product\" },\n {\n \"kind\": \"EventsNode\",\n \"event\": \"purchase\",\n \"properties\": [{ \"key\": \"paymentMethod\", \"type\": \"event\", \"value\": \"credit_card\", \"operator\": \"exact\" }]\n }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"funnelsFilter\": {\n \"funnelOrderType\": \"strict\",\n \"funnelWindowInterval\": 14,\n \"funnelWindowIntervalUnit\": \"day\"\n },\n \"filterTestAccounts\": true\n}\n```\n\n## View product to buy button to purchase, using actions and events\n\n```json\n{\n \"kind\": \"FunnelsQuery\",\n \"series\": [\n { \"kind\": \"ActionsNode\", \"id\": 8882, \"name\": \"view product\" },\n { \"kind\": \"EventsNode\", \"event\": \"click buy button\" },\n {\n \"kind\": \"ActionsNode\",\n \"id\": 573,\n \"name\": \"purchase\",\n \"properties\": [\n { \"key\": \"shipping_method\", \"value\": \"express_delivery\", \"operator\": \"icontains\", \"type\": \"event\" }\n ]\n }\n ],\n \"funnelsFilter\": { \"funnelVizType\": \"steps\" },\n \"filterTestAccounts\": true\n}\n```\n\n# Reminders\n\n- You MUST ALWAYS use AT LEAST TWO series (events or actions) in the funnel.\n- Ensure that any properties included are directly relevant to the context and objectives of the user's question. Avoid unnecessary or unrelated details.\n- Avoid overcomplicating the response with excessive property filters. Focus on the simplest solution.\n- The default funnel step order is `ordered` (events in sequence but with other events allowed in between). Use `strict` when events should happen consecutively with no events in between. Use `unordered` when order doesn't matter.\n- Exclusion events in funnels only exclude conversions where the event happened between the specified steps, not before or after the funnel.",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 433a6dfdb19b..3e6fea1bd0d4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -16235,6 +16235,49 @@ export namespace Schemas {error: string;}+ export interface ErrorTrackingVolumeBucket {+ /** Bucket timestamp label. */+ label: string;+ /**+ * Occurrence count for the bucket.+ * @nullable+ */+ value?: number | null;+ }++ export interface ErrorTrackingAggregations {+ /** Exception occurrence count. */+ occurrences?: number;+ /** Unique user count. */+ users?: number;+ /** Unique session count. */+ sessions?: number;+ /** Occurrence counts per volume bucket. */+ volumeRange?: number[];+ /** Labeled volume buckets. */+ volume_buckets?: ErrorTrackingVolumeBucket[];+ }++ export interface ErrorTrackingAssignee {+ /** User ID or role UUID to filter by. */+ id: string | number;+ /** Assignee target type: user or role.++ * `user` - user+ * `role` - role */+ type: AssigneeTypeEnum;+ }++ export interface ErrorTrackingAssigneeResponse {+ /** Assignee user ID or role UUID. */+ id?: string | number | null;+ /**+ * Assignee type.+ * @nullable+ */+ type?: string | null;+ }+/*** @nullable*/@@ -16341,6 +16384,32 @@ export namespace Schemas {version?: number | null;}+ export interface ErrorTrackingDateRange {+ /** Start of the date range as an ISO timestamp or relative date such as -7d. Defaults to -7d. */+ date_from?: string;+ /**+ * End of the date range as an ISO timestamp or relative date. Defaults to now when omitted.+ * @nullable+ */+ date_to?: string | null;+ }++ /**+ * Normalized sampled exception event properties.+ */+ export type ErrorTrackingEventProperties = { [key: string]: unknown };++ export interface ErrorTrackingEvent {+ /** Event UUID. */+ uuid?: string;+ /** Event distinct ID. */+ distinct_id?: string;+ /** Event timestamp. */+ timestamp?: string;+ /** Normalized sampled exception event properties. */+ properties?: ErrorTrackingEventProperties;+ }+export interface ErrorTrackingExternalReferenceIntegrationResult {readonly id: number;readonly kind: string;@@ -16425,11 +16494,232 @@ export namespace Schemas {results: ErrorTrackingGroupingRule[];}+ export interface ErrorTrackingImpact {+ /** Exception occurrence count. */+ occurrences?: number;+ /** Unique user count. */+ users?: number;+ /** Unique session count. */+ sessions?: number;+ }+export interface ErrorTrackingIssueAssignment {readonly id: number | string | null;readonly type: string;}+ export interface ErrorTrackingTopFrame {+ /** Frame function name. */+ function?: string;+ /** Frame source, filename, or module. */+ source?: string;+ /** Line number. */+ line?: number;+ /** Column number. */+ column?: number;+ /** Whether the frame is an application frame. */+ in_app?: boolean;+ }++ export interface ErrorTrackingLatestRelease {+ /** Release version. */+ version?: string;+ /** Release project/library. */+ project?: string;+ /** Release timestamp. */+ timestamp?: string;+ /** Git commit ID. */+ commit_id?: string;+ /** Git branch. */+ branch?: string;+ /** Git repository name. */+ repo_name?: string;+ }++ export interface ErrorTrackingIssueDetail {+ /** Error tracking issue ID. */+ id: string;+ /**+ * Issue name.+ * @nullable+ */+ name?: string | null;+ /**+ * Issue description.+ * @nullable+ */+ description?: string | null;+ /** Issue status. */+ status?: string;+ /**+ * First seen timestamp.+ * @nullable+ */+ first_seen?: string | null;+ /**+ * Last seen timestamp.+ * @nullable+ */+ last_seen?: string | null;+ /**+ * SDK/library associated with the issue.+ * @nullable+ */+ library?: string | null;+ /**+ * Top source/file associated with the issue.+ * @nullable+ */+ source?: string | null;+ /** Issue assignee. */+ assignee?: ErrorTrackingAssigneeResponse | null;+ /** Aggregate counts. */+ aggregations?: ErrorTrackingAggregations | null;+ /**+ * Top function associated with the issue.+ * @nullable+ */+ function?: string | null;+ /** Top in_app application frame. */+ top_in_app_frame?: ErrorTrackingTopFrame;+ /** Latest release metadata. */+ latest_release?: ErrorTrackingLatestRelease;+ /** Compact impact counts. */+ impact?: ErrorTrackingImpact;+ /** Optional compact occurrence sparkline. */+ sparkline?: number[];+ }++ /**+ * * `exact` - exact+ * `is_not` - is_not+ * `icontains` - icontains+ * `not_icontains` - not_icontains+ * `regex` - regex+ * `not_regex` - not_regex+ * `gt` - gt+ * `lt` - lt+ * `gte` - gte+ * `lte` - lte+ * `is_set` - is_set+ * `is_not_set` - is_not_set+ * `is_date_exact` - is_date_exact+ * `is_date_after` - is_date_after+ * `is_date_before` - is_date_before+ * `in` - in+ * `not_in` - not_in+ */+ export type PropertyItemOperatorEnum = typeof PropertyItemOperatorEnum[keyof typeof PropertyItemOperatorEnum];+++ export const PropertyItemOperatorEnum = {+ Exact: 'exact',+ IsNot: 'is_not',+ Icontains: 'icontains',+ NotIcontains: 'not_icontains',+ Regex: 'regex',+ NotRegex: 'not_regex',+ Gt: 'gt',+ Lt: 'lt',+ Gte: 'gte',+ Lte: 'lte',+ IsSet: 'is_set',+ IsNotSet: 'is_not_set',+ IsDateExact: 'is_date_exact',+ IsDateAfter: 'is_date_after',+ IsDateBefore: 'is_date_before',+ In: 'in',+ NotIn: 'not_in',+ } as const;++ export interface PropertyItem {+ /** Key of the property you're filtering on. For example `email` or `$current_url` */+ key: string;+ /** Value of your filter. For example `[email protected]` or `https://example.com/test/`. Can be an array for an OR query, like `["[email protected]","[email protected]"]` */+ value: string | number | boolean | (string | number)[];+ operator?: PropertyItemOperatorEnum | BlankEnum | NullEnum | null;+ type?: PropertyFilterTypeEnum | BlankEnum;+ }++ /**+ * * `ASC` - ASC+ * `DESC` - DESC+ */+ export type OrderDirectionEnum = typeof OrderDirectionEnum[keyof typeof OrderDirectionEnum];+++ export const OrderDirectionEnum = {+ Asc: 'ASC',+ Desc: 'DESC',+ } as const;++ /**+ * * `summary` - summary+ * `stack` - stack+ * `raw` - raw+ */+ export type VerbosityEnum = typeof VerbosityEnum[keyof typeof VerbosityEnum];+++ export const VerbosityEnum = {+ Summary: 'summary',+ Stack: 'stack',+ Raw: 'raw',+ } as const;++ export interface ErrorTrackingIssueEventsQueryRequest {+ /** Error tracking issue ID. */+ issueId: string;+ /** Date range for sampled exception events. Defaults to the last 7 days. */+ dateRange?: ErrorTrackingDateRange;+ /** When true, exclude internal/test account data from results. Defaults to true. */+ filterTestAccounts?: boolean;+ /** Advanced flat AND property filters applied to sampled events. HogQL filters are rejected. */+ filterGroup?: PropertyItem[];+ /**+ * Search exception types, exception values, and current URL among sampled events.+ * @maxLength 500+ */+ searchQuery?: string;+ /** Timestamp sort direction. Defaults to DESC.++ * `ASC` - ASC+ * `DESC` - DESC */+ orderDirection?: OrderDirectionEnum;+ /**+ * Page size.+ * @minimum 1+ * @maximum 20+ */+ limit?: number;+ /**+ * Pagination offset.+ * @minimum 0+ */+ offset?: number;+ /** Controls exception detail size: summary, stack, or raw. Defaults to summary.++ * `summary` - summary+ * `stack` - stack+ * `raw` - raw */+ verbosity?: VerbosityEnum;+ /** When true, include only stack frames marked in_app. Defaults to true. */+ onlyAppFrames?: boolean;+ }++ export interface ErrorTrackingIssueEventsResponse {+ /** Sampled exception events. */+ results: ErrorTrackingEvent[];+ /** Whether more results are available. */+ hasMore: boolean;+ /** Page size. */+ limit: number;+ /** Current offset. */+ offset: number;+ /** Offset to fetch the next page when hasMore is true. */+ nextOffset?: number;+ }+/*** @nullable*/@@ -16470,6 +16760,47 @@ export namespace Schemas {readonly cohort: ErrorTrackingIssueFullCohort;}+ export interface ErrorTrackingIssueListItem {+ /** Error tracking issue ID. */+ id: string;+ /**+ * Issue name.+ * @nullable+ */+ name?: string | null;+ /**+ * Issue description.+ * @nullable+ */+ description?: string | null;+ /** Issue status. */+ status?: string;+ /**+ * First seen timestamp.+ * @nullable+ */+ first_seen?: string | null;+ /**+ * Last seen timestamp.+ * @nullable+ */+ last_seen?: string | null;+ /**+ * SDK/library associated with the issue.+ * @nullable+ */+ library?: string | null;+ /**+ * Top source/file associated with the issue.+ * @nullable+ */+ source?: string | null;+ /** Issue assignee. */+ assignee?: ErrorTrackingAssigneeResponse | null;+ /** Aggregate counts. */+ aggregations?: ErrorTrackingAggregations | null;+ }+export interface ErrorTrackingIssueMergeRequest {/** IDs of the issues to merge into the current issue. */ids: string[];@@ -16480,6 +16811,41 @@ export namespace Schemas {success: boolean;}+ /**+ * * `last_seen` - last_seen+ * `first_seen` - first_seen+ * `occurrences` - occurrences+ * `users` - users+ * `sessions` - sessions+ */+ export type ErrorTrackingIssueOrderByEnum = typeof ErrorTrackingIssueOrderByEnum[keyof typeof ErrorTrackingIssueOrderByEnum];+++ export const ErrorTrackingIssueOrderByEnum = {+ LastSeen: 'last_seen',+ FirstSeen: 'first_seen',+ Occurrences: 'occurrences',+ Users: 'users',+ Sessions: 'sessions',+ } as const;++ export interface ErrorTrackingIssueQueryRequest {+ /** Error tracking issue ID. */+ issueId: string;+ /** Date range for issue impact and latest-event metadata. Defaults to the last 7 days. */+ dateRange?: ErrorTrackingDateRange;+ /** When true, exclude internal/test account data from results. Defaults to true. */+ filterTestAccounts?: boolean;+ /**+ * Volume buckets. Maximum 200.+ * @minimum 0+ * @maximum 200+ */+ volumeResolution?: number;+ /** Set true to include a compact numeric occurrence sparkline. Defaults to false. */+ includeSparkline?: boolean;+ }+export interface ErrorTrackingIssueSplitFingerprint {/** Fingerprint to split into a new issue. */fingerprint: string;@@ -16501,6 +16867,120 @@ export namespace Schemas {new_issue_ids: string[];}+ /**+ * * `archived` - archived+ * `active` - active+ * `resolved` - resolved+ * `pending_release` - pending_release+ * `suppressed` - suppressed+ * `all` - all+ */+ export type ErrorTrackingIssuesListQueryRequestStatusEnum = typeof ErrorTrackingIssuesListQueryRequestStatusEnum[keyof typeof ErrorTrackingIssuesListQueryRequestStatusEnum];+++ export const ErrorTrackingIssuesListQueryRequestStatusEnum = {+ Archived: 'archived',+ Active: 'active',+ Resolved: 'resolved',+ PendingRelease: 'pending_release',+ Suppressed: 'suppressed',+ All: 'all',+ } as const;++ export interface ErrorTrackingIssuesListQueryRequest {+ /** Date range for issue aggregates. Defaults to the last 7 days. */+ dateRange?: ErrorTrackingDateRange;+ /** Filter by issue status. Defaults to active.++ * `archived` - archived+ * `active` - active+ * `resolved` - resolved+ * `pending_release` - pending_release+ * `suppressed` - suppressed+ * `all` - all */+ status?: ErrorTrackingIssuesListQueryRequestStatusEnum;+ /** Filter by issue assignee. Omit to include all assignees. */+ assignee?: ErrorTrackingAssignee | null;+ /** When true, exclude internal/test account data from results. Defaults to true. */+ filterTestAccounts?: boolean;+ /**+ * Free-text search across exception types, values, stack frames, and email fields.+ * @maxLength 500+ */+ searchQuery?: string;+ /** Advanced flat AND property filters. Prefer typed shortcut fields when they fit. HogQL filters are rejected. */+ filterGroup?: PropertyItem[];+ /** Field used to sort issues. Defaults to occurrences.++ * `last_seen` - last_seen+ * `first_seen` - first_seen+ * `occurrences` - occurrences+ * `users` - users+ * `sessions` - sessions */+ orderBy?: ErrorTrackingIssueOrderByEnum;+ /** Sort direction. Defaults to DESC.++ * `ASC` - ASC+ * `DESC` - DESC */+ orderDirection?: OrderDirectionEnum;+ /**+ * Page size.+ * @minimum 1+ * @maximum 100+ */+ limit?: number;+ /**+ * Pagination offset.+ * @minimum 0+ */+ offset?: number;+ /**+ * Number of volume buckets. Defaults to 0 for compact aggregate counts.+ * @minimum 0+ * @maximum 200+ */+ volumeResolution?: number;+ /** Filter by SDK/library value from event $lib, for example posthog-js. */+ library?: string | string[];+ /**+ * Filter by exact release ID, version, or git commit ID captured in $exception_releases.+ * @maxLength 500+ */+ release?: string;+ /** Filter by exact exception fingerprint hash, not fuzzy search. */+ fingerprint?: string | string[];+ /**+ * Search user/email text.+ * @maxLength 500+ */+ user?: string;+ /** Filter by exact PostHog person UUID. */+ personId?: string;+ /**+ * Filter by current URL substring.+ * @maxLength 1000+ */+ url?: string;+ /**+ * Search stack-frame source/file path text.+ * @maxLength 1000+ */+ filePath?: string;+ }++ export interface ErrorTrackingIssuesListResponse {+ /** Issue rows. */+ results: ErrorTrackingIssueListItem[];+ /** Whether more results are available. */+ hasMore: boolean;+ /** Page size. */+ limit: number;+ /** Current offset. */+ offset: number;+ /** Offset to fetch the next page when hasMore is true. */+ nextOffset?: number;+ }+export type ErrorTrackingRecommendationMeta = { [key: string]: unknown };export interface ErrorTrackingRecommendation {@@ -33776,57 +34256,6 @@ export namespace Schemas {readonly available_setup_task_ids: readonly AvailableSetupTaskIdsEnum[];}- /**- * * `exact` - exact- * `is_not` - is_not- * `icontains` - icontains- * `not_icontains` - not_icontains- * `regex` - regex- * `not_regex` - not_regex- * `gt` - gt- * `lt` - lt- * `gte` - gte- * `lte` - lte- * `is_set` - is_set- * `is_not_set` - is_not_set- * `is_date_exact` - is_date_exact- * `is_date_after` - is_date_after- * `is_date_before` - is_date_before- * `in` - in- * `not_in` - not_in- */- export type PropertyItemOperatorEnum = typeof PropertyItemOperatorEnum[keyof typeof PropertyItemOperatorEnum];--- export const PropertyItemOperatorEnum = {- Exact: 'exact',- IsNot: 'is_not',- Icontains: 'icontains',- NotIcontains: 'not_icontains',- Regex: 'regex',- NotRegex: 'not_regex',- Gt: 'gt',- Lt: 'lt',- Gte: 'gte',- Lte: 'lte',- IsSet: 'is_set',- IsNotSet: 'is_not_set',- IsDateExact: 'is_date_exact',- IsDateAfter: 'is_date_after',- IsDateBefore: 'is_date_before',- In: 'in',- NotIn: 'not_in',- } as const;-- export interface PropertyItem {- /** Key of the property you're filtering on. For example `email` or `$current_url` */- key: string;- /** Value of your filter. For example `[email protected]` or `https://example.com/test/`. Can be an array for an OR query, like `["[email protected]","[email protected]"]` */- value: string | number | boolean | (string | number)[];- operator?: PropertyItemOperatorEnum | BlankEnum | NullEnum | null;- type?: PropertyFilterTypeEnum | BlankEnum;- }-export interface Property {/**You can use a simplified version:diff --git a/services/mcp/src/generated/error_tracking/api.ts b/services/mcp/src/generated/error_tracking/api.tsindex 53316959aef2..10db012c0e9f 100644--- a/services/mcp/src/generated/error_tracking/api.ts+++ b/services/mcp/src/generated/error_tracking/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 14 enabled ops+ * PostHog API - MCP 15 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -1954,28 +1954,6 @@ export const ErrorTrackingGroupingRulesCreateBody = /* @__PURE__ */ zod.object({.describe('Optional human-readable description of what this grouping rule is for.'),})-export const ErrorTrackingIssuesListParams = /* @__PURE__ */ zod.object({- project_id: zod- .string()- .describe(- "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."- ),-})--export const ErrorTrackingIssuesListQueryParams = /* @__PURE__ */ zod.object({- limit: zod.number().optional().describe('Number of results to return per page.'),- offset: zod.number().optional().describe('The initial index from which to return the results.'),-})--export const ErrorTrackingIssuesRetrieveParams = /* @__PURE__ */ zod.object({- id: zod.string().describe('A UUID string identifying this error tracking issue.'),- 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 ErrorTrackingIssuesPartialUpdateParams = /* @__PURE__ */ zod.object({id: zod.string().describe('A UUID string identifying this error tracking issue.'),project_id: zod@@ -2062,6 +2040,454 @@ export const ErrorTrackingIssuesSplitCreateBody = /* @__PURE__ */ zod.object({.describe('Fingerprints to split into new issues. Each fingerprint becomes its own new issue.'),})+/**+ * Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional sparkline.+ * @summary Get compact error tracking issue details+ */+export const ErrorTrackingQueryIssueCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const errorTrackingQueryIssueCreateBodyFilterTestAccountsDefault = true+export const errorTrackingQueryIssueCreateBodyVolumeResolutionDefault = 0+export const errorTrackingQueryIssueCreateBodyVolumeResolutionMin = 0+export const errorTrackingQueryIssueCreateBodyVolumeResolutionMax = 200++export const errorTrackingQueryIssueCreateBodyIncludeSparklineDefault = false++export const ErrorTrackingQueryIssueCreateBody = /* @__PURE__ */ zod.object({+ issueId: zod.string().describe('Error tracking issue ID.'),+ dateRange: zod+ .object({+ date_from: zod+ .string()+ .optional()+ .describe('Start of the date range as an ISO timestamp or relative date such as -7d. Defaults to -7d.'),+ date_to: zod+ .string()+ .nullish()+ .describe('End of the date range as an ISO timestamp or relative date. Defaults to now when omitted.'),+ })+ .optional()+ .describe('Date range for issue impact and latest-event metadata. Defaults to the last 7 days.'),+ filterTestAccounts: zod+ .boolean()+ .default(errorTrackingQueryIssueCreateBodyFilterTestAccountsDefault)+ .describe('When true, exclude internal/test account data from results. Defaults to true.'),+ volumeResolution: zod+ .number()+ .min(errorTrackingQueryIssueCreateBodyVolumeResolutionMin)+ .max(errorTrackingQueryIssueCreateBodyVolumeResolutionMax)+ .default(errorTrackingQueryIssueCreateBodyVolumeResolutionDefault)+ .describe('Volume buckets. Maximum 200.'),+ includeSparkline: zod+ .boolean()+ .default(errorTrackingQueryIssueCreateBodyIncludeSparklineDefault)+ .describe('Set true to include a compact numeric occurrence sparkline. Defaults to false.'),+})++/**+ * Fetch sampled exception events, stack traces, browser/SDK context, URL, and $session_id values for one issue.+ * @summary List sampled exception events for an error tracking issue+ */+export const ErrorTrackingQueryIssueEventsCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const errorTrackingQueryIssueEventsCreateBodyFilterTestAccountsDefault = true+export const errorTrackingQueryIssueEventsCreateBodyFilterGroupItemOperatorDefault = `exact`+export const errorTrackingQueryIssueEventsCreateBodyFilterGroupItemTypeDefault = `event`+export const errorTrackingQueryIssueEventsCreateBodySearchQueryMax = 500++export const errorTrackingQueryIssueEventsCreateBodyOrderDirectionDefault = `DESC`+export const errorTrackingQueryIssueEventsCreateBodyLimitDefault = 1+export const errorTrackingQueryIssueEventsCreateBodyLimitMax = 20++export const errorTrackingQueryIssueEventsCreateBodyOffsetDefault = 0+export const errorTrackingQueryIssueEventsCreateBodyOffsetMin = 0++export const errorTrackingQueryIssueEventsCreateBodyVerbosityDefault = `summary`+export const errorTrackingQueryIssueEventsCreateBodyOnlyAppFramesDefault = true++export const ErrorTrackingQueryIssueEventsCreateBody = /* @__PURE__ */ zod.object({+ issueId: zod.string().describe('Error tracking issue ID.'),+ dateRange: zod+ .object({+ date_from: zod+ .string()+ .optional()+ .describe('Start of the date range as an ISO timestamp or relative date such as -7d. Defaults to -7d.'),+ date_to: zod+ .string()+ .nullish()+ .describe('End of the date range as an ISO timestamp or relative date. Defaults to now when omitted.'),+ })+ .optional()+ .describe('Date range for sampled exception events. Defaults to the last 7 days.'),+ filterTestAccounts: zod+ .boolean()+ .default(errorTrackingQueryIssueEventsCreateBodyFilterTestAccountsDefault)+ .describe('When true, exclude internal/test account data from results. Defaults to true.'),+ filterGroup: zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe("Key of the property you're filtering on. For example `email` or `$current_url`"),+ value: zod+ .union([+ zod.string(),+ zod.number(),+ zod.boolean(),+ zod.array(zod.union([zod.string(), zod.number()])),+ ])+ .describe(+ 'Value of your filter. For example `[email protected]` or `https://example.com/test/`. Can be an array for an OR query, like `["[email protected]","[email protected]"]`'+ ),+ operator: zod+ .union([+ zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'regex',+ 'not_regex',+ 'gt',+ 'lt',+ 'gte',+ 'lte',+ 'is_set',+ 'is_not_set',+ 'is_date_exact',+ 'is_date_after',+ 'is_date_before',+ 'in',+ 'not_in',+ ])+ .describe(+ '* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `gte` - gte\n* `lte` - lte\n* `is_set` - is_set\n* `is_not_set` - is_not_set\n* `is_date_exact` - is_date_exact\n* `is_date_after` - is_date_after\n* `is_date_before` - is_date_before\n* `in` - in\n* `not_in` - not_in'+ ),+ zod.enum(['']),+ zod.literal(null),+ ])+ .default(errorTrackingQueryIssueEventsCreateBodyFilterGroupItemOperatorDefault),+ type: zod+ .union([+ zod+ .enum([+ 'event',+ 'event_metadata',+ 'feature',+ 'person',+ 'cohort',+ 'element',+ 'static-cohort',+ 'dynamic-cohort',+ 'precalculated-cohort',+ 'group',+ 'recording',+ 'log_entry',+ 'behavioral',+ 'session',+ 'hogql',+ 'data_warehouse',+ 'data_warehouse_person_property',+ 'error_tracking_issue',+ 'log',+ 'log_attribute',+ 'log_resource_attribute',+ 'span',+ 'span_attribute',+ 'span_resource_attribute',+ 'revenue_analytics',+ 'flag',+ 'workflow_variable',+ ])+ .describe(+ '* `event` - event\n* `event_metadata` - event_metadata\n* `feature` - feature\n* `person` - person\n* `cohort` - cohort\n* `element` - element\n* `static-cohort` - static-cohort\n* `dynamic-cohort` - dynamic-cohort\n* `precalculated-cohort` - precalculated-cohort\n* `group` - group\n* `recording` - recording\n* `log_entry` - log_entry\n* `behavioral` - behavioral\n* `session` - session\n* `hogql` - hogql\n* `data_warehouse` - data_warehouse\n* `data_warehouse_person_property` - data_warehouse_person_property\n* `error_tracking_issue` - error_tracking_issue\n* `log` - log\n* `log_attribute` - log_attribute\n* `log_resource_attribute` - log_resource_attribute\n* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute\n* `revenue_analytics` - revenue_analytics\n* `flag` - flag\n* `workflow_variable` - workflow_variable'+ ),+ zod.enum(['']),+ ])+ .default(errorTrackingQueryIssueEventsCreateBodyFilterGroupItemTypeDefault),+ })+ )+ .optional()+ .describe('Advanced flat AND property filters applied to sampled events. HogQL filters are rejected.'),+ searchQuery: zod+ .string()+ .max(errorTrackingQueryIssueEventsCreateBodySearchQueryMax)+ .optional()+ .describe('Search exception types, exception values, and current URL among sampled events.'),+ orderDirection: zod+ .enum(['ASC', 'DESC'])+ .describe('* `ASC` - ASC\n* `DESC` - DESC')+ .default(errorTrackingQueryIssueEventsCreateBodyOrderDirectionDefault)+ .describe('Timestamp sort direction. Defaults to DESC.\n\n* `ASC` - ASC\n* `DESC` - DESC'),+ limit: zod+ .number()+ .min(1)+ .max(errorTrackingQueryIssueEventsCreateBodyLimitMax)+ .default(errorTrackingQueryIssueEventsCreateBodyLimitDefault)+ .describe('Page size.'),+ offset: zod+ .number()+ .min(errorTrackingQueryIssueEventsCreateBodyOffsetMin)+ .default(errorTrackingQueryIssueEventsCreateBodyOffsetDefault)+ .describe('Pagination offset.'),+ verbosity: zod+ .enum(['summary', 'stack', 'raw'])+ .describe('* `summary` - summary\n* `stack` - stack\n* `raw` - raw')+ .default(errorTrackingQueryIssueEventsCreateBodyVerbosityDefault)+ .describe(+ 'Controls exception detail size: summary, stack, or raw. Defaults to summary.\n\n* `summary` - summary\n* `stack` - stack\n* `raw` - raw'+ ),+ onlyAppFrames: zod+ .boolean()+ .default(errorTrackingQueryIssueEventsCreateBodyOnlyAppFramesDefault)+ .describe('When true, include only stack frames marked in_app. Defaults to true.'),+})++/**+ * List error tracking issues with typed filters and compact aggregate counts.+ * @summary List compact error tracking issues+ */+export const ErrorTrackingQueryIssuesListCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const errorTrackingQueryIssuesListCreateBodyStatusDefault = `active`+export const errorTrackingQueryIssuesListCreateBodyFilterTestAccountsDefault = true+export const errorTrackingQueryIssuesListCreateBodySearchQueryMax = 500++export const errorTrackingQueryIssuesListCreateBodyFilterGroupItemOperatorDefault = `exact`+export const errorTrackingQueryIssuesListCreateBodyFilterGroupItemTypeDefault = `event`+export const errorTrackingQueryIssuesListCreateBodyOrderByDefault = `occurrences`+export const errorTrackingQueryIssuesListCreateBodyOrderDirectionDefault = `DESC`+export const errorTrackingQueryIssuesListCreateBodyLimitDefault = 25+export const errorTrackingQueryIssuesListCreateBodyLimitMax = 100++export const errorTrackingQueryIssuesListCreateBodyOffsetDefault = 0+export const errorTrackingQueryIssuesListCreateBodyOffsetMin = 0++export const errorTrackingQueryIssuesListCreateBodyVolumeResolutionDefault = 0+export const errorTrackingQueryIssuesListCreateBodyVolumeResolutionMin = 0+export const errorTrackingQueryIssuesListCreateBodyVolumeResolutionMax = 200++export const errorTrackingQueryIssuesListCreateBodyReleaseMax = 500++export const errorTrackingQueryIssuesListCreateBodyUserMax = 500++export const errorTrackingQueryIssuesListCreateBodyUrlMax = 1000++export const errorTrackingQueryIssuesListCreateBodyFilePathMax = 1000++export const ErrorTrackingQueryIssuesListCreateBody = /* @__PURE__ */ zod.object({+ dateRange: zod+ .object({+ date_from: zod+ .string()+ .optional()+ .describe('Start of the date range as an ISO timestamp or relative date such as -7d. Defaults to -7d.'),+ date_to: zod+ .string()+ .nullish()+ .describe('End of the date range as an ISO timestamp or relative date. Defaults to now when omitted.'),+ })+ .optional()+ .describe('Date range for issue aggregates. Defaults to the last 7 days.'),+ status: zod+ .enum(['archived', 'active', 'resolved', 'pending_release', 'suppressed', 'all'])+ .describe(+ '* `archived` - archived\n* `active` - active\n* `resolved` - resolved\n* `pending_release` - pending_release\n* `suppressed` - suppressed\n* `all` - all'+ )+ .default(errorTrackingQueryIssuesListCreateBodyStatusDefault)+ .describe(+ 'Filter by issue status. Defaults to active.\n\n* `archived` - archived\n* `active` - active\n* `resolved` - resolved\n* `pending_release` - pending_release\n* `suppressed` - suppressed\n* `all` - all'+ ),+ assignee: zod+ .object({+ id: zod.union([zod.string(), zod.number()]).describe('User ID or role UUID to filter by.'),+ type: zod+ .enum(['user', 'role'])+ .describe('* `user` - user\n* `role` - role')+ .describe('Assignee target type: user or role.\n\n* `user` - user\n* `role` - role'),+ })+ .nullish()+ .describe('Filter by issue assignee. Omit to include all assignees.'),+ filterTestAccounts: zod+ .boolean()+ .default(errorTrackingQueryIssuesListCreateBodyFilterTestAccountsDefault)+ .describe('When true, exclude internal/test account data from results. Defaults to true.'),+ searchQuery: zod+ .string()+ .max(errorTrackingQueryIssuesListCreateBodySearchQueryMax)+ .optional()+ .describe('Free-text search across exception types, values, stack frames, and email fields.'),+ filterGroup: zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe("Key of the property you're filtering on. For example `email` or `$current_url`"),+ value: zod+ .union([+ zod.string(),+ zod.number(),+ zod.boolean(),+ zod.array(zod.union([zod.string(), zod.number()])),+ ])+ .describe(+ 'Value of your filter. For example `[email protected]` or `https://example.com/test/`. Can be an array for an OR query, like `["[email protected]","[email protected]"]`'+ ),+ operator: zod+ .union([+ zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'regex',+ 'not_regex',+ 'gt',+ 'lt',+ 'gte',+ 'lte',+ 'is_set',+ 'is_not_set',+ 'is_date_exact',+ 'is_date_after',+ 'is_date_before',+ 'in',+ 'not_in',+ ])+ .describe(+ '* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `gte` - gte\n* `lte` - lte\n* `is_set` - is_set\n* `is_not_set` - is_not_set\n* `is_date_exact` - is_date_exact\n* `is_date_after` - is_date_after\n* `is_date_before` - is_date_before\n* `in` - in\n* `not_in` - not_in'+ ),+ zod.enum(['']),+ zod.literal(null),+ ])+ .default(errorTrackingQueryIssuesListCreateBodyFilterGroupItemOperatorDefault),+ type: zod+ .union([+ zod+ .enum([+ 'event',+ 'event_metadata',+ 'feature',+ 'person',+ 'cohort',+ 'element',+ 'static-cohort',+ 'dynamic-cohort',+ 'precalculated-cohort',+ 'group',+ 'recording',+ 'log_entry',+ 'behavioral',+ 'session',+ 'hogql',+ 'data_warehouse',+ 'data_warehouse_person_property',+ 'error_tracking_issue',+ 'log',+ 'log_attribute',+ 'log_resource_attribute',+ 'span',+ 'span_attribute',+ 'span_resource_attribute',+ 'revenue_analytics',+ 'flag',+ 'workflow_variable',+ ])+ .describe(+ '* `event` - event\n* `event_metadata` - event_metadata\n* `feature` - feature\n* `person` - person\n* `cohort` - cohort\n* `element` - element\n* `static-cohort` - static-cohort\n* `dynamic-cohort` - dynamic-cohort\n* `precalculated-cohort` - precalculated-cohort\n* `group` - group\n* `recording` - recording\n* `log_entry` - log_entry\n* `behavioral` - behavioral\n* `session` - session\n* `hogql` - hogql\n* `data_warehouse` - data_warehouse\n* `data_warehouse_person_property` - data_warehouse_person_property\n* `error_tracking_issue` - error_tracking_issue\n* `log` - log\n* `log_attribute` - log_attribute\n* `log_resource_attribute` - log_resource_attribute\n* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute\n* `revenue_analytics` - revenue_analytics\n* `flag` - flag\n* `workflow_variable` - workflow_variable'+ ),+ zod.enum(['']),+ ])+ .default(errorTrackingQueryIssuesListCreateBodyFilterGroupItemTypeDefault),+ })+ )+ .optional()+ .describe(+ 'Advanced flat AND property filters. Prefer typed shortcut fields when they fit. HogQL filters are rejected.'+ ),+ orderBy: zod+ .enum(['last_seen', 'first_seen', 'occurrences', 'users', 'sessions'])+ .describe(+ '* `last_seen` - last_seen\n* `first_seen` - first_seen\n* `occurrences` - occurrences\n* `users` - users\n* `sessions` - sessions'+ )+ .default(errorTrackingQueryIssuesListCreateBodyOrderByDefault)+ .describe(+ 'Field used to sort issues. Defaults to occurrences.\n\n* `last_seen` - last_seen\n* `first_seen` - first_seen\n* `occurrences` - occurrences\n* `users` - users\n* `sessions` - sessions'+ ),+ orderDirection: zod+ .enum(['ASC', 'DESC'])+ .describe('* `ASC` - ASC\n* `DESC` - DESC')+ .default(errorTrackingQueryIssuesListCreateBodyOrderDirectionDefault)+ .describe('Sort direction. Defaults to DESC.\n\n* `ASC` - ASC\n* `DESC` - DESC'),+ limit: zod+ .number()+ .min(1)+ .max(errorTrackingQueryIssuesListCreateBodyLimitMax)+ .default(errorTrackingQueryIssuesListCreateBodyLimitDefault)+ .describe('Page size.'),+ offset: zod+ .number()+ .min(errorTrackingQueryIssuesListCreateBodyOffsetMin)+ .default(errorTrackingQueryIssuesListCreateBodyOffsetDefault)+ .describe('Pagination offset.'),+ volumeResolution: zod+ .number()+ .min(errorTrackingQueryIssuesListCreateBodyVolumeResolutionMin)+ .max(errorTrackingQueryIssuesListCreateBodyVolumeResolutionMax)+ .default(errorTrackingQueryIssuesListCreateBodyVolumeResolutionDefault)+ .describe('Number of volume buckets. Defaults to 0 for compact aggregate counts.'),+ library: zod+ .union([zod.string(), zod.array(zod.string()).min(1)])+ .optional()+ .describe('Filter by SDK/library value from event $lib, for example posthog-js.'),+ release: zod+ .string()+ .max(errorTrackingQueryIssuesListCreateBodyReleaseMax)+ .optional()+ .describe('Filter by exact release ID, version, or git commit ID captured in $exception_releases.'),+ fingerprint: zod+ .union([zod.string(), zod.array(zod.string()).min(1)])+ .optional()+ .describe('Filter by exact exception fingerprint hash, not fuzzy search.'),+ user: zod+ .string()+ .max(errorTrackingQueryIssuesListCreateBodyUserMax)+ .optional()+ .describe('Search user/email text.'),+ personId: zod.string().optional().describe('Filter by exact PostHog person UUID.'),+ url: zod+ .string()+ .max(errorTrackingQueryIssuesListCreateBodyUrlMax)+ .optional()+ .describe('Filter by current URL substring.'),+ filePath: zod+ .string()+ .max(errorTrackingQueryIssuesListCreateBodyFilePathMax)+ .optional()+ .describe('Search stack-frame source/file path text.'),+})+export const ErrorTrackingSuppressionRulesListParams = /* @__PURE__ */ zod.object({project_id: zod.string()diff --git a/services/mcp/src/tools/generated/error_tracking.ts b/services/mcp/src/tools/generated/error_tracking.tsindex f9a1cc726c4a..b99785246832 100644--- a/services/mcp/src/tools/generated/error_tracking.ts+++ b/services/mcp/src/tools/generated/error_tracking.ts@@ -6,14 +6,15 @@ import {ErrorTrackingAssignmentRulesCreateBody,ErrorTrackingAssignmentRulesListQueryParams,ErrorTrackingGroupingRulesCreateBody,- ErrorTrackingIssuesListQueryParams,ErrorTrackingIssuesMergeCreateBody,ErrorTrackingIssuesMergeCreateParams,ErrorTrackingIssuesPartialUpdateBody,ErrorTrackingIssuesPartialUpdateParams,- ErrorTrackingIssuesRetrieveParams,ErrorTrackingIssuesSplitCreateBody,ErrorTrackingIssuesSplitCreateParams,+ ErrorTrackingQueryIssueCreateBody,+ ErrorTrackingQueryIssueEventsCreateBody,+ ErrorTrackingQueryIssuesListCreateBody,ErrorTrackingSuppressionRulesCreateBody,ErrorTrackingSuppressionRulesListQueryParams,ErrorTrackingSymbolSetsDownloadRetrieveParams,@@ -21,7 +22,6 @@ import {ErrorTrackingSymbolSetsRetrieveParams,} from '@/generated/error_tracking/api'import { withUiApp } from '@/resources/ui-apps'-import { createQueryWrapper } from '@/tools/query-wrapper-factory'import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'@@ -121,46 +121,6 @@ const errorTrackingGroupingRulesList = (): ToolBase<},})-const ErrorTrackingIssuesListSchema = ErrorTrackingIssuesListQueryParams--const errorTrackingIssuesList = (): ToolBase<- typeof ErrorTrackingIssuesListSchema,- WithPostHogUrl<Schemas.PaginatedErrorTrackingIssueFullList>-> =>- withUiApp('error-issue-list', {- name: 'error-tracking-issues-list',- schema: ErrorTrackingIssuesListSchema,- handler: async (context: Context, params: z.infer<typeof ErrorTrackingIssuesListSchema>) => {- const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<Schemas.PaginatedErrorTrackingIssueFullList>({- method: 'GET',- path: `/api/environments/${encodeURIComponent(String(projectId))}/error_tracking/issues/`,- query: {- limit: params.limit,- offset: params.offset,- },- })- const filtered = {- ...result,- results: (result.results ?? []).map((item: any) =>- pickResponseFields(item, ['id', 'status', 'name', 'first_seen', 'assignee'])- ),- } as typeof result- return await withPostHogUrl(- context,- {- ...filtered,- results: await Promise.all(- (filtered.results ?? []).map((item) =>- withPostHogUrl(context, item, `/error_tracking/${item.id}`)- )- ),- },- '/error_tracking'- )- },- })-const ErrorTrackingIssuesMergeCreateSchema = ErrorTrackingIssuesMergeCreateParams.omit({ project_id: true }).extend(ErrorTrackingIssuesMergeCreateBody.shape)@@ -227,25 +187,6 @@ const errorTrackingIssuesPartialUpdate = (): ToolBase<},})-const ErrorTrackingIssuesRetrieveSchema = ErrorTrackingIssuesRetrieveParams.omit({ project_id: true })--const errorTrackingIssuesRetrieve = (): ToolBase<- typeof ErrorTrackingIssuesRetrieveSchema,- WithPostHogUrl<Schemas.ErrorTrackingIssueFull>-> =>- withUiApp('error-issue', {- name: 'error-tracking-issues-retrieve',- schema: ErrorTrackingIssuesRetrieveSchema,- handler: async (context: Context, params: z.infer<typeof ErrorTrackingIssuesRetrieveSchema>) => {- const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<Schemas.ErrorTrackingIssueFull>({- method: 'GET',- path: `/api/environments/${encodeURIComponent(String(projectId))}/error_tracking/issues/${encodeURIComponent(String(params.id))}/`,- })- return await withPostHogUrl(context, result, `/error_tracking/${result.id}`)- },- })-const ErrorTrackingIssuesSplitCreateSchema = ErrorTrackingIssuesSplitCreateParams.omit({ project_id: true }).extend(ErrorTrackingIssuesSplitCreateBody.shape)@@ -405,350 +346,210 @@ const errorTrackingSymbolSetsRetrieve = (): ToolBase<},})-// --- Query wrapper schemas from schema.json -----const integer = z.coerce.number().int()--const ErrorTrackingIssueAssigneeType = z.enum(['user', 'role'])--const ErrorTrackingIssueAssignee = z.object({- id: z.union([integer, z.string()]),- type: ErrorTrackingIssueAssigneeType,-})--const DateRange = z.object({- date_from: z- .string()- .nullable()- .describe(- 'Start of the date range. Accepts ISO 8601 timestamps (e.g., 2024-01-15T00:00:00Z) or relative formats: -7d (7 days ago), -2w (2 weeks ago), -1m (1 month ago),\n-1h (1 hour ago), -1mStart (start of last month), -1yStart (start of last year).'- )- .optional(),- date_to: z- .string()- .nullable()- .describe('End of the date range. Same format as date_from. Omit or null for "now".')- .optional(),- explicitDate: z.coerce- .boolean()- .nullable()- .describe(- 'Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period.'- )- .default(false)- .optional(),-})--const AssistantStringOrBooleanValuePropertyFilterOperator = z.enum([- 'exact',- 'is_not',- 'icontains',- 'not_icontains',- 'regex',- 'not_regex',-])--const AssistantGenericPropertyFilterType = z.enum(['event', 'person', 'session', 'feature'])+const QueryErrorTrackingIssueSchema = ErrorTrackingQueryIssueCreateBody-const AssistantNumericValuePropertyFilterOperator = z.enum(['exact', 'gt', 'lt'])--const AssistantArrayPropertyFilterOperator = z.enum(['exact', 'is_not'])+const queryErrorTrackingIssue = (): ToolBase<+ typeof QueryErrorTrackingIssueSchema,+ WithPostHogUrl<Schemas.ErrorTrackingIssueDetail>+> =>+ withUiApp('error-issue', {+ name: 'query-error-tracking-issue',+ schema: QueryErrorTrackingIssueSchema,+ handler: async (context: Context, params: z.infer<typeof QueryErrorTrackingIssueSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.issueId !== undefined) {+ body['issueId'] = params.issueId+ }+ if (params.dateRange !== undefined) {+ body['dateRange'] = params.dateRange+ }+ if (params.filterTestAccounts !== undefined) {+ body['filterTestAccounts'] = params.filterTestAccounts+ }+ if (params.volumeResolution !== undefined) {+ body['volumeResolution'] = params.volumeResolution+ }+ if (params.includeSparkline !== undefined) {+ body['includeSparkline'] = params.includeSparkline+ }+ const result = await context.api.request<Schemas.ErrorTrackingIssueDetail>({+ method: 'POST',+ path: `/api/environments/${encodeURIComponent(String(projectId))}/error_tracking/query/issue/`,+ body,+ })+ return await withPostHogUrl(context, result, `/error_tracking/${params.issueId}`)+ },+ })-const AssistantDateTimePropertyFilterOperator = z.enum(['is_date_exact', 'is_date_before', 'is_date_after'])+const QueryErrorTrackingIssueEventsSchema = ErrorTrackingQueryIssueEventsCreateBody-const AssistantSetPropertyFilterOperator = z.enum(['is_set', 'is_not_set'])+const queryErrorTrackingIssueEvents = (): ToolBase<+ typeof QueryErrorTrackingIssueEventsSchema,+ WithPostHogUrl<Schemas.ErrorTrackingIssueEventsResponse>+> =>+ withUiApp('error-details', {+ name: 'query-error-tracking-issue-events',+ schema: QueryErrorTrackingIssueEventsSchema,+ handler: async (context: Context, params: z.infer<typeof QueryErrorTrackingIssueEventsSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.issueId !== undefined) {+ body['issueId'] = params.issueId+ }+ if (params.dateRange !== undefined) {+ body['dateRange'] = params.dateRange+ }+ if (params.filterTestAccounts !== undefined) {+ body['filterTestAccounts'] = params.filterTestAccounts+ }+ if (params.filterGroup !== undefined) {+ body['filterGroup'] = params.filterGroup+ }+ if (params.searchQuery !== undefined) {+ body['searchQuery'] = params.searchQuery+ }+ if (params.orderDirection !== undefined) {+ body['orderDirection'] = params.orderDirection+ }+ if (params.limit !== undefined) {+ body['limit'] = params.limit+ }+ if (params.offset !== undefined) {+ body['offset'] = params.offset+ }+ if (params.verbosity !== undefined) {+ body['verbosity'] = params.verbosity+ }+ if (params.onlyAppFrames !== undefined) {+ body['onlyAppFrames'] = params.onlyAppFrames+ }+ const result = await context.api.request<Schemas.ErrorTrackingIssueEventsResponse>({+ method: 'POST',+ path: `/api/environments/${encodeURIComponent(String(projectId))}/error_tracking/query/issue_events/`,+ body,+ })+ return await withPostHogUrl(context, result, `/error_tracking/${params.issueId}`)+ },+ })-const AssistantGenericPropertyFilter = z.union([- z.object({- key: z.string().describe('Use one of the properties the user has provided in the plan.'),- operator: AssistantStringOrBooleanValuePropertyFilterOperator.describe(- '`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.'- ),- type: AssistantGenericPropertyFilterType,- value: z- .string()- .describe(- 'Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.'- ),- }),- z.object({- key: z.string().describe('Use one of the properties the user has provided in the plan.'),- operator: AssistantNumericValuePropertyFilterOperator,- type: AssistantGenericPropertyFilterType,- value: z.coerce.number(),- }),- z.object({- key: z.string().describe('Use one of the properties the user has provided in the plan.'),- operator: AssistantArrayPropertyFilterOperator.describe(- '`exact` - exact match of any of the values. `is_not` - does not match any of the values.'- ),- type: AssistantGenericPropertyFilterType,- value: z- .array(z.string())- .describe(- 'Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string "true" or "false".'- ),- }),- z.object({- key: z.string().describe('Use one of the properties the user has provided in the plan.'),- operator: AssistantDateTimePropertyFilterOperator,- type: AssistantGenericPropertyFilterType,- value: z.string().describe('Value must be a date in ISO 8601 format.'),- }),- z.object({- key: z.string().describe('Use one of the properties the user has provided in the plan.'),- operator: AssistantSetPropertyFilterOperator.describe(- "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected."- ),- type: AssistantGenericPropertyFilterType,- }),-])--const AssistantGroupPropertyFilter = z.union([- z.object({- group_type_index: integer.describe('Index of the group type from the group mapping.'),- key: z.string().describe('Use one of the properties the user has provided in the plan.'),- operator: AssistantStringOrBooleanValuePropertyFilterOperator.describe(- '`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.'- ),- type: z.literal('group').default('group'),- value: z- .string()- .describe(- 'Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.'- ),- }),- z.object({- group_type_index: integer.describe('Index of the group type from the group mapping.'),- key: z.string().describe('Use one of the properties the user has provided in the plan.'),- operator: AssistantNumericValuePropertyFilterOperator,- type: z.literal('group').default('group'),- value: z.coerce.number(),- }),- z.object({- group_type_index: integer.describe('Index of the group type from the group mapping.'),- key: z.string().describe('Use one of the properties the user has provided in the plan.'),- operator: AssistantArrayPropertyFilterOperator.describe(- '`exact` - exact match of any of the values. `is_not` - does not match any of the values.'- ),- type: z.literal('group').default('group'),- value: z- .array(z.string())- .describe(- 'Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string "true" or "false".'- ),- }),- z.object({- group_type_index: integer.describe('Index of the group type from the group mapping.'),- key: z.string().describe('Use one of the properties the user has provided in the plan.'),- operator: AssistantDateTimePropertyFilterOperator,- type: z.literal('group').default('group'),- value: z.string().describe('Value must be a date in ISO 8601 format.'),- }),- z.object({- group_type_index: integer.describe('Index of the group type from the group mapping.'),- key: z.string().describe('Use one of the properties the user has provided in the plan.'),- operator: AssistantSetPropertyFilterOperator.describe(- "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected."- ),- type: z.literal('group').default('group'),- }),-])--const AssistantCohortPropertyFilter = z.object({- key: z.literal('id').default('id'),- operator: z.literal('in').default('in'),- type: z- .literal('cohort')- .describe(- 'Filter events by cohort membership. Use this to narrow down results to persons belonging to a specific cohort. Example: `{ type: "cohort", key: "id", value: 42, operator: "in" }`'- )- .default('cohort'),- value: integer.describe('The cohort ID to filter by.'),-})+const QueryErrorTrackingIssuesListSchema = ErrorTrackingQueryIssuesListCreateBody-const AssistantElementPropertyFilter = z.union([- z.object({- key: z- .enum(['tag_name', 'text', 'href', 'selector'])- .describe(- 'The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).'- ),- operator: AssistantStringOrBooleanValuePropertyFilterOperator.describe(- '`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.'- ),- type: z- .literal('element')- .describe(- 'Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: "element", key: "text", value: "Sign Up", operator: "exact" }`'- )- .default('element'),- value: z- .string()- .describe(- 'Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.'- ),- }),- z.object({- key: z- .enum(['tag_name', 'text', 'href', 'selector'])- .describe(- 'The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).'- ),- operator: AssistantNumericValuePropertyFilterOperator,- type: z- .literal('element')- .describe(- 'Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: "element", key: "text", value: "Sign Up", operator: "exact" }`'- )- .default('element'),- value: z.coerce.number(),- }),- z.object({- key: z- .enum(['tag_name', 'text', 'href', 'selector'])- .describe(- 'The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).'- ),- operator: AssistantArrayPropertyFilterOperator.describe(- '`exact` - exact match of any of the values. `is_not` - does not match any of the values.'- ),- type: z- .literal('element')- .describe(- 'Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: "element", key: "text", value: "Sign Up", operator: "exact" }`'- )- .default('element'),- value: z- .array(z.string())- .describe(- 'Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string "true" or "false".'- ),- }),- z.object({- key: z- .enum(['tag_name', 'text', 'href', 'selector'])- .describe(- 'The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).'- ),- operator: AssistantDateTimePropertyFilterOperator,- type: z- .literal('element')- .describe(- 'Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: "element", key: "text", value: "Sign Up", operator: "exact" }`'- )- .default('element'),- value: z.string().describe('Value must be a date in ISO 8601 format.'),- }),- z.object({- key: z- .enum(['tag_name', 'text', 'href', 'selector'])- .describe(- 'The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).'- ),- operator: AssistantSetPropertyFilterOperator.describe(- "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected."- ),- type: z- .literal('element')- .describe(- 'Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: "element", key: "text", value: "Sign Up", operator: "exact" }`'+const queryErrorTrackingIssuesList = (): ToolBase<+ typeof QueryErrorTrackingIssuesListSchema,+ WithPostHogUrl<Schemas.ErrorTrackingIssuesListResponse>+> =>+ withUiApp('error-issue-list', {+ name: 'query-error-tracking-issues-list',+ schema: QueryErrorTrackingIssuesListSchema,+ handler: async (context: Context, params: z.infer<typeof QueryErrorTrackingIssuesListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.dateRange !== undefined) {+ body['dateRange'] = params.dateRange+ }+ if (params.status !== undefined) {+ body['status'] = params.status+ }+ if (params.assignee !== undefined) {+ body['assignee'] = params.assignee+ }+ if (params.filterTestAccounts !== undefined) {+ body['filterTestAccounts'] = params.filterTestAccounts+ }+ if (params.searchQuery !== undefined) {+ body['searchQuery'] = params.searchQuery+ }+ if (params.filterGroup !== undefined) {+ body['filterGroup'] = params.filterGroup+ }+ if (params.orderBy !== undefined) {+ body['orderBy'] = params.orderBy+ }+ if (params.orderDirection !== undefined) {+ body['orderDirection'] = params.orderDirection+ }+ if (params.limit !== undefined) {+ body['limit'] = params.limit+ }+ if (params.offset !== undefined) {+ body['offset'] = params.offset+ }+ if (params.volumeResolution !== undefined) {+ body['volumeResolution'] = params.volumeResolution+ }+ if (params.library !== undefined) {+ body['library'] = params.library+ }+ if (params.release !== undefined) {+ body['release'] = params.release+ }+ if (params.fingerprint !== undefined) {+ body['fingerprint'] = params.fingerprint+ }+ if (params.user !== undefined) {+ body['user'] = params.user+ }+ if (params.personId !== undefined) {+ body['personId'] = params.personId+ }+ if (params.url !== undefined) {+ body['url'] = params.url+ }+ if (params.filePath !== undefined) {+ body['filePath'] = params.filePath+ }+ const result = await context.api.request<Schemas.ErrorTrackingIssuesListResponse>({+ method: 'POST',+ path: `/api/environments/${encodeURIComponent(String(projectId))}/error_tracking/query/issues/`,+ body,+ })+ const filtered = {+ ...result,+ results: (result.results ?? []).map((item: any) =>+ pickResponseFields(item, [+ 'id',+ 'name',+ 'description',+ 'status',+ 'first_seen',+ 'last_seen',+ 'library',+ 'source',+ 'assignee',+ 'aggregations',+ ])+ ),+ } as typeof result+ return await withPostHogUrl(+ context,+ {+ ...filtered,+ results: await Promise.all(+ (filtered.results ?? []).map((item) =>+ withPostHogUrl(context, item, `/error_tracking/${item.id}`)+ )+ ),+ },+ '/error_tracking')- .default('element'),- }),-])--const AssistantHogQLPropertyFilter = z.object({- key: z- .string()- .describe(- "A HogQL boolean expression used as a filter condition.\n\nExamples:\n- Filter where a property exceeds a threshold: `toFloat(properties.load_time) > 5.0`\n- Filter with string matching: `properties.$current_url LIKE '%/pricing%'`\n- Filter with multiple conditions: `properties.$browser = 'Chrome' AND toFloat(properties.duration) > 30`"- ),- type: z- .literal('hogql')- .describe(- "Filter by a HogQL boolean expression for advanced filtering that can't be expressed with standard property filters."- )- .default('hogql'),-})--const AssistantFlagPropertyFilter = z.object({- key: z.string().describe('The feature flag key.'),- operator: z.literal('flag_evaluates_to').default('flag_evaluates_to'),- type: z- .literal('flag')- .describe(- 'Filter events by feature flag state — only include events where a specific flag evaluated to a given value. Examples:\n- Flag enabled: `{ type: "flag", key: "new-onboarding", operator: "flag_evaluates_to", value: true }`\n- Specific variant: `{ type: "flag", key: "checkout-experiment", operator: "flag_evaluates_to", value: "variant-a" }`'- )- .default('flag'),- value: z- .union([z.coerce.boolean(), z.string()])- .describe('`true`/`false` for boolean flags, or a variant name string for multivariate flags.'),-})--const AssistantPropertyFilter = z.union([- AssistantGenericPropertyFilter,- AssistantGroupPropertyFilter,- AssistantCohortPropertyFilter,- AssistantElementPropertyFilter,- AssistantHogQLPropertyFilter,- AssistantFlagPropertyFilter,-])--const ErrorTrackingOrderBy = z.enum(['last_seen', 'first_seen', 'occurrences', 'users', 'sessions'])--const ErrorTrackingIssueStatus = z.enum(['archived', 'active', 'resolved', 'pending_release', 'suppressed'])--const ErrorTrackingQueryStatus = z.union([ErrorTrackingIssueStatus, z.literal('all')])--const AssistantErrorTrackingQuery = z.object({- assignee: z.union([ErrorTrackingIssueAssignee, z.null()]).describe('Filter by assignee.').optional(),- dateRange: DateRange.describe('Date range to filter results.').optional(),- filterGroup: z.array(AssistantPropertyFilter).describe('Property filters for the query').default([]).optional(),- filterTestAccounts: z.coerce.boolean().describe('Whether to filter out test accounts.').optional(),- issueId: z.string().describe('Filter to a specific error tracking issue by ID.').optional(),- kind: z.literal('ErrorTrackingQuery').default('ErrorTrackingQuery'),- limit: integer.optional(),- offset: integer.optional(),- orderBy: ErrorTrackingOrderBy.describe('Field to sort results by.').optional(),- orderDirection: z.enum(['ASC', 'DESC']).describe('Sort direction.').optional(),- searchQuery: z.string().describe('Free-text search across exception type, message, and stack frames.').optional(),- status: ErrorTrackingQueryStatus.describe('Filter by issue status.').optional(),- volumeResolution: integer- .describe('Controls volume chart granularity. Use 1 for sparklines, 0 for counts only.')- .optional(),-})--const QueryErrorTrackingIssuesSchema = AssistantErrorTrackingQuery.extend({- limit: AssistantErrorTrackingQuery.shape.limit.default(50).optional(),- orderBy: AssistantErrorTrackingQuery.shape.orderBy.default('occurrences').optional(),- volumeResolution: AssistantErrorTrackingQuery.shape.volumeResolution.default(1).optional(),- dateRange: AssistantErrorTrackingQuery.shape.dateRange.default({ date_from: '-7d' }).optional(),- filterTestAccounts: AssistantErrorTrackingQuery.shape.filterTestAccounts.default(true).optional(),- status: AssistantErrorTrackingQuery.shape.status.default('active').optional(),- orderDirection: AssistantErrorTrackingQuery.shape.orderDirection.default('DESC').optional(),-})+ },+ })export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'error-tracking-assignment-rules-create': errorTrackingAssignmentRulesCreate,'error-tracking-assignment-rules-list': errorTrackingAssignmentRulesList,'error-tracking-grouping-rules-create': errorTrackingGroupingRulesCreate,'error-tracking-grouping-rules-list': errorTrackingGroupingRulesList,- 'error-tracking-issues-list': errorTrackingIssuesList,'error-tracking-issues-merge-create': errorTrackingIssuesMergeCreate,'error-tracking-issues-partial-update': errorTrackingIssuesPartialUpdate,- 'error-tracking-issues-retrieve': errorTrackingIssuesRetrieve,'error-tracking-issues-split-create': errorTrackingIssuesSplitCreate,'error-tracking-suppression-rules-create': errorTrackingSuppressionRulesCreate,'error-tracking-suppression-rules-list': errorTrackingSuppressionRulesList,'error-tracking-symbol-sets-download-retrieve': errorTrackingSymbolSetsDownloadRetrieve,'error-tracking-symbol-sets-list': errorTrackingSymbolSetsList,'error-tracking-symbol-sets-retrieve': errorTrackingSymbolSetsRetrieve,- 'query-error-tracking-issues': createQueryWrapper({- name: 'query-error-tracking-issues',- schema: QueryErrorTrackingIssuesSchema,- kind: 'ErrorTrackingQuery',- uiResourceUri: 'ui://posthog/error-issue-list.html',- urlPrefix: '/error_tracking',- }),+ 'query-error-tracking-issue': queryErrorTrackingIssue,+ 'query-error-tracking-issue-events': queryErrorTrackingIssueEvents,+ 'query-error-tracking-issues-list': queryErrorTrackingIssuesList,}diff --git a/services/mcp/src/ui-apps/apps/generated/error-issue-list.tsx b/services/mcp/src/ui-apps/apps/generated/error-issue-list.tsxindex 1568c7ba5fa3..10c316a56f37 100644--- a/services/mcp/src/ui-apps/apps/generated/error-issue-list.tsx+++ b/services/mcp/src/ui-apps/apps/generated/error-issue-list.tsx@@ -36,8 +36,8 @@ function ErrorIssueListContent({ data, app }: { data: ErrorIssueListData; app: A}try {const result = await app.callServerTool({- name: 'error-tracking-issues-retrieve',- arguments: { id: item.id },+ name: 'query-error-tracking-issue',+ arguments: { issueId: item.id },})if (result.isError || !result.structuredContent) {fallbackToChat(item.name)diff --git a/services/mcp/tests/integration/feature-routing.test.ts b/services/mcp/tests/integration/feature-routing.test.tsindex 1063f60083bd..b49b7c710ca9 100644--- a/services/mcp/tests/integration/feature-routing.test.ts+++ b/services/mcp/tests/integration/feature-routing.test.ts@@ -34,7 +34,7 @@ describe('Feature Routing Integration', () => {'dashboard-create','insights-list','organizations-list',- 'query-error-tracking-issues',+ 'query-error-tracking-issues-list',],},{diff --git a/services/mcp/tests/tools/errorTracking.integration.test.ts b/services/mcp/tests/tools/errorTracking.integration.test.tsindex 371a45d3db98..a8d829dcb363 100644--- a/services/mcp/tests/tools/errorTracking.integration.test.ts+++ b/services/mcp/tests/tools/errorTracking.integration.test.ts@@ -30,7 +30,9 @@ type ErrorTrackingSymbolSetListResult = {describe('Error Tracking', { concurrent: false }, () => {let context: Contextlet currentUserId: number- const queryTool = GENERATED_TOOLS['query-error-tracking-issues']!()+ const issuesListTool = GENERATED_TOOLS['query-error-tracking-issues-list']!()+ const issueTool = GENERATED_TOOLS['query-error-tracking-issue']!()+ const issueEventsTool = GENERATED_TOOLS['query-error-tracking-issue-events']!()const createdAssignmentRuleIds: string[] = []const createdGroupingRuleIds: string[] = []const createdSuppressionRuleIds: string[] = []@@ -93,7 +95,7 @@ describe('Error Tracking', { concurrent: false }, () => {})async function getIssueIds(limit: number = 2): Promise<string[]> {- const result = await queryTool.handler(context, { status: 'all', limit })+ const result = await issuesListTool.handler(context, { status: 'all', limit })const errors = parseToolResponse(result) as ErrorTrackingIssueListResultif (!Array.isArray(errors.results)) {@@ -130,9 +132,9 @@ describe('Error Tracking', { concurrent: false }, () => {.filter((fingerprint: string | null | undefined): fingerprint is string => typeof fingerprint === 'string')}- describe('query-error-tracking-issues tool', () => {+ describe('query-error-tracking-issues-list tool', () => {it('should list errors with default parameters', async () => {- const result = await queryTool.handler(context, {})+ const result = await issuesListTool.handler(context, {})const errorData = parseToolResponse(result)expect(Array.isArray(errorData.results)).toBe(true)@@ -142,7 +144,7 @@ describe('Error Tracking', { concurrent: false }, () => {const dateFrom = new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString()const dateTo = new Date().toISOString()- const result = await queryTool.handler(context, {+ const result = await issuesListTool.handler(context, {dateRange: { date_from: dateFrom, date_to: dateTo },orderBy: 'occurrences',orderDirection: 'DESC',@@ -153,7 +155,7 @@ describe('Error Tracking', { concurrent: false }, () => {})it('should filter by status', async () => {- const result = await queryTool.handler(context, {+ const result = await issuesListTool.handler(context, {status: 'active',})const errorData = parseToolResponse(result)@@ -162,7 +164,7 @@ describe('Error Tracking', { concurrent: false }, () => {})it('should handle empty results', async () => {- const result = await queryTool.handler(context, {+ const result = await issuesListTool.handler(context, {dateRange: {date_from: new Date(Date.now() - 60000).toISOString(),date_to: new Date(Date.now() - 30000).toISOString(),@@ -173,31 +175,34 @@ describe('Error Tracking', { concurrent: false }, () => {expect(Array.isArray(errorData.results)).toBe(true)})- it('should get error details by issue ID', async () => {- const testIssueId = '00000000-0000-0000-0000-000000000000'+ it('should get error details by issue ID when data exists', async () => {+ const issueId = await getFirstIssueId()+ if (!issueId) {+ return+ }- const result = await queryTool.handler(context, {- issueId: testIssueId,+ const result = await issueTool.handler(context, {+ issueId,volumeResolution: 0,})const errorDetails = parseToolResponse(result)- expect(Array.isArray(errorDetails.results)).toBe(true)+ expect(errorDetails.id).toBe(issueId)})- it('should get error details with custom date range', async () => {- const testIssueId = '00000000-0000-0000-0000-000000000000'- const dateFrom = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()- const dateTo = new Date().toISOString()+ it('should get issue events when data exists', async () => {+ const issueId = await getFirstIssueId()+ if (!issueId) {+ return+ }- const result = await queryTool.handler(context, {- issueId: testIssueId,- volumeResolution: 0,- dateRange: { date_from: dateFrom, date_to: dateTo },+ const result = await issueEventsTool.handler(context, {+ issueId,+ limit: 1,})- const errorDetails = parseToolResponse(result)+ const eventData = parseToolResponse(result)- expect(Array.isArray(errorDetails.results)).toBe(true)+ expect(Array.isArray(eventData.results)).toBe(true)})})@@ -228,7 +233,7 @@ describe('Error Tracking', { concurrent: false }, () => {type: 'AND',values: [{- key: '$exception_type',+ key: '$exception_types',type: 'event',value: ['TypeError'],operator: 'exact',@@ -274,7 +279,7 @@ describe('Error Tracking', { concurrent: false }, () => {type: 'AND',values: [{- key: '$exception_type',+ key: '$exception_types',type: 'event',value: ['TypeError'],operator: 'exact',@@ -329,7 +334,7 @@ describe('Error Tracking', { concurrent: false }, () => {type: 'AND',values: [{- key: '$exception_type',+ key: '$exception_types',type: 'event',value: ['TypeError'],operator: 'exact',@@ -500,39 +505,27 @@ describe('Error Tracking', { concurrent: false }, () => {describe('Error tracking workflow', () => {it('should support listing errors and getting details workflow', async () => {- const queryTool = GENERATED_TOOLS['query-error-tracking-issues']!()-- const listResult = await queryTool.handler(context, {})+ const listResult = await issuesListTool.handler(context, {})const errorList = parseToolResponse(listResult)expect(Array.isArray(errorList.results)).toBe(true)- if (errorList.results.length > 0 && errorList.results[0].issueId) {+ if (errorList.results.length > 0 && errorList.results[0].id) {const firstError = errorList.results[0]- const detailsResult = await queryTool.handler(context, {- issueId: firstError.issueId,- volumeResolution: 0,- })- const errorDetails = parseToolResponse(detailsResult)-- expect(Array.isArray(errorDetails.results)).toBe(true)- } else {- const testIssueId = '00000000-0000-0000-0000-000000000000'- const detailsResult = await queryTool.handler(context, {- issueId: testIssueId,+ const detailsResult = await issueTool.handler(context, {+ issueId: firstError.id,volumeResolution: 0,})const errorDetails = parseToolResponse(detailsResult)- expect(Array.isArray(errorDetails.results)).toBe(true)+ expect(errorDetails.id).toBe(firstError.id)}})it('should support full error tracking workflow: list, get details, and update status', async () => {- const queryTool = GENERATED_TOOLS['query-error-tracking-issues']!()const updateTool = GENERATED_TOOLS['error-tracking-issues-partial-update']!()- const listResult = await queryTool.handler(context, { status: 'all' })+ const listResult = await issuesListTool.handler(context, { status: 'all' })const errorList = parseToolResponse(listResult)expect(Array.isArray(errorList.results)).toBe(true)@@ -543,12 +536,12 @@ describe('Error Tracking', { concurrent: false }, () => {const issueId = errorList.results[0].id- const detailsResult = await queryTool.handler(context, {+ const detailsResult = await issueTool.handler(context, {issueId,volumeResolution: 0,})const errorDetails = parseToolResponse(detailsResult)- expect(Array.isArray(errorDetails.results)).toBe(true)+ expect(errorDetails.id).toBe(issueId)const updateResult = (await updateTool.handler(context, {id: issueId,diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.jsonindex 3b0084ecf60c..d1d55501c5b7 100644--- a/services/mcp/tests/unit/__snapshots__/exec-tool.json+++ b/services/mcp/tests/unit/__snapshots__/exec-tool.json@@ -15,7 +15,7 @@"properties": {"command": {"type": "string",- "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary\nwith drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), you MUST call\n`schema <tool_name> <field_name>` for each field you need to populate BEFORE\nconstructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large),\ndrill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> properties` — to see property filter structure\n- `schema <tool> breakdownFilter` — when using breakdowns\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"Run `schema query-trends series` for full structure\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- batch\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-prompt-duplicate\n- llma-score-definition-new-version\n- llma-skill-duplicate\n- llma-skill-file-rename\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first to load its full guidance.\n\n#### Searching for existing entities\n\nAny \"find / which / do we have / what's our X chart\" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.\n\nMap intent to table:\n\n- \"find an insight\" / \"what's our X chart\" / \"is this insight saved\" → `system.insights`\n- \"find a dashboard\" → `system.dashboards`\n- \"find a cohort\" → `system.cohorts`\n- \"find a feature flag\" → `system.feature_flags`\n- \"find an experiment\" → `system.experiments`\n- \"find a survey\" → `system.surveys`\n- \"find a notebook\" → `system.notebooks`\n\nSearch rules:\n\n1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.\n2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.\n3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.\n4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.\n5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.\n\n<example>\nUser: Do we have any insights tracking revenue?\nAssistant: [Calls `execute-sql` with `SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20`]\n[Picks the most plausible match by name, then calls `insight-get` with the candidate's `id` (or `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]\n<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>\n</example>\n\n<bad-example>\nUser: Find me a graph of MAUs.\nAssistant: [Calls `execute-sql` with `SELECT * FROM system.insights WHERE id = 33800 LIMIT 1` after a search SELECT already surfaced id 33800]\nWRONG — verify with `insight-get` (passing `id: 33800`) instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issues` — Error filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nAll PostHog app URLs must use relative paths without a domain (no us.posthog.com, eu.posthog.com, app.posthog.com), and omit the `/project/:id/` prefix. Never include `/-/` in URLs.\nUse Markdown with descriptive anchor text, for example \"[Cohorts view](/cohorts)\".\n\nKey URL patterns:\n\n- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`\n- Data management: `/data-management/events`, `/data-management/properties`\n- Billing: `/organization/billing`\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"+ "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary\nwith drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), you MUST call\n`schema <tool_name> <field_name>` for each field you need to populate BEFORE\nconstructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large),\ndrill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> properties` — to see property filter structure\n- `schema <tool> breakdownFilter` — when using breakdowns\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"Run `schema query-trends series` for full structure\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- batch\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-prompt-duplicate\n- llma-score-definition-new-version\n- llma-skill-duplicate\n- llma-skill-file-rename\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first to load its full guidance.\n\n#### Searching for existing entities\n\nAny \"find / which / do we have / what's our X chart\" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.\n\nMap intent to table:\n\n- \"find an insight\" / \"what's our X chart\" / \"is this insight saved\" → `system.insights`\n- \"find a dashboard\" → `system.dashboards`\n- \"find a cohort\" → `system.cohorts`\n- \"find a feature flag\" → `system.feature_flags`\n- \"find an experiment\" → `system.experiments`\n- \"find a survey\" → `system.surveys`\n- \"find a notebook\" → `system.notebooks`\n\nSearch rules:\n\n1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.\n2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.\n3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.\n4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.\n5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.\n\n<example>\nUser: Do we have any insights tracking revenue?\nAssistant: [Calls `execute-sql` with `SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20`]\n[Picks the most plausible match by name, then calls `insight-get` with the candidate's `id` (or `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]\n<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>\n</example>\n\n<bad-example>\nUser: Find me a graph of MAUs.\nAssistant: [Calls `execute-sql` with `SELECT * FROM system.insights WHERE id = 33800 LIMIT 1` after a search SELECT already surfaced id 33800]\nWRONG — verify with `insight-get` (passing `id: 33800`) instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nAll PostHog app URLs must use relative paths without a domain (no us.posthog.com, eu.posthog.com, app.posthog.com), and omit the `/project/:id/` prefix. Never include `/-/` in URLs.\nUse Markdown with descriptive anchor text, for example \"[Cohorts view](/cohorts)\".\n\nKey URL patterns:\n\n- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`\n- Data management: `/data-management/events`, `/data-management/properties`\n- Billing: `/organization/billing`\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"}},"required": ["command"]diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/error-tracking-issues-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/error-tracking-issues-list.jsondeleted file mode 100644index 8331b796ac73..000000000000--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/error-tracking-issues-list.json+++ /dev/null@@ -1,14 +0,0 @@-{- "$schema": "https://json-schema.org/draft/2020-12/schema",- "properties": {- "limit": {- "description": "Number of results to return per page.",- "type": "number"- },- "offset": {- "description": "The initial index from which to return the results.",- "type": "number"- }- },- "type": "object"-}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/error-tracking-issues-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/error-tracking-issues-retrieve.jsondeleted file mode 100644index f268c731ed54..000000000000--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/error-tracking-issues-retrieve.json+++ /dev/null@@ -1,11 +0,0 @@-{- "$schema": "https://json-schema.org/draft/2020-12/schema",- "properties": {- "id": {- "description": "A UUID string identifying this error tracking issue.",- "type": "string"- }- },- "required": ["id"],- "type": "object"-}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-error-tracking-issue-events.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-error-tracking-issue-events.jsonnew file mode 100644index 000000000000..7d86d57ff590--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-error-tracking-issue-events.json@@ -0,0 +1,191 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "dateRange": {+ "description": "Date range for sampled exception events. Defaults to the last 7 days.",+ "properties": {+ "date_from": {+ "description": "Start of the date range as an ISO timestamp or relative date such as -7d. Defaults to -7d.",+ "type": "string"+ },+ "date_to": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "End of the date range as an ISO timestamp or relative date. Defaults to now when omitted."+ }+ },+ "type": "object"+ },+ "filterGroup": {+ "description": "Advanced flat AND property filters applied to sampled events. HogQL filters are rejected.",+ "items": {+ "properties": {+ "key": {+ "description": "Key of the property you're filtering on. For example `email` or `$current_url`",+ "type": "string"+ },+ "operator": {+ "anyOf": [+ {+ "description": "* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `gte` - gte\n* `lte` - lte\n* `is_set` - is_set\n* `is_not_set` - is_not_set\n* `is_date_exact` - is_date_exact\n* `is_date_after` - is_date_after\n* `is_date_before` - is_date_before\n* `in` - in\n* `not_in` - not_in",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex",+ "gt",+ "lt",+ "gte",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_after",+ "is_date_before",+ "in",+ "not_in"+ ],+ "type": "string"+ },+ {+ "enum": [""],+ "type": "string"+ },+ {+ "const": null,+ "type": "null"+ }+ ],+ "default": "exact"+ },+ "type": {+ "anyOf": [+ {+ "description": "* `event` - event\n* `event_metadata` - event_metadata\n* `feature` - feature\n* `person` - person\n* `cohort` - cohort\n* `element` - element\n* `static-cohort` - static-cohort\n* `dynamic-cohort` - dynamic-cohort\n* `precalculated-cohort` - precalculated-cohort\n* `group` - group\n* `recording` - recording\n* `log_entry` - log_entry\n* `behavioral` - behavioral\n* `session` - session\n* `hogql` - hogql\n* `data_warehouse` - data_warehouse\n* `data_warehouse_person_property` - data_warehouse_person_property\n* `error_tracking_issue` - error_tracking_issue\n* `log` - log\n* `log_attribute` - log_attribute\n* `log_resource_attribute` - log_resource_attribute\n* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute\n* `revenue_analytics` - revenue_analytics\n* `flag` - flag\n* `workflow_variable` - workflow_variable",+ "enum": [+ "event",+ "event_metadata",+ "feature",+ "person",+ "cohort",+ "element",+ "static-cohort",+ "dynamic-cohort",+ "precalculated-cohort",+ "group",+ "recording",+ "log_entry",+ "behavioral",+ "session",+ "hogql",+ "data_warehouse",+ "data_warehouse_person_property",+ "error_tracking_issue",+ "log",+ "log_attribute",+ "log_resource_attribute",+ "span",+ "span_attribute",+ "span_resource_attribute",+ "revenue_analytics",+ "flag",+ "workflow_variable"+ ],+ "type": "string"+ },+ {+ "enum": [""],+ "type": "string"+ }+ ],+ "default": "event"+ },+ "value": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ }+ ]+ },+ "type": "array"+ }+ ],+ "description": "Value of your filter. For example `[email protected]` or `https://example.com/test/`. Can be an array for an OR query, like `[\"[email protected]\",\"[email protected]\"]`"+ }+ },+ "required": ["key", "value"],+ "type": "object"+ },+ "type": "array"+ },+ "filterTestAccounts": {+ "default": true,+ "description": "When true, exclude internal/test account data from results. Defaults to true.",+ "type": "boolean"+ },+ "issueId": {+ "description": "Error tracking issue ID.",+ "type": "string"+ },+ "limit": {+ "default": 1,+ "description": "Page size.",+ "maximum": 20,+ "minimum": 1,+ "type": "number"+ },+ "offset": {+ "default": 0,+ "description": "Pagination offset.",+ "minimum": 0,+ "type": "number"+ },+ "onlyAppFrames": {+ "default": true,+ "description": "When true, include only stack frames marked in_app. Defaults to true.",+ "type": "boolean"+ },+ "orderDirection": {+ "default": "DESC",+ "description": "Timestamp sort direction. Defaults to DESC.\n\n* `ASC` - ASC\n* `DESC` - DESC",+ "enum": ["ASC", "DESC"],+ "type": "string"+ },+ "searchQuery": {+ "description": "Search exception types, exception values, and current URL among sampled events.",+ "maxLength": 500,+ "type": "string"+ },+ "verbosity": {+ "default": "summary",+ "description": "Controls exception detail size: summary, stack, or raw. Defaults to summary.\n\n* `summary` - summary\n* `stack` - stack\n* `raw` - raw",+ "enum": ["summary", "stack", "raw"],+ "type": "string"+ }+ },+ "required": ["issueId"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-error-tracking-issue.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-error-tracking-issue.jsonnew file mode 100644index 000000000000..373c147e99b2--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-error-tracking-issue.json@@ -0,0 +1,49 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "dateRange": {+ "description": "Date range for issue impact and latest-event metadata. Defaults to the last 7 days.",+ "properties": {+ "date_from": {+ "description": "Start of the date range as an ISO timestamp or relative date such as -7d. Defaults to -7d.",+ "type": "string"+ },+ "date_to": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "End of the date range as an ISO timestamp or relative date. Defaults to now when omitted."+ }+ },+ "type": "object"+ },+ "filterTestAccounts": {+ "default": true,+ "description": "When true, exclude internal/test account data from results. Defaults to true.",+ "type": "boolean"+ },+ "includeSparkline": {+ "default": false,+ "description": "Set true to include a compact numeric occurrence sparkline. Defaults to false.",+ "type": "boolean"+ },+ "issueId": {+ "description": "Error tracking issue ID.",+ "type": "string"+ },+ "volumeResolution": {+ "default": 0,+ "description": "Volume buckets. Maximum 200.",+ "maximum": 200,+ "minimum": 0,+ "type": "number"+ }+ },+ "required": ["issueId"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-error-tracking-issues-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-error-tracking-issues-list.jsonnew file mode 100644index 000000000000..109137075a99--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-error-tracking-issues-list.json@@ -0,0 +1,278 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "assignee": {+ "anyOf": [+ {+ "properties": {+ "id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ }+ ],+ "description": "User ID or role UUID to filter by."+ },+ "type": {+ "description": "Assignee target type: user or role.\n\n* `user` - user\n* `role` - role",+ "enum": ["user", "role"],+ "type": "string"+ }+ },+ "required": ["id", "type"],+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Filter by issue assignee. Omit to include all assignees."+ },+ "dateRange": {+ "description": "Date range for issue aggregates. Defaults to the last 7 days.",+ "properties": {+ "date_from": {+ "description": "Start of the date range as an ISO timestamp or relative date such as -7d. Defaults to -7d.",+ "type": "string"+ },+ "date_to": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "End of the date range as an ISO timestamp or relative date. Defaults to now when omitted."+ }+ },+ "type": "object"+ },+ "filePath": {+ "description": "Search stack-frame source/file path text.",+ "maxLength": 1000,+ "type": "string"+ },+ "filterGroup": {+ "description": "Advanced flat AND property filters. Prefer typed shortcut fields when they fit. HogQL filters are rejected.",+ "items": {+ "properties": {+ "key": {+ "description": "Key of the property you're filtering on. For example `email` or `$current_url`",+ "type": "string"+ },+ "operator": {+ "anyOf": [+ {+ "description": "* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `gte` - gte\n* `lte` - lte\n* `is_set` - is_set\n* `is_not_set` - is_not_set\n* `is_date_exact` - is_date_exact\n* `is_date_after` - is_date_after\n* `is_date_before` - is_date_before\n* `in` - in\n* `not_in` - not_in",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex",+ "gt",+ "lt",+ "gte",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_after",+ "is_date_before",+ "in",+ "not_in"+ ],+ "type": "string"+ },+ {+ "enum": [""],+ "type": "string"+ },+ {+ "const": null,+ "type": "null"+ }+ ],+ "default": "exact"+ },+ "type": {+ "anyOf": [+ {+ "description": "* `event` - event\n* `event_metadata` - event_metadata\n* `feature` - feature\n* `person` - person\n* `cohort` - cohort\n* `element` - element\n* `static-cohort` - static-cohort\n* `dynamic-cohort` - dynamic-cohort\n* `precalculated-cohort` - precalculated-cohort\n* `group` - group\n* `recording` - recording\n* `log_entry` - log_entry\n* `behavioral` - behavioral\n* `session` - session\n* `hogql` - hogql\n* `data_warehouse` - data_warehouse\n* `data_warehouse_person_property` - data_warehouse_person_property\n* `error_tracking_issue` - error_tracking_issue\n* `log` - log\n* `log_attribute` - log_attribute\n* `log_resource_attribute` - log_resource_attribute\n* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute\n* `revenue_analytics` - revenue_analytics\n* `flag` - flag\n* `workflow_variable` - workflow_variable",+ "enum": [+ "event",+ "event_metadata",+ "feature",+ "person",+ "cohort",+ "element",+ "static-cohort",+ "dynamic-cohort",+ "precalculated-cohort",+ "group",+ "recording",+ "log_entry",+ "behavioral",+ "session",+ "hogql",+ "data_warehouse",+ "data_warehouse_person_property",+ "error_tracking_issue",+ "log",+ "log_attribute",+ "log_resource_attribute",+ "span",+ "span_attribute",+ "span_resource_attribute",+ "revenue_analytics",+ "flag",+ "workflow_variable"+ ],+ "type": "string"+ },+ {+ "enum": [""],+ "type": "string"+ }+ ],+ "default": "event"+ },+ "value": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ }+ ]+ },+ "type": "array"+ }+ ],+ "description": "Value of your filter. For example `[email protected]` or `https://example.com/test/`. Can be an array for an OR query, like `[\"[email protected]\",\"[email protected]\"]`"+ }+ },+ "required": ["key", "value"],+ "type": "object"+ },+ "type": "array"+ },+ "filterTestAccounts": {+ "default": true,+ "description": "When true, exclude internal/test account data from results. Defaults to true.",+ "type": "boolean"+ },+ "fingerprint": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "items": {+ "type": "string"+ },+ "minItems": 1,+ "type": "array"+ }+ ],+ "description": "Filter by exact exception fingerprint hash, not fuzzy search."+ },+ "library": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "items": {+ "type": "string"+ },+ "minItems": 1,+ "type": "array"+ }+ ],+ "description": "Filter by SDK/library value from event $lib, for example posthog-js."+ },+ "limit": {+ "default": 25,+ "description": "Page size.",+ "maximum": 100,+ "minimum": 1,+ "type": "number"+ },+ "offset": {+ "default": 0,+ "description": "Pagination offset.",+ "minimum": 0,+ "type": "number"+ },+ "orderBy": {+ "default": "occurrences",+ "description": "Field used to sort issues. Defaults to occurrences.\n\n* `last_seen` - last_seen\n* `first_seen` - first_seen\n* `occurrences` - occurrences\n* `users` - users\n* `sessions` - sessions",+ "enum": ["last_seen", "first_seen", "occurrences", "users", "sessions"],+ "type": "string"+ },+ "orderDirection": {+ "default": "DESC",+ "description": "Sort direction. Defaults to DESC.\n\n* `ASC` - ASC\n* `DESC` - DESC",+ "enum": ["ASC", "DESC"],+ "type": "string"+ },+ "personId": {+ "description": "Filter by exact PostHog person UUID.",+ "type": "string"+ },+ "release": {+ "description": "Filter by exact release ID, version, or git commit ID captured in $exception_releases.",+ "maxLength": 500,+ "type": "string"+ },+ "searchQuery": {+ "description": "Free-text search across exception types, values, stack frames, and email fields.",+ "maxLength": 500,+ "type": "string"+ },+ "status": {+ "default": "active",+ "description": "Filter by issue status. Defaults to active.\n\n* `archived` - archived\n* `active` - active\n* `resolved` - resolved\n* `pending_release` - pending_release\n* `suppressed` - suppressed\n* `all` - all",+ "enum": ["archived", "active", "resolved", "pending_release", "suppressed", "all"],+ "type": "string"+ },+ "url": {+ "description": "Filter by current URL substring.",+ "maxLength": 1000,+ "type": "string"+ },+ "user": {+ "description": "Search user/email text.",+ "maxLength": 500,+ "type": "string"+ },+ "volumeResolution": {+ "default": 0,+ "description": "Number of volume buckets. Defaults to 0 for compact aggregate counts.",+ "maximum": 200,+ "minimum": 0,+ "type": "number"+ }+ },+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-error-tracking-issues.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-error-tracking-issues.jsondeleted file mode 100644index bd034c54f5e5..000000000000--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-error-tracking-issues.json+++ /dev/null@@ -1,621 +0,0 @@-{- "$schema": "https://json-schema.org/draft/2020-12/schema",- "properties": {- "assignee": {- "anyOf": [- {- "properties": {- "id": {- "anyOf": [- {- "maximum": 9007199254740991,- "minimum": -9007199254740991,- "type": "integer"- },- {- "type": "string"- }- ]- },- "type": {- "enum": ["user", "role"],- "type": "string"- }- },- "required": ["id", "type"],- "type": "object"- },- {- "type": "null"- }- ],- "description": "Filter by assignee."- },- "dateRange": {- "default": {- "date_from": "-7d"- },- "description": "Date range to filter results.",- "properties": {- "date_from": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "description": "Start of the date range. Accepts ISO 8601 timestamps (e.g., 2024-01-15T00:00:00Z) or relative formats: -7d (7 days ago), -2w (2 weeks ago), -1m (1 month ago),\n-1h (1 hour ago), -1mStart (start of last month), -1yStart (start of last year)."- },- "date_to": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "description": "End of the date range. Same format as date_from. Omit or null for \"now\"."- },- "explicitDate": {- "anyOf": [- {- "type": "boolean"- },- {- "type": "null"- }- ],- "default": false,- "description": "Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period."- }- },- "type": "object"- },- "filterGroup": {- "default": [],- "description": "Property filters for the query",- "items": {- "anyOf": [- {- "anyOf": [- {- "properties": {- "key": {- "description": "Use one of the properties the user has provided in the plan.",- "type": "string"- },- "operator": {- "description": "`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.",- "enum": ["exact", "is_not", "icontains", "not_icontains", "regex", "not_regex"],- "type": "string"- },- "type": {- "enum": ["event", "person", "session", "feature"],- "type": "string"- },- "value": {- "description": "Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.",- "type": "string"- }- },- "required": ["key", "operator", "type", "value"],- "type": "object"- },- {- "properties": {- "key": {- "description": "Use one of the properties the user has provided in the plan.",- "type": "string"- },- "operator": {- "enum": ["exact", "gt", "lt"],- "type": "string"- },- "type": {- "enum": ["event", "person", "session", "feature"],- "type": "string"- },- "value": {- "type": "number"- }- },- "required": ["key", "operator", "type", "value"],- "type": "object"- },- {- "properties": {- "key": {- "description": "Use one of the properties the user has provided in the plan.",- "type": "string"- },- "operator": {- "description": "`exact` - exact match of any of the values. `is_not` - does not match any of the values.",- "enum": ["exact", "is_not"],- "type": "string"- },- "type": {- "enum": ["event", "person", "session", "feature"],- "type": "string"- },- "value": {- "description": "Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string \"true\" or \"false\".",- "items": {- "type": "string"- },- "type": "array"- }- },- "required": ["key", "operator", "type", "value"],- "type": "object"- },- {- "properties": {- "key": {- "description": "Use one of the properties the user has provided in the plan.",- "type": "string"- },- "operator": {- "enum": ["is_date_exact", "is_date_before", "is_date_after"],- "type": "string"- },- "type": {- "enum": ["event", "person", "session", "feature"],- "type": "string"- },- "value": {- "description": "Value must be a date in ISO 8601 format.",- "type": "string"- }- },- "required": ["key", "operator", "type", "value"],- "type": "object"- },- {- "properties": {- "key": {- "description": "Use one of the properties the user has provided in the plan.",- "type": "string"- },- "operator": {- "description": "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected.",- "enum": ["is_set", "is_not_set"],- "type": "string"- },- "type": {- "enum": ["event", "person", "session", "feature"],- "type": "string"- }- },- "required": ["key", "operator", "type"],- "type": "object"- }- ]- },- {- "anyOf": [- {- "properties": {- "group_type_index": {- "description": "Index of the group type from the group mapping.",- "maximum": 9007199254740991,- "minimum": -9007199254740991,- "type": "integer"- },- "key": {- "description": "Use one of the properties the user has provided in the plan.",- "type": "string"- },- "operator": {- "description": "`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.",- "enum": ["exact", "is_not", "icontains", "not_icontains", "regex", "not_regex"],- "type": "string"- },- "type": {- "const": "group",- "default": "group",- "type": "string"- },- "value": {- "description": "Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.",- "type": "string"- }- },- "required": ["group_type_index", "key", "operator", "value"],- "type": "object"- },- {- "properties": {- "group_type_index": {- "description": "Index of the group type from the group mapping.",- "maximum": 9007199254740991,- "minimum": -9007199254740991,- "type": "integer"- },- "key": {- "description": "Use one of the properties the user has provided in the plan.",- "type": "string"- },- "operator": {- "enum": ["exact", "gt", "lt"],- "type": "string"- },- "type": {- "const": "group",- "default": "group",- "type": "string"- },- "value": {- "type": "number"- }- },- "required": ["group_type_index", "key", "operator", "value"],- "type": "object"- },- {- "properties": {- "group_type_index": {- "description": "Index of the group type from the group mapping.",- "maximum": 9007199254740991,- "minimum": -9007199254740991,- "type": "integer"- },- "key": {- "description": "Use one of the properties the user has provided in the plan.",- "type": "string"- },- "operator": {- "description": "`exact` - exact match of any of the values. `is_not` - does not match any of the values.",- "enum": ["exact", "is_not"],- "type": "string"- },- "type": {- "const": "group",- "default": "group",- "type": "string"- },- "value": {- "description": "Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string \"true\" or \"false\".",- "items": {- "type": "string"- },- "type": "array"- }- },- "required": ["group_type_index", "key", "operator", "value"],- "type": "object"- },- {- "properties": {- "group_type_index": {- "description": "Index of the group type from the group mapping.",- "maximum": 9007199254740991,- "minimum": -9007199254740991,- "type": "integer"- },- "key": {- "description": "Use one of the properties the user has provided in the plan.",- "type": "string"- },- "operator": {- "enum": ["is_date_exact", "is_date_before", "is_date_after"],- "type": "string"- },- "type": {- "const": "group",- "default": "group",- "type": "string"- },- "value": {- "description": "Value must be a date in ISO 8601 format.",- "type": "string"- }- },- "required": ["group_type_index", "key", "operator", "value"],- "type": "object"- },- {- "properties": {- "group_type_index": {- "description": "Index of the group type from the group mapping.",- "maximum": 9007199254740991,- "minimum": -9007199254740991,- "type": "integer"- },- "key": {- "description": "Use one of the properties the user has provided in the plan.",- "type": "string"- },- "operator": {- "description": "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected.",- "enum": ["is_set", "is_not_set"],- "type": "string"- },- "type": {- "const": "group",- "default": "group",- "type": "string"- }- },- "required": ["group_type_index", "key", "operator"],- "type": "object"- }- ]- },- {- "properties": {- "key": {- "const": "id",- "default": "id",- "type": "string"- },- "operator": {- "const": "in",- "default": "in",- "type": "string"- },- "type": {- "const": "cohort",- "default": "cohort",- "description": "Filter events by cohort membership. Use this to narrow down results to persons belonging to a specific cohort. Example: `{ type: \"cohort\", key: \"id\", value: 42, operator: \"in\" }`",- "type": "string"- },- "value": {- "description": "The cohort ID to filter by.",- "maximum": 9007199254740991,- "minimum": -9007199254740991,- "type": "integer"- }- },- "required": ["value"],- "type": "object"- },- {- "anyOf": [- {- "properties": {- "key": {- "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",- "enum": ["tag_name", "text", "href", "selector"],- "type": "string"- },- "operator": {- "description": "`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.",- "enum": ["exact", "is_not", "icontains", "not_icontains", "regex", "not_regex"],- "type": "string"- },- "type": {- "const": "element",- "default": "element",- "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",- "type": "string"- },- "value": {- "description": "Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.",- "type": "string"- }- },- "required": ["key", "operator", "value"],- "type": "object"- },- {- "properties": {- "key": {- "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",- "enum": ["tag_name", "text", "href", "selector"],- "type": "string"- },- "operator": {- "enum": ["exact", "gt", "lt"],- "type": "string"- },- "type": {- "const": "element",- "default": "element",- "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",- "type": "string"- },- "value": {- "type": "number"- }- },- "required": ["key", "operator", "value"],- "type": "object"- },- {- "properties": {- "key": {- "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",- "enum": ["tag_name", "text", "href", "selector"],- "type": "string"- },- "operator": {- "description": "`exact` - exact match of any of the values. `is_not` - does not match any of the values.",- "enum": ["exact", "is_not"],- "type": "string"- },- "type": {- "const": "element",- "default": "element",- "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",- "type": "string"- },- "value": {- "description": "Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string \"true\" or \"false\".",- "items": {- "type": "string"- },- "type": "array"- }- },- "required": ["key", "operator", "value"],- "type": "object"- },- {- "properties": {- "key": {- "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",- "enum": ["tag_name", "text", "href", "selector"],- "type": "string"- },- "operator": {- "enum": ["is_date_exact", "is_date_before", "is_date_after"],- "type": "string"- },- "type": {- "const": "element",- "default": "element",- "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",- "type": "string"- },- "value": {- "description": "Value must be a date in ISO 8601 format.",- "type": "string"- }- },- "required": ["key", "operator", "value"],- "type": "object"- },- {- "properties": {- "key": {- "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",- "enum": ["tag_name", "text", "href", "selector"],- "type": "string"- },- "operator": {- "description": "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected.",- "enum": ["is_set", "is_not_set"],- "type": "string"- },- "type": {- "const": "element",- "default": "element",- "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",- "type": "string"- }- },- "required": ["key", "operator"],- "type": "object"- }- ]- },- {- "properties": {- "key": {- "description": "A HogQL boolean expression used as a filter condition.\n\nExamples:\n- Filter where a property exceeds a threshold: `toFloat(properties.load_time) > 5.0`\n- Filter with string matching: `properties.$current_url LIKE '%/pricing%'`\n- Filter with multiple conditions: `properties.$browser = 'Chrome' AND toFloat(properties.duration) > 30`",- "type": "string"- },- "type": {- "const": "hogql",- "default": "hogql",- "description": "Filter by a HogQL boolean expression for advanced filtering that can't be expressed with standard property filters.",- "type": "string"- }- },- "required": ["key"],- "type": "object"- },- {- "properties": {- "key": {- "description": "The feature flag key.",- "type": "string"- },- "operator": {- "const": "flag_evaluates_to",- "default": "flag_evaluates_to",- "type": "string"- },- "type": {- "const": "flag",- "default": "flag",- "description": "Filter events by feature flag state — only include events where a specific flag evaluated to a given value. Examples:\n- Flag enabled: `{ type: \"flag\", key: \"new-onboarding\", operator: \"flag_evaluates_to\", value: true }`\n- Specific variant: `{ type: \"flag\", key: \"checkout-experiment\", operator: \"flag_evaluates_to\", value: \"variant-a\" }`",- "type": "string"- },- "value": {- "anyOf": [- {- "type": "boolean"- },- {- "type": "string"- }- ],- "description": "`true`/`false` for boolean flags, or a variant name string for multivariate flags."- }- },- "required": ["key", "value"],- "type": "object"- }- ]- },- "type": "array"- },- "filterTestAccounts": {- "default": true,- "description": "Whether to filter out test accounts.",- "type": "boolean"- },- "issueId": {- "description": "Filter to a specific error tracking issue by ID.",- "type": "string"- },- "kind": {- "const": "ErrorTrackingQuery",- "default": "ErrorTrackingQuery",- "type": "string"- },- "limit": {- "default": 50,- "maximum": 9007199254740991,- "minimum": -9007199254740991,- "type": "integer"- },- "offset": {- "maximum": 9007199254740991,- "minimum": -9007199254740991,- "type": "integer"- },- "orderBy": {- "default": "occurrences",- "description": "Field to sort results by.",- "enum": ["last_seen", "first_seen", "occurrences", "users", "sessions"],- "type": "string"- },- "orderDirection": {- "default": "DESC",- "description": "Sort direction.",- "enum": ["ASC", "DESC"],- "type": "string"- },- "searchQuery": {- "description": "Free-text search across exception type, message, and stack frames.",- "type": "string"- },- "status": {- "anyOf": [- {- "enum": ["archived", "active", "resolved", "pending_release", "suppressed"],- "type": "string"- },- {- "const": "all",- "type": "string"- }- ],- "default": "active",- "description": "Filter by issue status."- },- "volumeResolution": {- "default": 1,- "description": "Controls volume chart granularity. Use 1 for sparklines, 0 for counts only.",- "maximum": 9007199254740991,- "minimum": -9007199254740991,- "type": "integer"- }- },- "type": "object"-}diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 0483b2a65ef5..919662f70a6f 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -63,12 +63,12 @@ describe('Tool Filtering - Features', () => {{features: ['error_tracking'],description: 'error tracking tools (underscore)',- expectedTools: ['query-error-tracking-issues', 'error-tracking-issues-list'],+ expectedTools: ['query-error-tracking-issues-list', 'query-error-tracking-issue'],},{features: ['error-tracking'],description: 'error tracking tools (hyphen, normalized)',- expectedTools: ['query-error-tracking-issues', 'error-tracking-issues-list'],+ expectedTools: ['query-error-tracking-issues-list', 'query-error-tracking-issue'],},{features: ['experiments'],