: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(error-tracking): add an opt-in event breakdown to the issue mcp tool (#107629)
Hugues Pouillot8468cf20787c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8e481c13c852..38d6069cd1bc 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5808,6 +5808,8 @@ snapshots:hash: v1.k794b7964.fde427a04a5be7d7bd22031125188c719c92e3cec3040de64e833259496836a4.tr8wf9B0D2VjRFAGVH8LpfHNiLuXIUBQkPcsRigf1MQmcp-apps-error-tracking--stack-trace--light:hash: v1.k794b7964.ad8da946c8891849416cc66d17c77e44dc83e62d5b71cb2eb433779d1ddc0cb3.s-3zNqXOIZXWGTq1Ts0ETT809GtSjhzHcG4PbGrfgDo+ mcp-apps-error-tracking--with-breakdown--light:+ hash: v1.k794b7964.1dd412a9421bb62e86ff964b3a0449375c9429b972a66fe3074db04bc7d7dd97.qWnA19cd9of2KGwgsVLoFh0yzOSwj8lWaSr2cDaW4_0mcp-apps-error-tracking--with-external-links--light:hash: v1.k794b7964.1c438b81ddecf6cd51016c53d57b3a80c7a60aab20f69a4629f52d9366452c72.alkUqUY-JcNO_PquFIaJSqBh0hBs4BbMf4NNbwjkHI4mcp-apps-experiments--completed--light:diff --git a/products/error_tracking/backend/facade/query_utils.py b/products/error_tracking/backend/facade/query_utils.pyindex c3ba97f1a97c..87254c67f379 100644--- a/products/error_tracking/backend/facade/query_utils.py+++ b/products/error_tracking/backend/facade/query_utils.py@@ -1,10 +1,15 @@from __future__ import annotationsimport json+from datetime import datetime, timedeltafrom typing import cast+from zoneinfo import ZoneInfofrom posthog.hogql.escape_sql import escape_hogql_string+from posthog.dataclasses import frozen+from posthog.utils import relative_date_parse+MAX_NORMALIZED_TEXT_CHARS = 1000MAX_STACK_FRAMES = 50# The issue detail tool returns the full description, so list rows keep only a preview.@@ -90,6 +95,29 @@ PROPERTY_COLUMN_NAMES = {select.removeprefix("properties.") for select in [*CONTEXT_EVENT_SELECTS, *EVENT_PROPERTY_SELECTS]}+ISSUE_BREAKDOWN_TOP_VALUES = 5+ISSUE_BREAKDOWN_MAX_DAYS = 30+MAX_BREAKDOWN_VALUE_CHARS = 200+# Ask for more values than the response returns: NULL and empty values can take a slot, and they are dropped.+ISSUE_BREAKDOWN_QUERY_VALUES = ISSUE_BREAKDOWN_TOP_VALUES + 2+# Dimension name in the response -> event property. All of them have materialized columns. A property without one+# makes the query read the whole properties blob, which holds the exception payload. On a high-volume issue that+# multiplies the bytes read by about 40, for example with $trace_id or $exception_handled.+ISSUE_BREAKDOWN_DIMENSIONS = {+ "path": "$pathname",+ "url": "$current_url",+ "screen": "$screen_name",+ "browser": "$browser",+ "os": "$os",+ "library": "$lib",+ "library_version": "$lib_version",+ "app_version": "$app_version",+}+ISSUE_BREAKDOWN_SESSION_PROPERTY = "$session_id"+ISSUE_BREAKDOWN_PROPERTIES = [*ISSUE_BREAKDOWN_DIMENSIONS.values(), ISSUE_BREAKDOWN_SESSION_PROPERTY]+# Labels the breakdowns query uses for a missing value.+BREAKDOWN_EMPTY_VALUES = {"", "$$_posthog_breakdown_null_$$"}+def build_event_selects(includes: list[str]) -> list[str]:property_selects = list(@@ -498,6 +526,93 @@ def extract_latest_release(event_properties: dict[str, object]) -> dict[str, obj)+@frozen+class BreakdownRange:+ date_from: datetime+ date_to: datetime+ # True when the limit made the range shorter than the request.+ range_limited: bool+++def resolve_breakdown_range(date_range: dict[str, object], timezone_info: ZoneInfo, now: datetime) -> BreakdownRange:+ """Resolve the breakdown range and limit it to the last ISSUE_BREAKDOWN_MAX_DAYS days before its end.++ The breakdown aggregates every matching event, so its cost grows with the range. The limit keeps the cost+ bounded.+ """+ raw_date_to = date_range.get("date_to")+ date_to = relative_date_parse(str(raw_date_to), timezone_info, now=now) if raw_date_to else now+ raw_date_from = date_range.get("date_from")+ date_from = (+ relative_date_parse(str(raw_date_from), timezone_info, now=now)+ if raw_date_from and raw_date_from != "all"+ else None+ )+ earliest = date_to - timedelta(days=ISSUE_BREAKDOWN_MAX_DAYS)+ if date_from is None or date_from < earliest:+ return BreakdownRange(date_from=earliest, date_to=date_to, range_limited=True)+ return BreakdownRange(date_from=date_from, date_to=date_to, range_limited=False)+++def breakdown_query_date_range(+ date_range: dict[str, object], timezone_info: ZoneInfo, now: datetime+) -> tuple[dict[str, str | None], bool]:+ """Build the date range for the breakdowns query and say whether the 30-day limit made it shorter.++ A range within the limit keeps the requested strings, so a relative range such as -7d gives the same query, and+ the same cache key, on every call. A relative date_to is sent resolved: the breakdowns query reads it forward.+ """+ resolved = resolve_breakdown_range(date_range, timezone_info, now)+ raw_date_from = date_range.get("date_from")+ return {+ "date_from": resolved.date_from.isoformat() if resolved.range_limited else str(raw_date_from),+ "date_to": resolved.date_to.isoformat() if date_range.get("date_to") else None,+ }, resolved.range_limited+++def as_count(value: object) -> int:+ # The breakdowns query returns counts as floats.+ return int(value) if isinstance(value, int | float) and not isinstance(value, bool) else 0+++def breakdown_values(results: dict[str, object], prop: str, limit: int) -> list[dict[str, object]]:+ property_result = as_record(results.get(prop))+ raw_values = property_result.get("values") if property_result else None+ values: list[dict[str, object]] = []+ for item in raw_values if isinstance(raw_values, list) else []:+ record = as_record(item)+ value = record.get("value") if record else None+ count = record.get("count") if record else None+ if not isinstance(value, str) or value in BREAKDOWN_EMPTY_VALUES:+ continue+ values.append({"value": truncate_text(value, MAX_BREAKDOWN_VALUE_CHARS), "count": as_count(count)})+ return values[:limit]+++def map_issue_breakdown(results: dict[str, object]) -> dict[str, object]:+ """Map ErrorTrackingBreakdownsQuery results to the compact breakdown of the issue tool."""+ totals = [+ as_count(record.get("total_count"))+ for prop in ISSUE_BREAKDOWN_PROPERTIES+ if (record := as_record(results.get(prop))) is not None+ ]+ top_values = {+ name: breakdown_values(results, prop, ISSUE_BREAKDOWN_TOP_VALUES)+ for name, prop in ISSUE_BREAKDOWN_DIMENSIONS.items()+ }+ # The URL only matters when there is no path: backend SDKs set $current_url but not $pathname.+ if top_values["path"]:+ top_values["url"] = []+ sessions = breakdown_values(results, ISSUE_BREAKDOWN_SESSION_PROPERTY, ISSUE_BREAKDOWN_TOP_VALUES)+ return {+ # Each event adds one row for each property, so every property has the same total.+ "occurrences": max(totals, default=0),+ "sample_session_ids": [session["value"] for session in sessions],+ # Leave out empty dimensions: backend SDKs send no browser or OS, and web SDKs send no screen name.+ "top_values": {name: items for name, items in top_values.items() if items},+ }++def build_impact(issue: dict[str, object]) -> dict[str, object]:aggregations = as_record(issue.get("aggregations")) or {}return compact_dict(diff --git a/products/error_tracking/backend/presentation/views/query.py b/products/error_tracking/backend/presentation/views/query.pyindex 3cd35993c980..f2e6531561a7 100644--- a/products/error_tracking/backend/presentation/views/query.py+++ b/products/error_tracking/backend/presentation/views/query.py@@ -2,13 +2,22 @@ from __future__ import annotationsfrom typing import Literal, cast+from django.utils.timezone import now+import structlogfrom drf_spectacular.utils import OpenApiResponsefrom rest_framework import status, viewsetsfrom rest_framework.exceptions import ValidationErrorfrom rest_framework.response import Response-from posthog.schema import DateRange, ErrorTrackingIssueAssignee, ErrorTrackingQuery, EventsQuery+from posthog.schema import (+ CachedErrorTrackingBreakdownsQueryResponse,+ DateRange,+ ErrorTrackingBreakdownsQuery,+ ErrorTrackingIssueAssignee,+ ErrorTrackingQuery,+ EventsQuery,+)from posthog.hogql.errors import ResolutionError@@ -17,6 +26,8 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.hogql_queries.events_query_runner import EventsQueryRunner+from posthog.hogql_queries.query_runner import ExecutionMode+from posthog.models import Userfrom products.error_tracking.backend.facade import (api as facade_api,@@ -25,7 +36,10 @@ from products.error_tracking.backend.facade import (from products.error_tracking.backend.facade.query_utils import (CONTEXT_EVENT_SELECTS,DEFAULT_EVENT_CONTEXT_INCLUDES,+ ISSUE_BREAKDOWN_PROPERTIES,+ ISSUE_BREAKDOWN_QUERY_VALUES,ISSUE_FIELDS,+ breakdown_query_date_range,build_date_range,build_event_selects,build_impact,@@ -43,10 +57,12 @@ from products.error_tracking.backend.facade.query_utils import (get_page_info,map_context_event_properties,map_event_row,+ map_issue_breakdown,normalize_volume_resolution,pick_fields,)from products.error_tracking.backend.presentation.views.query_serializers import (+ ErrorTrackingIssueBreakdownSerializer,ErrorTrackingIssueDetailSerializer,ErrorTrackingIssueEventsQueryRequestSerializer,ErrorTrackingIssueEventsResponseSerializer,@@ -117,7 +133,10 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):},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.",+ description=(+ "Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional "+ "sparkline and event breakdown."+ ),)@action(methods=["POST"], detail=False, url_path="issue", required_scopes=["error_tracking:read"])def issue(self, request: ValidatedRequest, **kwargs: object) -> Response:@@ -125,6 +144,8 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):issue_id = str(params["issueId"])date_range = build_date_range(params.get("dateRange"))include_sparkline = cast(bool, params.get("includeSparkline", False))+ include_breakdown = cast(bool, params.get("includeBreakdown", False))+ filter_test_accounts = cast(bool, params.get("filterTestAccounts", True))volume_resolution = cast(int, params.get("volumeResolution", 0))if include_sparkline and volume_resolution <= 0:volume_resolution = 12@@ -135,7 +156,7 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):kind="ErrorTrackingQuery",issueId=issue_id,dateRange=DateRange(**date_range),- filterTestAccounts=cast(bool, params.get("filterTestAccounts", True)),+ filterTestAccounts=filter_test_accounts,volumeResolution=normalize_volume_resolution(volume_resolution),limit=1,orderBy="last_seen",@@ -170,7 +191,7 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):event="$exception",select=CONTEXT_EVENT_SELECTS,where=build_issue_where(issue_id),- filterTestAccounts=cast(bool, params.get("filterTestAccounts", True)),+ filterTestAccounts=filter_test_accounts,after=date_range.get("date_from"),before=date_range.get("date_to"),orderBy=["timestamp DESC"],@@ -211,8 +232,42 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):"sparkline": build_sparkline(issue) if include_sparkline else None,})+ if include_breakdown:+ payload["breakdown"] = self._issue_breakdown(request, issue_id, date_range, filter_test_accounts)return Response(payload)+ def _issue_breakdown(+ self, request: ValidatedRequest, issue_id: str, date_range: dict[str, object], filter_test_accounts: bool+ ) -> dict[str, object]:+ breakdown_date_range, range_limited = breakdown_query_date_range(date_range, self.team.timezone_info, now())+ # The same query as the breakdowns on the issue page, so agents and people see the same numbers. It goes+ # through the query cache, and HogQL masks restricted properties, so such a dimension comes back empty.+ runner = query_facade.ErrorTrackingBreakdownsQueryRunner(+ team=self.team,+ query=ErrorTrackingBreakdownsQuery(+ kind="ErrorTrackingBreakdownsQuery",+ issueId=issue_id,+ breakdownProperties=ISSUE_BREAKDOWN_PROPERTIES,+ dateRange=DateRange(**breakdown_date_range),+ filterTestAccounts=filter_test_accounts,+ maxValuesPerProperty=ISSUE_BREAKDOWN_QUERY_VALUES,+ tags={"productKey": "error_tracking"},+ ),+ )+ with tags_context(product=Product.ERROR_TRACKING, feature=Feature.QUERY):+ response = runner.run(+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE, user=cast(User, request.user)+ )+ if not isinstance(response, CachedErrorTrackingBreakdownsQueryResponse):+ raise ValidationError("The issue breakdown could not be calculated.")+ breakdown = {+ "date_from": runner.date_from,+ "date_to": runner.date_to,+ "range_limited": range_limited,+ **map_issue_breakdown(response.model_dump(mode="json").get("results") or {}),+ }+ return ErrorTrackingIssueBreakdownSerializer(instance=breakdown).data+@validated_request(request_serializer=ErrorTrackingIssueEventsQueryRequestSerializer,responses={diff --git a/products/error_tracking/backend/presentation/views/query_serializers.py b/products/error_tracking/backend/presentation/views/query_serializers.pyindex 3ebcf39e5fe3..17729e9d6912 100644--- a/products/error_tracking/backend/presentation/views/query_serializers.py+++ b/products/error_tracking/backend/presentation/views/query_serializers.py@@ -189,6 +189,16 @@ class ErrorTrackingIssueQueryRequestSerializer(serializers.Serializer):default=False,help_text="Set true to include a compact numeric occurrence sparkline. Defaults to false.",)+ includeBreakdown = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "Set true to include the issue page breakdowns: the most common paths (or URLs when events have no path), "+ "screens, browsers, OS, libraries, library versions, and app versions, each with a count, plus the "+ "sessions with the most events. Covers at most the last 30 days of dateRange. Adds one aggregate query, "+ "so request it only to answer where, for whom, or on which platforms the issue happens. Defaults to false."+ ),+ )class ErrorTrackingIssueEventsQueryRequestSerializer(serializers.Serializer):@@ -325,6 +335,45 @@ class ErrorTrackingLatestReleaseSerializer(serializers.Serializer):repo_name = serializers.CharField(required=False, help_text="Git repository name.")+class ErrorTrackingBreakdownValueSerializer(serializers.Serializer):+ value = serializers.CharField(help_text="Property value.")+ count = serializers.IntegerField(help_text="Number of matching events with this value.")+++def breakdown_values_field(help_text: str) -> serializers.ListField:+ return serializers.ListField(child=ErrorTrackingBreakdownValueSerializer(), required=False, help_text=help_text)+++class ErrorTrackingBreakdownTopValuesSerializer(serializers.Serializer):+ path = breakdown_values_field("Most common $pathname values, most frequent first.")+ url = breakdown_values_field(+ "Most common $current_url values, most frequent first. Returned only when events have no $pathname, as with "+ "backend SDKs."+ )+ screen = breakdown_values_field("Most common $screen_name values, most frequent first.")+ browser = breakdown_values_field("Most common $browser values, most frequent first.")+ os = breakdown_values_field("Most common $os values, most frequent first.")+ library = breakdown_values_field("Most common $lib values, most frequent first.")+ library_version = breakdown_values_field("Most common $lib_version values, most frequent first.")+ app_version = breakdown_values_field("Most common $app_version values, most frequent first.")+++class ErrorTrackingIssueBreakdownSerializer(serializers.Serializer):+ date_from = serializers.DateTimeField(help_text="Start of the range that the breakdown covers.")+ date_to = serializers.DateTimeField(help_text="End of the range that the breakdown covers.")+ range_limited = serializers.BooleanField(+ help_text="True when the requested range was longer than 30 days and the breakdown covers only the last 30."+ )+ occurrences = serializers.IntegerField(help_text="Matching exception events in the breakdown range.")+ sample_session_ids = serializers.ListField(+ child=serializers.CharField(),+ help_text="Up to 5 $session_id values with the most matching events, for session recording lookups.",+ )+ top_values = ErrorTrackingBreakdownTopValuesSerializer(+ help_text="Most common values for each dimension. A dimension with no values is left out."+ )++class ErrorTrackingIssueDetailSerializer(ErrorTrackingIssueListItemSerializer):function = serializers.CharField(required=False, allow_null=True, help_text="Top function associated with the issue."@@ -335,6 +384,9 @@ class ErrorTrackingIssueDetailSerializer(ErrorTrackingIssueListItemSerializer):sparkline = serializers.ListField(child=serializers.FloatField(), required=False, help_text="Optional compact occurrence sparkline.")+ breakdown = ErrorTrackingIssueBreakdownSerializer(+ required=False, help_text="Aggregate over matching events. Returned only when includeBreakdown is true."+ )class ErrorTrackingEventSerializer(serializers.Serializer):diff --git a/products/error_tracking/backend/tests/api/test_query_api.py b/products/error_tracking/backend/tests/api/test_query_api.pyindex 41e06753c785..d70a1c83cf17 100644--- a/products/error_tracking/backend/tests/api/test_query_api.py+++ b/products/error_tracking/backend/tests/api/test_query_api.py@@ -1,7 +1,8 @@from __future__ import annotations-from datetime import timedelta+from datetime import UTC, datetime, timedeltafrom typing import Any, cast+from zoneinfo import ZoneInfoimport time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events@@ -22,13 +23,18 @@ from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.access_control.backend.models.property_access_control import PropertyAccessControlfrom products.access_control.backend.property_access_control import PropertyAccessLevelfrom products.error_tracking.backend.facade.query_utils import (+ ISSUE_BREAKDOWN_TOP_VALUES,MAX_STACK_FRAMES,+ BreakdownRange,+ breakdown_query_date_range,build_issue_event_where,build_issue_filters,build_search_query,build_sparkline,dedupe_repeated_stacktraces,+ map_issue_breakdown,normalize_stacktrace,+ resolve_breakdown_range,)from products.error_tracking.backend.hogql_queries.error_tracking_query_runner import ErrorTrackingQueryRunnerfrom products.error_tracking.backend.models import (@@ -121,6 +127,99 @@ def test_dedupe_repeated_stacktraces_references_the_first_copy_of_the_stack() ->assert stacks[2][0]["frames"][0]["line"] == 44+BREAKDOWN_NOW = datetime(2026, 4, 24, 12, 0, tzinfo=UTC)+++ [+ ("short_relative_range", {"date_from": "-7d"}, BREAKDOWN_NOW - timedelta(days=7), BREAKDOWN_NOW, False),+ ("long_relative_range", {"date_from": "-90d"}, BREAKDOWN_NOW - timedelta(days=30), BREAKDOWN_NOW, True),+ ("unbounded_range", {"date_from": "all"}, BREAKDOWN_NOW - timedelta(days=30), BREAKDOWN_NOW, True),+ (+ "long_explicit_range",+ {"date_from": "2026-01-01T00:00:00Z", "date_to": "2026-03-01T00:00:00Z"},+ datetime(2026, 1, 30, tzinfo=UTC),+ datetime(2026, 3, 1, tzinfo=UTC),+ True,+ ),+ ]+)+def test_resolve_breakdown_range_limits_the_range_to_30_days(+ _name: str,+ date_range: dict[str, object],+ expected_from: datetime,+ expected_to: datetime,+ expected_limited: bool,+) -> None:+ assert resolve_breakdown_range(date_range, ZoneInfo("UTC"), BREAKDOWN_NOW) == BreakdownRange(+ date_from=expected_from, date_to=expected_to, range_limited=expected_limited+ )+++def test_map_issue_breakdown_drops_empty_values_and_dimensions() -> None:+ long_path = "/" + "a" * 500+ null_label = "$$_posthog_breakdown_null_$$"+ results: dict[str, object] = {+ "$pathname": {+ "values": [{"value": long_path, "count": 3}, {"value": null_label, "count": 1}],+ "total_count": 4,+ },+ "$current_url": {"values": [{"value": "https://example.test/a", "count": 3}], "total_count": 4},+ "$browser": {"values": [{"value": "Chrome", "count": 4}], "total_count": 4},+ "$os": {"values": [{"value": null_label, "count": 4}], "total_count": 4},+ "$session_id": {+ "values": [{"value": null_label, "count": 2}, {"value": "session-1", "count": 2}],+ "total_count": 4,+ },+ }++ breakdown = map_issue_breakdown(results)++ assert breakdown["occurrences"] == 4+ assert breakdown["sample_session_ids"] == ["session-1"]+ top_values = cast(dict[str, Any], breakdown["top_values"])+ # The URL is left out when the events have a path, and a dimension with only missing values is left out.+ assert set(top_values) == {"path", "browser"}+ assert top_values["browser"] == [{"value": "Chrome", "count": 4}]+ assert len(top_values["path"]) == 1+ assert top_values["path"][0]["count"] == 3+ assert len(top_values["path"][0]["value"]) == 200+++def test_map_issue_breakdown_returns_urls_when_events_have_no_path() -> None:+ results: dict[str, object] = {+ "$pathname": {"values": [{"value": "", "count": 2}], "total_count": 2},+ "$current_url": {"values": [{"value": "https://api.example.test/orders", "count": 2}], "total_count": 2},+ }++ top_values = cast(dict[str, Any], map_issue_breakdown(results)["top_values"])++ assert top_values == {"url": [{"value": "https://api.example.test/orders", "count": 2}]}+++ [+ ("relative_range_keeps_the_request", {"date_from": "-7d"}, {"date_from": "-7d", "date_to": None}, False),+ (+ "long_range_is_limited",+ {"date_from": "-90d"},+ {"date_from": (BREAKDOWN_NOW - timedelta(days=30)).isoformat(), "date_to": None},+ True,+ ),+ (+ "relative_date_to_is_resolved",+ {"date_from": "-7d", "date_to": "-1d"},+ {"date_from": "-7d", "date_to": (BREAKDOWN_NOW - timedelta(days=1)).isoformat()},+ False,+ ),+ ]+)+def test_breakdown_query_date_range(+ _name: str, date_range: dict[str, object], expected: dict[str, object], expected_limited: bool+) -> None:+ assert breakdown_query_date_range(date_range, ZoneInfo("UTC"), BREAKDOWN_NOW) == (expected, expected_limited)++class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):issue_id = "01936e7f-d7ff-7314-b2d4-7627981e34f0"fingerprint = "issue-fingerprint"@@ -686,6 +785,119 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):assert response.status_code == 400assert "Access to property '$referrer' is restricted" in str(response.json())+ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)+ def test_issue_detail_omits_breakdown_by_default(self) -> None:+ self.create_issue()+ self.create_exception_event(properties={"$current_url": "https://example.test/checkout"})+ flush_persons_and_events()++ 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 "breakdown" not in response.json()++ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)+ def test_issue_detail_breakdown_aggregates_matching_events(self) -> None:+ self.create_issue()+ for pathname, session_id, lib in [+ ("/checkout", "session-id-1", "web"),+ ("/checkout", "session-id-1", "web"),+ ("/cart", "session-id-2", "web"),+ ("/cart", "", "posthog-python"),+ ("/cart", "", "posthog-python"),+ ]:+ self.create_exception_event(+ properties={+ "$pathname": pathname,+ "$current_url": f"https://example.test{pathname}",+ "$session_id": session_id,+ "$browser": "Chrome",+ "$lib": lib,+ }+ )+ self.create_exception_event(+ issue_id="01936e7f-d7ff-7314-b2d4-7627981e34f1",+ fingerprint="other-fingerprint",+ properties={"$current_url": "https://example.test/other"},+ )+ flush_persons_and_events()++ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issue",+ data={"issueId": self.issue_id, "includeBreakdown": True},+ format="json",+ )++ assert response.status_code == 200+ breakdown = response.json()["breakdown"]+ assert breakdown["occurrences"] == 5+ assert breakdown["range_limited"] is False+ # Sessions with the most events first; events without a session are not a session.+ assert breakdown["sample_session_ids"] == ["session-id-1", "session-id-2"]+ top_values = breakdown["top_values"]+ assert top_values["path"] == [{"value": "/cart", "count": 3}, {"value": "/checkout", "count": 2}]+ assert top_values["browser"] == [{"value": "Chrome", "count": 5}]+ assert top_values["library"] == [{"value": "web", "count": 3}, {"value": "posthog-python", "count": 2}]+ # The URL repeats the path here, and no event has an OS or a screen name.+ assert set(top_values) == {"path", "browser", "library"}++ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)+ def test_issue_detail_breakdown_keeps_empty_values_out_of_top_values(self) -> None:+ self.create_issue()+ for index in range(ISSUE_BREAKDOWN_TOP_VALUES):+ self.create_exception_event(properties={"$pathname": f"/page-{index}"})+ # More events have an empty or no path than have any single real path, so a missing value would take a+ # slot if the query ranked it and the response kept it.+ for _ in range(ISSUE_BREAKDOWN_TOP_VALUES):+ self.create_exception_event(properties={"$pathname": ""})+ self.create_exception_event()+ flush_persons_and_events()++ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issue",+ data={"issueId": self.issue_id, "includeBreakdown": True},+ format="json",+ )++ assert response.status_code == 200+ paths = [item["value"] for item in response.json()["breakdown"]["top_values"]["path"]]+ assert sorted(paths) == sorted(f"/page-{index}" for index in range(ISSUE_BREAKDOWN_TOP_VALUES))++ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)+ def test_issue_detail_breakdown_masks_restricted_properties(self) -> None:+ self.organization.available_product_features = [+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}+ ]+ self.organization.save()+ property_definition = PropertyDefinition.objects.create(+ team=self.team, name="$pathname", type=PropertyDefinition.Type.EVENT+ )+ PropertyAccessControl.objects.create(+ team=self.team,+ property_definition=property_definition,+ access_level=PropertyAccessLevel.NONE.value,+ organization_member=self.organization_membership,+ )+ self.create_issue()+ self.create_exception_event(properties={"$pathname": "/checkout", "$browser": "Chrome"})+ flush_persons_and_events()++ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issue",+ data={"issueId": self.issue_id, "includeBreakdown": True},+ format="json",+ )++ assert response.status_code == 200+ top_values = response.json()["breakdown"]["top_values"]+ assert "path" not in top_values+ assert "/checkout" not in str(response.json())+ assert top_values["browser"] == [{"value": "Chrome", "count": 1}]+@time_machine.travel("2026-04-24T12:00:00Z", tick=False)def test_issue_events_returns_plural_exception_arrays_and_truncates_summary_text(self) -> None:long_text = "x" * 1200diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.tsindex dd0c9b6340eb..0a92bc93b3f8 100644--- a/products/error_tracking/frontend/generated/api.schemas.ts+++ b/products/error_tracking/frontend/generated/api.schemas.ts@@ -1136,6 +1136,8 @@ export interface ErrorTrackingIssueQueryRequestApi {volumeResolution?: number/** Set true to include a compact numeric occurrence sparkline. Defaults to false. */includeSparkline?: boolean+ /** Set true to include the issue page breakdowns: the most common paths (or URLs when events have no path), screens, browsers, OS, libraries, library versions, and app versions, each with a count, plus the sessions with the most events. Covers at most the last 30 days of dateRange. Adds one aggregate query, so request it only to answer where, for whom, or on which platforms the issue happens. Defaults to false. */+ includeBreakdown?: boolean}export interface ErrorTrackingAssigneeResponseApi {@@ -1208,6 +1210,47 @@ export interface ErrorTrackingImpactApi {sessions?: number}+export interface ErrorTrackingBreakdownValueApi {+ /** Property value. */+ value: string+ /** Number of matching events with this value. */+ count: number+}++export interface ErrorTrackingBreakdownTopValuesApi {+ /** Most common $pathname values, most frequent first. */+ path?: ErrorTrackingBreakdownValueApi[]+ /** Most common $current_url values, most frequent first. Returned only when events have no $pathname, as with backend SDKs. */+ url?: ErrorTrackingBreakdownValueApi[]+ /** Most common $screen_name values, most frequent first. */+ screen?: ErrorTrackingBreakdownValueApi[]+ /** Most common $browser values, most frequent first. */+ browser?: ErrorTrackingBreakdownValueApi[]+ /** Most common $os values, most frequent first. */+ os?: ErrorTrackingBreakdownValueApi[]+ /** Most common $lib values, most frequent first. */+ library?: ErrorTrackingBreakdownValueApi[]+ /** Most common $lib_version values, most frequent first. */+ library_version?: ErrorTrackingBreakdownValueApi[]+ /** Most common $app_version values, most frequent first. */+ app_version?: ErrorTrackingBreakdownValueApi[]+}++export interface ErrorTrackingIssueBreakdownApi {+ /** Start of the range that the breakdown covers. */+ date_from: string+ /** End of the range that the breakdown covers. */+ date_to: string+ /** True when the requested range was longer than 30 days and the breakdown covers only the last 30. */+ range_limited: boolean+ /** Matching exception events in the breakdown range. */+ occurrences: number+ /** Up to 5 $session_id values with the most matching events, for session recording lookups. */+ sample_session_ids: string[]+ /** Most common values for each dimension. A dimension with no values is left out. */+ top_values: ErrorTrackingBreakdownTopValuesApi+}+export interface ErrorTrackingIssueDetailApi {/** Error tracking issue ID. */id: string@@ -1262,6 +1305,8 @@ export interface ErrorTrackingIssueDetailApi {impact?: ErrorTrackingImpactApi/** Optional compact occurrence sparkline. */sparkline?: number[]+ /** Aggregate over matching events. Returned only when includeBreakdown is true. */+ breakdown?: ErrorTrackingIssueBreakdownApi}/**diff --git a/products/error_tracking/frontend/generated/api.ts b/products/error_tracking/frontend/generated/api.tsindex 8baa761c2d23..7cfa6af22581 100644--- a/products/error_tracking/frontend/generated/api.ts+++ b/products/error_tracking/frontend/generated/api.ts@@ -1211,7 +1211,7 @@ export const getErrorTrackingQueryIssueCreateUrl = (projectId: string) => {}/**- * Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional sparkline.+ * Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional sparkline and event breakdown.* @summary Get compact error tracking issue details*/export const errorTrackingQueryIssueCreate = async (diff --git a/products/error_tracking/frontend/generated/api.zod.ts b/products/error_tracking/frontend/generated/api.zod.tsindex 7b69071140b2..2b2b3de5d6b3 100644--- a/products/error_tracking/frontend/generated/api.zod.ts+++ b/products/error_tracking/frontend/generated/api.zod.ts@@ -568,7 +568,7 @@ export const ErrorTrackingIssuesBulkCreateBody = /* @__PURE__ */ zod.object({})/**- * Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional sparkline.+ * Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional sparkline and event breakdown.* @summary Get compact error tracking issue details*/export const errorTrackingQueryIssueCreateBodyFilterTestAccountsDefault = true@@ -577,6 +577,7 @@ export const errorTrackingQueryIssueCreateBodyVolumeResolutionMin = 0export const errorTrackingQueryIssueCreateBodyVolumeResolutionMax = 200export const errorTrackingQueryIssueCreateBodyIncludeSparklineDefault = false+export const errorTrackingQueryIssueCreateBodyIncludeBreakdownDefault = falseexport const ErrorTrackingQueryIssueCreateBody = /* @__PURE__ */ zod.object({issueId: zod.uuid().describe('Error tracking issue ID.'),@@ -607,6 +608,12 @@ export const ErrorTrackingQueryIssueCreateBody = /* @__PURE__ */ zod.object({.boolean().default(errorTrackingQueryIssueCreateBodyIncludeSparklineDefault).describe('Set true to include a compact numeric occurrence sparkline. Defaults to false.'),+ includeBreakdown: zod+ .boolean()+ .default(errorTrackingQueryIssueCreateBodyIncludeBreakdownDefault)+ .describe(+ 'Set true to include the issue page breakdowns: the most common paths (or URLs when events have no path), screens, browsers, OS, libraries, library versions, and app versions, each with a count, plus the sessions with the most events. Covers at most the last 30 days of dateRange. Adds one aggregate query, so request it only to answer where, for whom, or on which platforms the issue happens. Defaults to false.'+ ),})/**diff --git a/products/error_tracking/mcp/apps/ErrorIssueView.test.tsx b/products/error_tracking/mcp/apps/ErrorIssueView.test.tsxnew file mode 100644index 000000000000..a2cb2aef4958--- /dev/null+++ b/products/error_tracking/mcp/apps/ErrorIssueView.test.tsx@@ -0,0 +1,76 @@+import { cleanup, render, screen } from '@testing-library/react'+import { type ReactElement } from 'react'++import { ErrorIssueView, formatBreakdownValues } from './ErrorIssueView'++jest.mock(+ '@posthog/mcp-ui',+ () => ({+ DescriptionList: ({ items }: { items: { label: string; value: string }[] }): ReactElement => (+ <dl>+ {items+ .filter((item) => item.value)+ .map((item) => (+ <div key={item.label}>{`${item.label}: ${item.value}`}</div>+ ))}+ </dl>+ ),+ formatDate: (value: string): string => value,+ }),+ { virtual: true }+)++jest.mock(+ '@posthog/quill',+ () => ({+ Badge: ({ children }: { children: ReactElement }): ReactElement => <span>{children}</span>,+ Button: ({ children }: { children: ReactElement }): ReactElement => <span>{children}</span>,+ Card: ({ children }: { children: ReactElement }): ReactElement => <div>{children}</div>,+ CardContent: ({ children }: { children: ReactElement }): ReactElement => <div>{children}</div>,+ }),+ { virtual: true }+)++describe('ErrorIssueView', () => {+ afterEach(cleanup)++ it('formats breakdown values with their counts', () => {+ expect(+ formatBreakdownValues([+ { value: '/checkout', count: 2 },+ { value: '/cart', count: 1 },+ ])+ ).toBe('/checkout (2), /cart (1)')+ expect(formatBreakdownValues(undefined)).toBe('')+ })++ it('shows the breakdown only for dimensions that have values', () => {+ render(+ <ErrorIssueView+ issue={{+ id: 'issue-1',+ name: 'TypeError',+ breakdown: {+ date_from: '2026-04-17T00:00:00Z',+ date_to: '2026-04-24T00:00:00Z',+ range_limited: true,+ occurrences: 3,+ sample_session_ids: ['session-1'],+ top_values: { path: [{ value: '/checkout', count: 3 }] },+ },+ }}+ />+ )++ expect(screen.getByText('Breakdown of 3 events (last 30 days of the range)')).toBeTruthy()+ expect(screen.getByText('Paths: /checkout (3)')).toBeTruthy()+ expect(screen.getByText('Sample session IDs: session-1')).toBeTruthy()+ expect(screen.queryByText(/Browsers:/)).toBeNull()+ })++ it('shows no breakdown when the response has none', () => {+ render(<ErrorIssueView issue={{ id: 'issue-1', name: 'TypeError' }} />)++ expect(screen.queryByText(/Breakdown of/)).toBeNull()+ })+})diff --git a/products/error_tracking/mcp/apps/ErrorIssueView.tsx b/products/error_tracking/mcp/apps/ErrorIssueView.tsxindex c232636a09b2..095295999761 100644--- a/products/error_tracking/mcp/apps/ErrorIssueView.tsx+++ b/products/error_tracking/mcp/apps/ErrorIssueView.tsx@@ -8,6 +8,45 @@ export interface ExternalIssue {integration?: { display_name?: string }}+export interface ErrorIssueBreakdownValue {+ value: string+ count: number+}++export interface ErrorIssueBreakdown {+ date_from: string+ date_to: string+ range_limited: boolean+ occurrences: number+ sample_session_ids: string[]+ top_values: Partial<Record<ErrorIssueBreakdownDimension, ErrorIssueBreakdownValue[]>>+}++export type ErrorIssueBreakdownDimension =+ | 'path'+ | 'url'+ | 'screen'+ | 'browser'+ | 'os'+ | 'library'+ | 'library_version'+ | 'app_version'++const breakdownLabels: Record<ErrorIssueBreakdownDimension, string> = {+ path: 'Paths',+ url: 'URLs',+ screen: 'Screens',+ browser: 'Browsers',+ os: 'OS',+ library: 'Libraries',+ library_version: 'Library versions',+ app_version: 'App versions',+}++export function formatBreakdownValues(values: ErrorIssueBreakdownValue[] | undefined): string {+ return (values ?? []).map(({ value, count }) => `${value} (${count})`).join(', ')+}+export interface ErrorIssueData {id: stringname: string@@ -16,6 +55,7 @@ export interface ErrorIssueData {first_seen?: stringassignee?: { id: string; type: string } | nullexternal_issues?: ExternalIssue[]+ breakdown?: ErrorIssueBreakdown_posthogUrl?: string}@@ -63,6 +103,33 @@ export function ErrorIssueView({ issue }: ErrorIssueViewProps): ReactElement {</CardContent></Card>+ {issue.breakdown && (+ <Card>+ <CardContent>+ <div className="flex flex-col gap-2">+ <span className="text-sm font-semibold">+ Breakdown of {issue.breakdown.occurrences} events+ {issue.breakdown.range_limited ? ' (last 30 days of the range)' : ''}+ </span>+ <DescriptionList+ items={[+ ...(Object.keys(breakdownLabels) as ErrorIssueBreakdownDimension[]).map(+ (dimension) => ({+ label: breakdownLabels[dimension],+ value: formatBreakdownValues(issue.breakdown?.top_values[dimension]),+ })+ ),+ {+ label: 'Sample session IDs',+ value: issue.breakdown.sample_session_ids.join(', '),+ },+ ]}+ />+ </div>+ </CardContent>+ </Card>+ )}+{issue.external_issues && issue.external_issues.length > 0 && (<Card><CardContent>diff --git a/products/error_tracking/mcp/apps/ErrorTracking.stories.tsx b/products/error_tracking/mcp/apps/ErrorTracking.stories.tsxindex e17cb1b9c9eb..82724e87a52b 100644--- a/products/error_tracking/mcp/apps/ErrorTracking.stories.tsx+++ b/products/error_tracking/mcp/apps/ErrorTracking.stories.tsx@@ -83,6 +83,38 @@ export const WithExternalLinks: Story = {name: 'Issue with external links',}+const issueWithBreakdown: ErrorIssueData = {+ ...activeIssue,+ breakdown: {+ date_from: '2025-12-11T00:00:00Z',+ date_to: '2025-12-18T00:00:00Z',+ range_limited: false,+ occurrences: 1240,+ sample_session_ids: ['0193a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b', '0193a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5c'],+ top_values: {+ path: [+ { value: '/project/1/dashboard/42', count: 910 },+ { value: '/project/1/dashboard', count: 330 },+ ],+ browser: [+ { value: 'Chrome', count: 800 },+ { value: 'Safari', count: 440 },+ ],+ os: [{ value: 'Mac OS X', count: 1240 }],+ library: [{ value: 'web', count: 1240 }],+ library_version: [+ { value: '1.300.0', count: 1000 },+ { value: '1.299.2', count: 240 },+ ],+ },+ },+}++export const WithBreakdown: Story = {+ render: () => <ErrorIssueView issue={issueWithBreakdown} />,+ name: 'Issue with breakdown',+}+const sampleListData: ErrorIssueListData = {count: 4,results: [activeIssue, resolvedIssue, issueWithLinks, suppressedIssue],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.mdindex 1a7850f9f817..faf9f76c59b0 100644--- a/products/error_tracking/mcp/prompts/query-error-tracking-issue-events.md+++ b/products/error_tracking/mcp/prompts/query-error-tracking-issue-events.md@@ -1,6 +1,6 @@Fetch sampled `$exception` events for one Error tracking issue.-Use this when the user asks for concrete examples, stack traces, code variables, affected URLs, browser/OS/library context, release details, diagnostics, or Session replay links for a specific issue.+Use this when the user asks for concrete examples, stack traces, code variables, release details, diagnostics, or trace IDs for a specific issue. To learn which URLs, browsers, OS, or versions an issue affects, call `query-error-tracking-issue` with `includeBreakdown: true` instead of fetching many events.Returns sampled events with plural exception fields (`$exception_types`, `$exception_values`), normalized `$exception_list`, `$exception_fingerprint`, `$exception_level`, `$exception_handled`, `$session_id`, OpenTelemetry and AI trace/span IDs, `$lib`, browser/OS fields, and `$current_url`.diff --git a/products/error_tracking/mcp/prompts/query-error-tracking-issue.md b/products/error_tracking/mcp/prompts/query-error-tracking-issue.mdindex 1427063774af..17643c6327a9 100644--- a/products/error_tracking/mcp/prompts/query-error-tracking-issue.md+++ b/products/error_tracking/mcp/prompts/query-error-tracking-issue.md@@ -10,7 +10,10 @@ Defaults are intentionally useful: last 7 days, test accounts filtered out, aggr- `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.+- `includeBreakdown`: set true when the user asks where, for whom, or on which platforms the issue happens. It returns the same breakdowns as the issue page, over all matching events: the most common paths (or URLs, when events have no path, as with backend SDKs), screens, browsers, OS, libraries, library versions, and app versions, each with a count, and up to 5 `$session_id` values with the most events. It covers at most the last 30 days of `dateRange`; `range_limited` is true when it covers less than you asked for. Empty dimensions are left out.# 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.+Use `query-error-tracking-issue-events` with the same `issueId` only when the user needs a concrete event, a stack trace, code variables, OpenTelemetry trace IDs, or the handled flag. Do not fetch many events to count browsers, URLs, or versions; use `includeBreakdown` instead.++When `sample_session_ids` is not empty and the user asks what happened before the error, call `query-session-recordings-list` with `session_ids`.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 6758e0422338..e4c6248dc2fa 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -9736,7 +9736,7 @@"feature_flag": "tracing"},"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, severity, 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.",+ "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, severity, 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- `includeBreakdown`: set true when the user asks where, for whom, or on which platforms the issue happens. It returns the same breakdowns as the issue page, over all matching events: the most common paths (or URLs, when events have no path, as with backend SDKs), screens, browsers, OS, libraries, library versions, and app versions, each with a count, and up to 5 `$session_id` values with the most events. It covers at most the last 30 days of `dateRange`; `range_limited` is true when it covers less than you asked for. Empty dimensions are left out.\n\n# Next steps\n\nUse `query-error-tracking-issue-events` with the same `issueId` only when the user needs a concrete event, a stack trace, code variables, OpenTelemetry trace IDs, or the handled flag. Do not fetch many events to count browsers, URLs, or versions; use `includeBreakdown` instead.\n\nWhen `sample_session_ids` is not empty and the user asks what happened before the error, call `query-session-recordings-list` with `session_ids`.","category": "Error tracking","feature": "error_tracking","summary": "Query error tracking issue",@@ -9751,7 +9751,7 @@"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, code variables, affected URLs, browser/OS/library context, release details, diagnostics, 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_level`, `$exception_handled`, `$session_id`, OpenTelemetry and AI trace/span IDs, `$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- `include`: context groups to return. Defaults to compact exception, environment, navigation, and correlation context. Add `stacktrace`, `code_variables`, `release`, or `diagnostics` only when needed. `code_variables` implies stack frames and may contain SDK-masked sensitive values.\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# Stack traces\n\n- A stack trace keeps at most the 50 frames closest to the error. `frames_omitted` gives the number of older frames that were left out.\n- When a stack trace is the same as one returned earlier on the page, its `stacktrace` is `{\"same_as_event\": \"<uuid>\", \"same_as_exception\": <index>}`. Read the frames from that event, at that index of its `$exception_list`. The event can be the same event, when two of its exceptions share a stack.\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.",+ "description": "Fetch sampled `$exception` events for one Error tracking issue.\n\nUse this when the user asks for concrete examples, stack traces, code variables, release details, diagnostics, or trace IDs for a specific issue. To learn which URLs, browsers, OS, or versions an issue affects, call `query-error-tracking-issue` with `includeBreakdown: true` instead of fetching many events.\n\nReturns sampled events with plural exception fields (`$exception_types`, `$exception_values`), normalized `$exception_list`, `$exception_fingerprint`, `$exception_level`, `$exception_handled`, `$session_id`, OpenTelemetry and AI trace/span IDs, `$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- `include`: context groups to return. Defaults to compact exception, environment, navigation, and correlation context. Add `stacktrace`, `code_variables`, `release`, or `diagnostics` only when needed. `code_variables` implies stack frames and may contain SDK-masked sensitive values.\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# Stack traces\n\n- A stack trace keeps at most the 50 frames closest to the error. `frames_omitted` gives the number of older frames that were left out.\n- When a stack trace is the same as one returned earlier on the page, its `stacktrace` is `{\"same_as_event\": \"<uuid>\", \"same_as_exception\": <index>}`. Read the frames from that event, at that index of its `$exception_list`. The event can be the same event, when two of its exceptions share a stack.\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",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 471ef6e4a9b3..65b2ecfa7b25 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -10297,7 +10297,7 @@"feature_flag": "tracing"},"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, severity, 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.",+ "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, severity, 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- `includeBreakdown`: set true when the user asks where, for whom, or on which platforms the issue happens. It returns the same breakdowns as the issue page, over all matching events: the most common paths (or URLs, when events have no path, as with backend SDKs), screens, browsers, OS, libraries, library versions, and app versions, each with a count, and up to 5 `$session_id` values with the most events. It covers at most the last 30 days of `dateRange`; `range_limited` is true when it covers less than you asked for. Empty dimensions are left out.\n\n# Next steps\n\nUse `query-error-tracking-issue-events` with the same `issueId` only when the user needs a concrete event, a stack trace, code variables, OpenTelemetry trace IDs, or the handled flag. Do not fetch many events to count browsers, URLs, or versions; use `includeBreakdown` instead.\n\nWhen `sample_session_ids` is not empty and the user asks what happened before the error, call `query-session-recordings-list` with `session_ids`.","category": "Error tracking","feature": "error_tracking","summary": "Query error tracking issue",@@ -10312,7 +10312,7 @@"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, code variables, affected URLs, browser/OS/library context, release details, diagnostics, 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_level`, `$exception_handled`, `$session_id`, OpenTelemetry and AI trace/span IDs, `$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- `include`: context groups to return. Defaults to compact exception, environment, navigation, and correlation context. Add `stacktrace`, `code_variables`, `release`, or `diagnostics` only when needed. `code_variables` implies stack frames and may contain SDK-masked sensitive values.\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# Stack traces\n\n- A stack trace keeps at most the 50 frames closest to the error. `frames_omitted` gives the number of older frames that were left out.\n- When a stack trace is the same as one returned earlier on the page, its `stacktrace` is `{\"same_as_event\": \"<uuid>\", \"same_as_exception\": <index>}`. Read the frames from that event, at that index of its `$exception_list`. The event can be the same event, when two of its exceptions share a stack.\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.",+ "description": "Fetch sampled `$exception` events for one Error tracking issue.\n\nUse this when the user asks for concrete examples, stack traces, code variables, release details, diagnostics, or trace IDs for a specific issue. To learn which URLs, browsers, OS, or versions an issue affects, call `query-error-tracking-issue` with `includeBreakdown: true` instead of fetching many events.\n\nReturns sampled events with plural exception fields (`$exception_types`, `$exception_values`), normalized `$exception_list`, `$exception_fingerprint`, `$exception_level`, `$exception_handled`, `$session_id`, OpenTelemetry and AI trace/span IDs, `$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- `include`: context groups to return. Defaults to compact exception, environment, navigation, and correlation context. Add `stacktrace`, `code_variables`, `release`, or `diagnostics` only when needed. `code_variables` implies stack frames and may contain SDK-masked sensitive values.\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# Stack traces\n\n- A stack trace keeps at most the 50 frames closest to the error. `frames_omitted` gives the number of older frames that were left out.\n- When a stack trace is the same as one returned earlier on the page, its `stacktrace` is `{\"same_as_event\": \"<uuid>\", \"same_as_exception\": <index>}`. Read the frames from that event, at that index of its `$exception_list`. The event can be the same event, when two of its exceptions share a stack.\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",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7d497d357bf6..4309d48f3c06 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -36886,6 +36886,32 @@ export namespace Schemas {assignee?: ErrorTrackingAssignmentRuleAssigneeRequest | null;}+ export interface ErrorTrackingBreakdownValue {+ /** Property value. */+ value: string;+ /** Number of matching events with this value. */+ count: number;+ }++ export interface ErrorTrackingBreakdownTopValues {+ /** Most common $pathname values, most frequent first. */+ path?: ErrorTrackingBreakdownValue[];+ /** Most common $current_url values, most frequent first. Returned only when events have no $pathname, as with backend SDKs. */+ url?: ErrorTrackingBreakdownValue[];+ /** Most common $screen_name values, most frequent first. */+ screen?: ErrorTrackingBreakdownValue[];+ /** Most common $browser values, most frequent first. */+ browser?: ErrorTrackingBreakdownValue[];+ /** Most common $os values, most frequent first. */+ os?: ErrorTrackingBreakdownValue[];+ /** Most common $lib values, most frequent first. */+ library?: ErrorTrackingBreakdownValue[];+ /** Most common $lib_version values, most frequent first. */+ library_version?: ErrorTrackingBreakdownValue[];+ /** Most common $app_version values, most frequent first. */+ app_version?: ErrorTrackingBreakdownValue[];+ }+export interface Results {total_count: number;values: BreakdownValue[];@@ -37216,6 +37242,21 @@ export namespace Schemas {type: AssigneeTypeEnum;}+ export interface ErrorTrackingIssueBreakdown {+ /** Start of the range that the breakdown covers. */+ date_from: string;+ /** End of the range that the breakdown covers. */+ date_to: string;+ /** True when the requested range was longer than 30 days and the breakdown covers only the last 30. */+ range_limited: boolean;+ /** Matching exception events in the breakdown range. */+ occurrences: number;+ /** Up to 5 $session_id values with the most matching events, for session recording lookups. */+ sample_session_ids: string[];+ /** Most common values for each dimension. A dimension with no values is left out. */+ top_values: ErrorTrackingBreakdownTopValues;+ }+/*** * `set_status` - set_status* * `assign` - assign@@ -37362,6 +37403,8 @@ export namespace Schemas {impact?: ErrorTrackingImpact;/** Optional compact occurrence sparkline. */sparkline?: number[];+ /** Aggregate over matching events. Returned only when includeBreakdown is true. */+ breakdown?: ErrorTrackingIssueBreakdown;}/**@@ -37600,6 +37643,8 @@ export namespace Schemas {volumeResolution?: number;/** Set true to include a compact numeric occurrence sparkline. Defaults to false. */includeSparkline?: boolean;+ /** Set true to include the issue page breakdowns: the most common paths (or URLs when events have no path), screens, browsers, OS, libraries, library versions, and app versions, each with a count, plus the sessions with the most events. Covers at most the last 30 days of dateRange. Adds one aggregate query, so request it only to answer where, for whom, or on which platforms the issue happens. Defaults to false. */+ includeBreakdown?: boolean;}/**diff --git a/services/mcp/src/generated/error_tracking/api.ts b/services/mcp/src/generated/error_tracking/api.tsindex 2ccdaf3e6ddc..ebd483a705ed 100644--- a/services/mcp/src/generated/error_tracking/api.ts+++ b/services/mcp/src/generated/error_tracking/api.ts@@ -8091,7 +8091,7 @@ export const ErrorTrackingIssuesSplitCreateBody = () => zod.object({})/**- * Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional sparkline.+ * Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional sparkline and event breakdown.* @summary Get compact error tracking issue details*/export const ErrorTrackingQueryIssueCreateParams = () => zod.object({@@ -8108,6 +8108,7 @@ export const errorTrackingQueryIssueCreateBodyVolumeResolutionMin = 0export const errorTrackingQueryIssueCreateBodyVolumeResolutionMax = 200export const errorTrackingQueryIssueCreateBodyIncludeSparklineDefault = false+export const errorTrackingQueryIssueCreateBodyIncludeBreakdownDefault = falseexport const ErrorTrackingQueryIssueCreateBody = () => zod.object({issueId: zod.string().describe('Error tracking issue ID.'),@@ -8138,6 +8139,12 @@ export const ErrorTrackingQueryIssueCreateBody = () => zod.object({.boolean().default(errorTrackingQueryIssueCreateBodyIncludeSparklineDefault).describe('Set true to include a compact numeric occurrence sparkline. Defaults to false.'),+ includeBreakdown: zod+ .boolean()+ .default(errorTrackingQueryIssueCreateBodyIncludeBreakdownDefault)+ .describe(+ 'Set true to include the issue page breakdowns: the most common paths (or URLs when events have no path), screens, browsers, OS, libraries, library versions, and app versions, each with a count, plus the sessions with the most events. Covers at most the last 30 days of dateRange. Adds one aggregate query, so request it only to answer where, for whom, or on which platforms the issue happens. Defaults to false.'+ ),})/**diff --git a/services/mcp/src/tools/generated/error_tracking.ts b/services/mcp/src/tools/generated/error_tracking.tsindex e8536cdd3fa5..6bb5d39778e4 100644--- a/services/mcp/src/tools/generated/error_tracking.ts+++ b/services/mcp/src/tools/generated/error_tracking.ts@@ -771,6 +771,9 @@ const queryErrorTrackingIssue = (): ToolBase<if (params.includeSparkline !== undefined) {body['includeSparkline'] = params.includeSparkline}+ if (params.includeBreakdown !== undefined) {+ body['includeBreakdown'] = params.includeBreakdown+ }const result = await context.api.request<Schemas.ErrorTrackingIssueDetail>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/error_tracking/query/issue/`,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-error-tracking-issue.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-error-tracking-issue.jsonindex 373c147e99b2..62fc67dd92e5 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-error-tracking-issue.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-error-tracking-issue.json@@ -27,6 +27,11 @@"description": "When true, exclude internal/test account data from results. Defaults to true.","type": "boolean"},+ "includeBreakdown": {+ "default": false,+ "description": "Set true to include the issue page breakdowns: the most common paths (or URLs when events have no path), screens, browsers, OS, libraries, library versions, and app versions, each with a count, plus the sessions with the most events. Covers at most the last 30 days of dateRange. Adds one aggregate query, so request it only to answer where, for whom, or on which platforms the issue happens. Defaults to false.",+ "type": "boolean"+ },"includeSparkline": {"default": false,"description": "Set true to include a compact numeric occurrence sparkline. Defaults to false.",