Skip to content

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

fix(tracing): bound apm-spans-aggregate default response size (#72019)

posthog[bot]395208cfae01
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index ca88d1a07d39..8b30dd900583 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -3000,11 +3000,15 @@ const api = {
serviceNames?: string[]
filterGroup?: PropertyGroupFilter
compareFilter?: { compare?: boolean; compare_to?: string | null }
+ limit?: number
+ offset?: number
},
signal?: AbortSignal
): Promise<{
results: AggregatedSpanRow[]
compare?: AggregatedSpanRow[] | null
+ has_more?: boolean
+ next_offset?: number | null
}> {
return new ApiRequest().tracingSpans().withAction('aggregate').create({ signal, data: { query } })
},
diff --git a/products/tracing/backend/aggregation_query_runner.py b/products/tracing/backend/aggregation_query_runner.py
index 8629d4b74929..565b31c2e989 100644
--- a/products/tracing/backend/aggregation_query_runner.py
+++ b/products/tracing/backend/aggregation_query_runner.py
@@ -55,18 +55,14 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange
from posthog.models.filters.mixins.utils import cached_property
-from .logic import TIME_BUCKET_DATE_RANGE_WHERE, translate_span_filter, with_span_attribute_type_suffix
+# _ROW_LIMIT lives in logic.py so the presentation layer can reach it through the
+# facade-allowed `logic` module; imported here (and re-exported) for the sibling runners.
+from .logic import _ROW_LIMIT, TIME_BUCKET_DATE_RANGE_WHERE, translate_span_filter, with_span_attribute_type_suffix
if TYPE_CHECKING:
from posthog.models import Team, User
-# Hard cap on number of rows returned per period. Keeps payloads bounded when name
-# cardinality blows up (e.g. untemplated URL paths). The flame graph collapses long
-# tails anyway so the lower-ranked rows aren't visible.
-_ROW_LIMIT = 5000
-
-
class _SpanAggregationMixin:
"""Shared scaffolding for the two span aggregation runners.
@@ -246,11 +242,20 @@ class TraceSpansAggregationQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunn
query: TraceSpansAggregationQuery
cached_response: CachedTraceSpansAggregationQueryResponse
- def __init__(self, query: TraceSpansAggregationQuery, *args, **kwargs) -> None:
+ def __init__(
+ self,
+ query: TraceSpansAggregationQuery,
+ *args,
+ limit: int | None = None,
+ offset: int = 0,
+ **kwargs,
+ ) -> None:
super().__init__(query, *args, **kwargs)
self.modifiers.convertToProjectTimezone = False
self.modifiers.propertyGroupsMode = PropertyGroupsMode.OPTIMIZED
self._extract_filters()
+ self._limit = _ROW_LIMIT if limit is None else max(1, min(limit, _ROW_LIMIT))
+ self._offset = max(0, offset)
def _calculate(self) -> TraceSpansAggregationQueryResponse:
current_rows, previous_rows = self._run_with_compare()
@@ -278,10 +283,12 @@ class TraceSpansAggregationQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunn
GROUP BY service_name, name
ORDER BY total_duration_nano DESC
LIMIT {limit}
+ OFFSET {offset}
""",
placeholders={
"where": self._where_without_date_range(),
- "limit": ast.Constant(value=_ROW_LIMIT),
+ "limit": ast.Constant(value=self._limit),
+ "offset": ast.Constant(value=self._offset),
**query_date_range.to_placeholders(),
},
)
diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.py
index f8d2bafa0195..4d3f5e87967f 100644
--- a/products/tracing/backend/logic.py
+++ b/products/tracing/backend/logic.py
@@ -59,6 +59,18 @@ TIME_BUCKET_DATE_RANGE_WHERE = (
"and toStartOfDay(time_bucket, 'UTC') <= toStartOfDay({date_to}, 'UTC')"
)
+# Hard cap on number of rows returned per period by the span aggregation runners. Keeps
+# payloads bounded when name cardinality blows up (e.g. untemplated URL paths). The flame
+# graph collapses long tails anyway so the lower-ranked rows aren't visible.
+_ROW_LIMIT = 5000
+
+# Default row cap for the flat aggregation when a caller does not pass an explicit `limit`.
+# Kept small because this endpoint feeds agent/MCP callers, where the full 5000-row tail can
+# push a single response past a million tokens once name cardinality blows up. Rows are
+# ordered by total_duration_nano DESC, so the default still surfaces the heaviest operations;
+# callers that need the long tail opt into a higher `limit` (up to _ROW_LIMIT) or paginate.
+DEFAULT_AGGREGATION_ROW_LIMIT = 100
+
# Value-search probes attribute_value with ILIKE %search%, which scans far more rows than
# the key-only path. Require a meaningfully specific term so short prefixes (e.g. "id")
# don't trigger an expensive scan.
@@ -1069,6 +1081,8 @@ def run_aggregation_query(
compare_filter: CompareFilter | None = None,
filter_group: PropertyGroupFilter | None = None,
service_names: list[str] | None = None,
+ limit: int | None = None,
+ offset: int = 0,
) -> TraceSpansAggregationQueryResponse | CachedTraceSpansAggregationQueryResponse:
"""Facade-friendly entry point for running a flat span aggregation query."""
# The runners import `translate_span_filter` from this module, so a module-level import here is circular.
@@ -1080,7 +1094,7 @@ def run_aggregation_query(
filterGroup=filter_group,
serviceNames=service_names,
)
- runner = TraceSpansAggregationQueryRunner(query, team)
+ runner = TraceSpansAggregationQueryRunner(query, team, limit=limit, offset=offset)
response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
assert isinstance(response, TraceSpansAggregationQueryResponse | CachedTraceSpansAggregationQueryResponse)
return response
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index b5e51df998be..06235c86ff78 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -53,6 +53,8 @@ from ..facade.api import (
)
from ..has_spans_query_runner import team_has_spans
from ..logic import (
+ _ROW_LIMIT,
+ DEFAULT_AGGREGATION_ROW_LIMIT,
TraceSpansQueryRunner,
run_aggregation_query,
run_attribute_names_query,
@@ -382,12 +384,63 @@ class _TracingAggregationQueryBodySerializer(serializers.Serializer):
default=[],
help_text="Property filters applied to spans in both windows.",
)
+ limit = serializers.IntegerField(
+ required=False,
+ min_value=1,
+ max_value=_ROW_LIMIT,
+ help_text=(
+ f"Max rows to return, ordered by total_duration_nano DESC. Defaults to {DEFAULT_AGGREGATION_ROW_LIMIT}; "
+ f"hard max {_ROW_LIMIT}. Keep this small to bound the response size — a high value on high-cardinality "
+ "span names (e.g. untemplated URL paths) returns a very large payload. Prefer narrowing with "
+ "`serviceNames`/`filterGroup` over raising the limit."
+ ),
+ )
+ offset = serializers.IntegerField(
+ required=False,
+ min_value=0,
+ help_text=(
+ "Row offset for pagination. Combine with `limit` and the `next_offset` returned in the response to page "
+ "through results beyond the first page."
+ ),
+ )
class _TracingAggregationRequestSerializer(serializers.Serializer):
query = _TracingAggregationQueryBodySerializer(help_text="The span aggregation query to execute.")
+class _AggregatedSpanRowSerializer(serializers.Serializer):
+ service_name = serializers.CharField(help_text="Service that emitted the spans in this group.")
+ name = serializers.CharField(help_text="Span name (operation) for this group.")
+ count = serializers.IntegerField(help_text="Number of spans matched in this group.")
+ total_duration_nano = serializers.FloatField(help_text="Sum of span durations in nanoseconds.")
+ avg_duration_nano = serializers.FloatField(help_text="Average span duration in nanoseconds.")
+ p50_duration_nano = serializers.FloatField(help_text="Median span duration in nanoseconds.")
+ p95_duration_nano = serializers.FloatField(help_text="95th percentile span duration in nanoseconds.")
+ p99_duration_nano = serializers.FloatField(help_text="99th percentile span duration in nanoseconds.")
+ p999_duration_nano = serializers.FloatField(help_text="99.9th percentile span duration in nanoseconds.")
+ error_count = serializers.IntegerField(help_text="Spans with OTel status code Error (status_code = 2).")
+
+
+class _TracingAggregationResponseSerializer(serializers.Serializer):
+ results = _AggregatedSpanRowSerializer(
+ many=True,
+ help_text="One row per (service_name, name) group, ordered by total_duration_nano descending.",
+ )
+ compare = _AggregatedSpanRowSerializer(
+ many=True,
+ allow_null=True,
+ help_text="Rows for the comparison window when compareFilter.compare is true, else null.",
+ )
+ has_more = serializers.BooleanField(
+ help_text="True when more rows exist beyond this page — page further with `next_offset`, or narrow the query."
+ )
+ next_offset = serializers.IntegerField(
+ allow_null=True,
+ help_text="Offset to request the next page, or null when this is the last page.",
+ )
+
+
class _TracingAttributeBreakdownQueryBodySerializer(serializers.Serializer):
breakdownKey = serializers.CharField(
required=True,
@@ -669,6 +722,17 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
return filter_group
return {"type": "AND", "values": []}
+ @staticmethod
+ def _parse_positive_int(value: object, default: int, *, minimum: int) -> int:
+ """Coerce an untrusted JSON value to an int no smaller than `minimum`, falling back to `default`."""
+ if not isinstance(value, int | str | float) or isinstance(value, bool):
+ return default
+ try:
+ parsed = int(value)
+ except (TypeError, ValueError):
+ return default
+ return max(minimum, parsed)
+
def _report_usage(self, request: Request, event: str, properties: dict) -> None:
# Usage telemetry must never turn a successful read into a 5xx, so swallow and record any failure.
try:
@@ -1030,7 +1094,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
return Response({"results": response.results}, status=status.HTTP_200_OK)
- @extend_schema(request=_TracingAggregationRequestSerializer)
+ @extend_schema(request=_TracingAggregationRequestSerializer, responses={200: _TracingAggregationResponseSerializer})
@action(detail=False, methods=["POST"], url_path="aggregate", required_scopes=["tracing:read"])
def aggregate(self, request: Request, *args, **kwargs) -> Response:
tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
@@ -1054,19 +1118,36 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
except (ValidationError, ValueError, ParseError):
compare_filter = None
+ # Bound the payload: default to a conservative page so agent/MCP callers don't pull the
+ # full high-cardinality tail. Callers opt into more via `limit`/`offset`.
+ limit = self._parse_positive_int(query_data.get("limit"), DEFAULT_AGGREGATION_ROW_LIMIT, minimum=1)
+ limit = min(limit, _ROW_LIMIT)
+ offset = self._parse_positive_int(query_data.get("offset"), 0, minimum=0)
+
+ # Over-fetch one row so we can report `has_more` without a separate count query.
response = run_aggregation_query(
team=self.team,
date_range=date_range,
compare_filter=compare_filter,
filter_group=filter_group,
service_names=query_data.get("serviceNames", None),
+ limit=min(limit + 1, _ROW_LIMIT),
+ offset=offset,
)
+ results = list(response.results)
+ has_more = len(results) > limit
+ results = results[:limit]
+ compare_rows = list(response.compare)[:limit] if response.compare else None
+
self._report_usage(
request,
"tracing aggregation queried",
{
- "results_count": len(response.results),
+ "results_count": len(results),
+ "has_more": has_more,
+ "limit": limit,
+ "offset": offset,
"has_compare": bool(query_data.get("compareFilter")),
"has_filter_group": bool(query_data.get("filterGroup")),
"service_names_count": len(query_data.get("serviceNames") or []),
@@ -1075,8 +1156,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
return Response(
{
- "results": [row.model_dump() for row in response.results],
- "compare": [row.model_dump() for row in (response.compare or [])] if response.compare else None,
+ "results": [row.model_dump() for row in results],
+ "compare": [row.model_dump() for row in compare_rows] if compare_rows is not None else None,
+ "has_more": has_more,
+ "next_offset": offset + limit if has_more else None,
},
status=status.HTTP_200_OK,
)
diff --git a/products/tracing/backend/tests/test_aggregation_endpoint.py b/products/tracing/backend/tests/test_aggregation_endpoint.py
new file mode 100644
index 000000000000..25547a2c107a
--- /dev/null
+++ b/products/tracing/backend/tests/test_aggregation_endpoint.py
@@ -0,0 +1,69 @@
+import datetime as dt
+
+from parameterized import parameterized
+
+from posthog.clickhouse.client import sync_execute
+
+from products.tracing.backend.logic import _ROW_LIMIT, DEFAULT_AGGREGATION_ROW_LIMIT
+from products.tracing.backend.tests.test_keyset_pagination import DATE_FROM, DATE_TO, _b64, _TraceSpansTestBase
+
+
+class TestTraceSpansAggregationEndpoint(_TraceSpansTestBase):
+ SERVICE = "web"
+ # More distinct (service, name) groups than the default page, so an unbounded response would
+ # return the full high-cardinality tail — the payload blow-up this endpoint must cap by default.
+ TOTAL_NAMES = DEFAULT_AGGREGATION_ROW_LIMIT + 20
+
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ cls._recreate_trace_spans_tables()
+
+ base_ts = dt.datetime(2026, 6, 2, 8, 0, 0)
+ start_str = base_ts.strftime("%Y-%m-%d %H:%M:%S.%f")
+ rows: list[str] = []
+ for i in range(cls.TOTAL_NAMES):
+ # Duration decreases with i so total_duration_nano DESC ordering is deterministic.
+ end_str = (base_ts + dt.timedelta(milliseconds=cls.TOTAL_NAMES - i)).strftime("%Y-%m-%d %H:%M:%S.%f")
+ rows.append(
+ f"('019e8770-0000-0000-0000-{i:012d}', {cls.team.id}, '{_b64(i.to_bytes(16, 'big'))}', "
+ f"'{_b64(i.to_bytes(8, 'big'))}', '', 'GET /api/thing/{i}', 2, "
+ f"'{start_str}', '{end_str}', '{start_str}', 0, '{cls.SERVICE}')"
+ )
+ sync_execute(
+ "INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "
+ "timestamp, end_time, observed_timestamp, status_code, service_name) VALUES " + ",".join(rows)
+ )
+
+ def _aggregate(self, **query_fields) -> dict:
+ query: dict = {"dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO}, **query_fields}
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/tracing/spans/aggregate/",
+ {"query": query},
+ format="json",
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ return response.json()
+
+ def test_default_query_caps_rows_and_reports_more(self):
+ data = self._aggregate()
+ self.assertEqual(len(data["results"]), DEFAULT_AGGREGATION_ROW_LIMIT)
+ self.assertTrue(data["has_more"])
+ self.assertEqual(data["next_offset"], DEFAULT_AGGREGATION_ROW_LIMIT)
+
+ def test_explicit_limit_opts_into_the_full_tail(self):
+ # The cap is a default, not a hard loss: callers can still page the whole set in.
+ data = self._aggregate(limit=_ROW_LIMIT)
+ self.assertEqual(len(data["results"]), self.TOTAL_NAMES)
+ self.assertFalse(data["has_more"])
+ self.assertIsNone(data["next_offset"])
+
+ @parameterized.expand([("first_page", 0), ("second_page", 60)])
+ def test_offset_pages_are_disjoint(self, _name, offset):
+ page_size = 60
+ data = self._aggregate(limit=page_size, offset=offset)
+ names = [row["name"] for row in data["results"]]
+ self.assertEqual(len(names), len(set(names)))
+ expected_more = offset + page_size < self.TOTAL_NAMES
+ self.assertEqual(data["has_more"], expected_more)
+ self.assertEqual(data["next_offset"], offset + page_size if expected_more else None)
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index f77c691beb9e..3eb7d1cd2858 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -106,6 +106,17 @@ export interface _TracingAggregationQueryBodyApi {
serviceNames?: string[]
/** Property filters applied to spans in both windows. */
filterGroup?: _SpanPropertyFilterApi[]
+ /**
+ * Max rows to return, ordered by total_duration_nano DESC. Defaults to 100; hard max 5000. Keep this small to bound the response size — a high value on high-cardinality span names (e.g. untemplated URL paths) returns a very large payload. Prefer narrowing with `serviceNames`/`filterGroup` over raising the limit.
+ * @minimum 1
+ * @maximum 5000
+ */
+ limit?: number
+ /**
+ * Row offset for pagination. Combine with `limit` and the `next_offset` returned in the response to page through results beyond the first page.
+ * @minimum 0
+ */
+ offset?: number
}
export interface _TracingAggregationRequestApi {
@@ -113,6 +124,46 @@ export interface _TracingAggregationRequestApi {
query: _TracingAggregationQueryBodyApi
}
+export interface _AggregatedSpanRowApi {
+ /** Service that emitted the spans in this group. */
+ service_name: string
+ /** Span name (operation) for this group. */
+ name: string
+ /** Number of spans matched in this group. */
+ count: number
+ /** Sum of span durations in nanoseconds. */
+ total_duration_nano: number
+ /** Average span duration in nanoseconds. */
+ avg_duration_nano: number
+ /** Median span duration in nanoseconds. */
+ p50_duration_nano: number
+ /** 95th percentile span duration in nanoseconds. */
+ p95_duration_nano: number
+ /** 99th percentile span duration in nanoseconds. */
+ p99_duration_nano: number
+ /** 99.9th percentile span duration in nanoseconds. */
+ p999_duration_nano: number
+ /** Spans with OTel status code Error (status_code = 2). */
+ error_count: number
+}
+
+export interface _TracingAggregationResponseApi {
+ /** One row per (service_name, name) group, ordered by total_duration_nano descending. */
+ results: _AggregatedSpanRowApi[]
+ /**
+ * Rows for the comparison window when compareFilter.compare is true, else null.
+ * @nullable
+ */
+ compare: _AggregatedSpanRowApi[] | null
+ /** True when more rows exist beyond this page — page further with `next_offset`, or narrow the query. */
+ has_more: boolean
+ /**
+ * Offset to request the next page, or null when this is the last page.
+ * @nullable
+ */
+ next_offset: number | null
+}
+
/**
* * `count` - count
* * `error_count` - error_count
diff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.ts
index a6da1adab149..00c744372463 100644
--- a/products/tracing/frontend/generated/api.ts
+++ b/products/tracing/frontend/generated/api.ts
@@ -20,6 +20,7 @@ import type {
_SymbolStatsRequestApi,
_SymbolStatsResponseApi,
_TracingAggregationRequestApi,
+ _TracingAggregationResponseApi,
_TracingAttributeBreakdownRequestApi,
_TracingAttributeBreakdownResponseApi,
_TracingAttributesResponseApi,
@@ -59,8 +60,8 @@ export const tracingSpansAggregateCreate = async (
projectId: string,
_tracingAggregationRequestApi: _TracingAggregationRequestApi,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getTracingSpansAggregateCreateUrl(projectId), {
+): Promise<_TracingAggregationResponseApi> => {
+ return apiMutator<_TracingAggregationResponseApi>(getTracingSpansAggregateCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.ts
index dc81446e9c28..12b63ce18f1b 100644
--- a/products/tracing/frontend/generated/api.zod.ts
+++ b/products/tracing/frontend/generated/api.zod.ts
@@ -11,6 +11,9 @@ import * as zod from 'zod'
export const tracingSpansAggregateCreateBodyQueryOneCompareFilterOneCompareDefault = false
export const tracingSpansAggregateCreateBodyQueryOneFilterGroupDefault = []
+export const tracingSpansAggregateCreateBodyQueryOneLimitMax = 5000
+
+export const tracingSpansAggregateCreateBodyQueryOneOffsetMin = 0
export const TracingSpansAggregateCreateBody = /* @__PURE__ */ zod.object({
query: zod
@@ -95,6 +98,21 @@ export const TracingSpansAggregateCreateBody = /* @__PURE__ */ zod.object({
)
.default(tracingSpansAggregateCreateBodyQueryOneFilterGroupDefault)
.describe('Property filters applied to spans in both windows.'),
+ limit: zod
+ .number()
+ .min(1)
+ .max(tracingSpansAggregateCreateBodyQueryOneLimitMax)
+ .optional()
+ .describe(
+ 'Max rows to return, ordered by total_duration_nano DESC. Defaults to 100; hard max 5000. Keep this small to bound the response size — a high value on high-cardinality span names (e.g. untemplated URL paths) returns a very large payload. Prefer narrowing with `serviceNames`\/`filterGroup` over raising the limit.'
+ ),
+ offset: zod
+ .number()
+ .min(tracingSpansAggregateCreateBodyQueryOneOffsetMin)
+ .optional()
+ .describe(
+ 'Row offset for pagination. Combine with `limit` and the `next_offset` returned in the response to page through results beyond the first page.'
+ ),
})
.describe('The span aggregation query to execute.'),
})
diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.ts
index c903d7b432a7..7b285fe2d3d2 100644
--- a/products/tracing/frontend/tracingDataLogic.ts
+++ b/products/tracing/frontend/tracingDataLogic.ts
@@ -73,6 +73,9 @@ export interface VisibleSpanTimeRange {
}
const DEFAULT_PAGE_SIZE = 100
+// Matches the backend's hard cap (_ROW_LIMIT) for span aggregation. The Operations tab needs
+// the full set for client-side sort/filter, unlike the smaller default the endpoint serves agents.
+const OPERATIONS_AGGREGATION_LIMIT = 5000
export const PREFETCH_SPANS = 20
export const NEW_QUERY_STARTED_ERROR_MESSAGE = 'new query started' as const
@@ -1071,6 +1074,9 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
compare,
compare_to: new Date(window.previousStartMs).toISOString(),
},
+ // The Operations table sorts/filters the full result set client-side, so
+ // request the endpoint's hard cap rather than its small default page.
+ limit: OPERATIONS_AGGREGATION_LIMIT,
},
controller.signal
)
diff --git a/products/tracing/mcp/prompts/apm-spans-aggregate.md b/products/tracing/mcp/prompts/apm-spans-aggregate.md
index 77df70ccb5b5..3ae9ecd74478 100644
--- a/products/tracing/mcp/prompts/apm-spans-aggregate.md
+++ b/products/tracing/mcp/prompts/apm-spans-aggregate.md
@@ -6,7 +6,7 @@ Returns one row per `(service_name, name)` pair with the following metrics:
- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (1 second = 1,000,000,000 ns). `p999_duration_nano` is the 99.9th percentile and is only meaningful for `(service, name)` groups with enough spans; on low-volume operations it collapses to the max
- `error_count` — spans with OTel status code `Error` (status_code = 2)
-Rows are ordered by `total_duration_nano` DESC and capped at 5000.
+Rows are ordered by `total_duration_nano` DESC. By default only the top 100 rows are returned — this keeps the response small, which matters because high span-name cardinality (e.g. untemplated URL paths) can otherwise produce an enormous payload. The top rows already surface the heaviest operations. When more rows genuinely exist the response sets `has_more: true` and `next_offset`; page through with `offset`, or raise `limit` (hard max 5000). Prefer narrowing with `serviceNames`/`filterGroup` over pulling a large page.
Use to answer:
@@ -76,6 +76,14 @@ List of service names to restrict the aggregation to. Use `apm-services-list` to
A flat list of property filters applied to both the primary and comparison windows. See the "Property filters" section.
+## query.limit
+
+Max rows to return, ordered by `total_duration_nano` DESC. Defaults to 100; hard max 5000. Keep this small — a high value on high-cardinality span names returns a very large response. Narrow with `serviceNames`/`filterGroup` instead of raising it when you can.
+
+## query.offset
+
+Row offset for pagination. Combine with `limit` and the `next_offset` from a previous response to page through results beyond the first page.
+
# Examples
## Top operations by total time in the last hour
@@ -146,7 +154,7 @@ Returns `results` for the last hour and `compare` for the hour before. Diff `tot
# Reminders
- Duration values are in nanoseconds. Divide by 1,000,000 for ms, 1,000,000,000 for seconds.
-- Results are ordered by `total_duration_nano` DESC and capped at 5000 rows.
+- Results are ordered by `total_duration_nano` DESC and default to the top 100 rows. Check `has_more`/`next_offset` to page; raise `limit` (max 5000) only when you truly need the long tail.
- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attribute keys/values before filtering.
- Use `apm-services-list` to discover services before filtering by service name.
- For parent → child breakdowns, use `apm-spans-tree` instead.
diff --git a/products/tracing/mcp/tools.yaml b/products/tracing/mcp/tools.yaml
index 8438f15c931f..065ff45b2a13 100644
--- a/products/tracing/mcp/tools.yaml
+++ b/products/tracing/mcp/tools.yaml
@@ -103,6 +103,8 @@ tools:
include:
- results
- compare
+ - has_more
+ - next_offset
apm-spans-count:
operation: tracing_spans_count_create
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index b8222dbe6e66..08dbd657a13a 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1199,7 +1199,7 @@
"feature_flag": "tracing"
},
"apm-spans-aggregate": {
- "description": "Aggregate trace span statistics grouped by `(service_name, name)` over a date window.\n\nReturns one row per `(service_name, name)` pair with the following metrics:\n\n- `count` — number of spans matched\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (1 second = 1,000,000,000 ns). `p999_duration_nano` is the 99.9th percentile and is only meaningful for `(service, name)` groups with enough spans; on low-volume operations it collapses to the max\n- `error_count` — spans with OTel status code `Error` (status_code = 2)\n\nRows are ordered by `total_duration_nano` DESC and capped at 5000.\n\nUse to answer:\n\n- \"Which services/operations consume the most time?\"\n- \"What's the p95 or p99 latency of `GET /users`?\"\n- \"How many errors did the checkout service emit in the last day?\"\n- \"Did `POST /orders` get slower this week vs last week?\" (with `compareFilter`)\n\nFor per-call-tree breakdowns (parent → child relationships), use `apm-spans-tree` instead. For time-bucketed trends (\"when did it change?\"), use `apm-spans-sparkline` instead — `compareFilter` only contrasts two static windows.\n\nAll parameters must be nested inside a `query` object.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length (e.g. `dateRange: -1d` → compares vs the day before).\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\n# Data narrowing\n\n## Property filters\n\nUse `query.filterGroup` to narrow results to spans matching specific attributes. Only include filters that are essential to the user's question.\n\nFilter `type` values:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes (e.g. \"http.method\", \"http.status_code\")\n- `span_resource_attribute` — resource-level attributes (e.g. k8s labels, deployment info)\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values before guessing.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`). Examples: `-1h`, `-6h`, `-1d`, `-7d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Omit when you only need the primary window.\n\n- `compare` (boolean): set to true to enable comparison.\n- `compare_to` (string, optional): relative offset for the comparison window (e.g. `-1d`, `-7d`). Defaults to the immediately previous period of equal length.\n\n## query.serviceNames\n\nList of service names to restrict the aggregation to. Use `apm-services-list` to discover available services.\n\n## query.filterGroup\n\nA flat list of property filters applied to both the primary and comparison windows. See the \"Property filters\" section.\n\n# Examples\n\n## Top operations by total time in the last hour\n\n```json\n{\n \"query\": {}\n}\n```\n\n## p95 latency by operation in the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nInspect the `p95_duration_nano` field on each result.\n\n## Compare this hour vs the previous hour\n\n```json\n{\n \"query\": {\n \"compareFilter\": { \"compare\": true }\n }\n}\n```\n\nReturns `results` for the last hour and `compare` for the hour before. Diff `total_duration_nano`, `avg_duration_nano`, etc. to find regressions.\n\n## Compare today vs same time last week\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Aggregate only error spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Aggregate within one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Duration values are in nanoseconds. Divide by 1,000,000 for ms, 1,000,000,000 for seconds.\n- Results are ordered by `total_duration_nano` DESC and capped at 5000 rows.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attribute keys/values before filtering.\n- Use `apm-services-list` to discover services before filtering by service name.\n- For parent → child breakdowns, use `apm-spans-tree` instead.",
+ "description": "Aggregate trace span statistics grouped by `(service_name, name)` over a date window.\n\nReturns one row per `(service_name, name)` pair with the following metrics:\n\n- `count` — number of spans matched\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (1 second = 1,000,000,000 ns). `p999_duration_nano` is the 99.9th percentile and is only meaningful for `(service, name)` groups with enough spans; on low-volume operations it collapses to the max\n- `error_count` — spans with OTel status code `Error` (status_code = 2)\n\nRows are ordered by `total_duration_nano` DESC. By default only the top 100 rows are returned — this keeps the response small, which matters because high span-name cardinality (e.g. untemplated URL paths) can otherwise produce an enormous payload. The top rows already surface the heaviest operations. When more rows genuinely exist the response sets `has_more: true` and `next_offset`; page through with `offset`, or raise `limit` (hard max 5000). Prefer narrowing with `serviceNames`/`filterGroup` over pulling a large page.\n\nUse to answer:\n\n- \"Which services/operations consume the most time?\"\n- \"What's the p95 or p99 latency of `GET /users`?\"\n- \"How many errors did the checkout service emit in the last day?\"\n- \"Did `POST /orders` get slower this week vs last week?\" (with `compareFilter`)\n\nFor per-call-tree breakdowns (parent → child relationships), use `apm-spans-tree` instead. For time-bucketed trends (\"when did it change?\"), use `apm-spans-sparkline` instead — `compareFilter` only contrasts two static windows.\n\nAll parameters must be nested inside a `query` object.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length (e.g. `dateRange: -1d` → compares vs the day before).\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\n# Data narrowing\n\n## Property filters\n\nUse `query.filterGroup` to narrow results to spans matching specific attributes. Only include filters that are essential to the user's question.\n\nFilter `type` values:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes (e.g. \"http.method\", \"http.status_code\")\n- `span_resource_attribute` — resource-level attributes (e.g. k8s labels, deployment info)\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values before guessing.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`). Examples: `-1h`, `-6h`, `-1d`, `-7d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Omit when you only need the primary window.\n\n- `compare` (boolean): set to true to enable comparison.\n- `compare_to` (string, optional): relative offset for the comparison window (e.g. `-1d`, `-7d`). Defaults to the immediately previous period of equal length.\n\n## query.serviceNames\n\nList of service names to restrict the aggregation to. Use `apm-services-list` to discover available services.\n\n## query.filterGroup\n\nA flat list of property filters applied to both the primary and comparison windows. See the \"Property filters\" section.\n\n## query.limit\n\nMax rows to return, ordered by `total_duration_nano` DESC. Defaults to 100; hard max 5000. Keep this small — a high value on high-cardinality span names returns a very large response. Narrow with `serviceNames`/`filterGroup` instead of raising it when you can.\n\n## query.offset\n\nRow offset for pagination. Combine with `limit` and the `next_offset` from a previous response to page through results beyond the first page.\n\n# Examples\n\n## Top operations by total time in the last hour\n\n```json\n{\n \"query\": {}\n}\n```\n\n## p95 latency by operation in the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nInspect the `p95_duration_nano` field on each result.\n\n## Compare this hour vs the previous hour\n\n```json\n{\n \"query\": {\n \"compareFilter\": { \"compare\": true }\n }\n}\n```\n\nReturns `results` for the last hour and `compare` for the hour before. Diff `total_duration_nano`, `avg_duration_nano`, etc. to find regressions.\n\n## Compare today vs same time last week\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Aggregate only error spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Aggregate within one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Duration values are in nanoseconds. Divide by 1,000,000 for ms, 1,000,000,000 for seconds.\n- Results are ordered by `total_duration_nano` DESC and default to the top 100 rows. Check `has_more`/`next_offset` to page; raise `limit` (max 5000) only when you truly need the long tail.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attribute keys/values before filtering.\n- Use `apm-services-list` to discover services before filtering by service name.\n- For parent → child breakdowns, use `apm-spans-tree` instead.",
"category": "Tracing",
"feature": "tracing",
"summary": "Aggregate span statistics",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index ceca21c441cb..4a68828ce2f7 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1228,7 +1228,7 @@
"feature_flag": "tracing"
},
"apm-spans-aggregate": {
- "description": "Aggregate trace span statistics grouped by `(service_name, name)` over a date window.\n\nReturns one row per `(service_name, name)` pair with the following metrics:\n\n- `count` — number of spans matched\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (1 second = 1,000,000,000 ns). `p999_duration_nano` is the 99.9th percentile and is only meaningful for `(service, name)` groups with enough spans; on low-volume operations it collapses to the max\n- `error_count` — spans with OTel status code `Error` (status_code = 2)\n\nRows are ordered by `total_duration_nano` DESC and capped at 5000.\n\nUse to answer:\n\n- \"Which services/operations consume the most time?\"\n- \"What's the p95 or p99 latency of `GET /users`?\"\n- \"How many errors did the checkout service emit in the last day?\"\n- \"Did `POST /orders` get slower this week vs last week?\" (with `compareFilter`)\n\nFor per-call-tree breakdowns (parent → child relationships), use `apm-spans-tree` instead. For time-bucketed trends (\"when did it change?\"), use `apm-spans-sparkline` instead — `compareFilter` only contrasts two static windows.\n\nAll parameters must be nested inside a `query` object.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length (e.g. `dateRange: -1d` → compares vs the day before).\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\n# Data narrowing\n\n## Property filters\n\nUse `query.filterGroup` to narrow results to spans matching specific attributes. Only include filters that are essential to the user's question.\n\nFilter `type` values:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes (e.g. \"http.method\", \"http.status_code\")\n- `span_resource_attribute` — resource-level attributes (e.g. k8s labels, deployment info)\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values before guessing.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`). Examples: `-1h`, `-6h`, `-1d`, `-7d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Omit when you only need the primary window.\n\n- `compare` (boolean): set to true to enable comparison.\n- `compare_to` (string, optional): relative offset for the comparison window (e.g. `-1d`, `-7d`). Defaults to the immediately previous period of equal length.\n\n## query.serviceNames\n\nList of service names to restrict the aggregation to. Use `apm-services-list` to discover available services.\n\n## query.filterGroup\n\nA flat list of property filters applied to both the primary and comparison windows. See the \"Property filters\" section.\n\n# Examples\n\n## Top operations by total time in the last hour\n\n```json\n{\n \"query\": {}\n}\n```\n\n## p95 latency by operation in the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nInspect the `p95_duration_nano` field on each result.\n\n## Compare this hour vs the previous hour\n\n```json\n{\n \"query\": {\n \"compareFilter\": { \"compare\": true }\n }\n}\n```\n\nReturns `results` for the last hour and `compare` for the hour before. Diff `total_duration_nano`, `avg_duration_nano`, etc. to find regressions.\n\n## Compare today vs same time last week\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Aggregate only error spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Aggregate within one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Duration values are in nanoseconds. Divide by 1,000,000 for ms, 1,000,000,000 for seconds.\n- Results are ordered by `total_duration_nano` DESC and capped at 5000 rows.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attribute keys/values before filtering.\n- Use `apm-services-list` to discover services before filtering by service name.\n- For parent → child breakdowns, use `apm-spans-tree` instead.",
+ "description": "Aggregate trace span statistics grouped by `(service_name, name)` over a date window.\n\nReturns one row per `(service_name, name)` pair with the following metrics:\n\n- `count` — number of spans matched\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (1 second = 1,000,000,000 ns). `p999_duration_nano` is the 99.9th percentile and is only meaningful for `(service, name)` groups with enough spans; on low-volume operations it collapses to the max\n- `error_count` — spans with OTel status code `Error` (status_code = 2)\n\nRows are ordered by `total_duration_nano` DESC. By default only the top 100 rows are returned — this keeps the response small, which matters because high span-name cardinality (e.g. untemplated URL paths) can otherwise produce an enormous payload. The top rows already surface the heaviest operations. When more rows genuinely exist the response sets `has_more: true` and `next_offset`; page through with `offset`, or raise `limit` (hard max 5000). Prefer narrowing with `serviceNames`/`filterGroup` over pulling a large page.\n\nUse to answer:\n\n- \"Which services/operations consume the most time?\"\n- \"What's the p95 or p99 latency of `GET /users`?\"\n- \"How many errors did the checkout service emit in the last day?\"\n- \"Did `POST /orders` get slower this week vs last week?\" (with `compareFilter`)\n\nFor per-call-tree breakdowns (parent → child relationships), use `apm-spans-tree` instead. For time-bucketed trends (\"when did it change?\"), use `apm-spans-sparkline` instead — `compareFilter` only contrasts two static windows.\n\nAll parameters must be nested inside a `query` object.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length (e.g. `dateRange: -1d` → compares vs the day before).\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\n# Data narrowing\n\n## Property filters\n\nUse `query.filterGroup` to narrow results to spans matching specific attributes. Only include filters that are essential to the user's question.\n\nFilter `type` values:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes (e.g. \"http.method\", \"http.status_code\")\n- `span_resource_attribute` — resource-level attributes (e.g. k8s labels, deployment info)\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values before guessing.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`). Examples: `-1h`, `-6h`, `-1d`, `-7d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Omit when you only need the primary window.\n\n- `compare` (boolean): set to true to enable comparison.\n- `compare_to` (string, optional): relative offset for the comparison window (e.g. `-1d`, `-7d`). Defaults to the immediately previous period of equal length.\n\n## query.serviceNames\n\nList of service names to restrict the aggregation to. Use `apm-services-list` to discover available services.\n\n## query.filterGroup\n\nA flat list of property filters applied to both the primary and comparison windows. See the \"Property filters\" section.\n\n## query.limit\n\nMax rows to return, ordered by `total_duration_nano` DESC. Defaults to 100; hard max 5000. Keep this small — a high value on high-cardinality span names returns a very large response. Narrow with `serviceNames`/`filterGroup` instead of raising it when you can.\n\n## query.offset\n\nRow offset for pagination. Combine with `limit` and the `next_offset` from a previous response to page through results beyond the first page.\n\n# Examples\n\n## Top operations by total time in the last hour\n\n```json\n{\n \"query\": {}\n}\n```\n\n## p95 latency by operation in the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nInspect the `p95_duration_nano` field on each result.\n\n## Compare this hour vs the previous hour\n\n```json\n{\n \"query\": {\n \"compareFilter\": { \"compare\": true }\n }\n}\n```\n\nReturns `results` for the last hour and `compare` for the hour before. Diff `total_duration_nano`, `avg_duration_nano`, etc. to find regressions.\n\n## Compare today vs same time last week\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Aggregate only error spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Aggregate within one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Duration values are in nanoseconds. Divide by 1,000,000 for ms, 1,000,000,000 for seconds.\n- Results are ordered by `total_duration_nano` DESC and default to the top 100 rows. Check `has_more`/`next_offset` to page; raise `limit` (max 5000) only when you truly need the long tail.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attribute keys/values before filtering.\n- Use `apm-services-list` to discover services before filtering by service name.\n- For parent → child breakdowns, use `apm-spans-tree` instead.",
"category": "Tracing",
"feature": "tracing",
"summary": "Aggregate span statistics",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a774582befd7..7f726b19d205 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -64165,6 +64165,29 @@ export namespace Schemas {
default_email_channel_id?: string | null;
}
+ export interface _AggregatedSpanRow {
+ /** Service that emitted the spans in this group. */
+ service_name: string;
+ /** Span name (operation) for this group. */
+ name: string;
+ /** Number of spans matched in this group. */
+ count: number;
+ /** Sum of span durations in nanoseconds. */
+ total_duration_nano: number;
+ /** Average span duration in nanoseconds. */
+ avg_duration_nano: number;
+ /** Median span duration in nanoseconds. */
+ p50_duration_nano: number;
+ /** 95th percentile span duration in nanoseconds. */
+ p95_duration_nano: number;
+ /** 99th percentile span duration in nanoseconds. */
+ p99_duration_nano: number;
+ /** 99.9th percentile span duration in nanoseconds. */
+ p999_duration_nano: number;
+ /** Spans with OTel status code Error (status_code = 2). */
+ error_count: number;
+ }
+
export interface _CompareFilter {
/** When true, also fetch results for a comparison window and return them under `compare`. */
compare?: boolean;
@@ -65449,6 +65472,17 @@ export namespace Schemas {
serviceNames?: string[];
/** Property filters applied to spans in both windows. */
filterGroup?: _SpanPropertyFilter[];
+ /**
+ * Max rows to return, ordered by total_duration_nano DESC. Defaults to 100; hard max 5000. Keep this small to bound the response size — a high value on high-cardinality span names (e.g. untemplated URL paths) returns a very large payload. Prefer narrowing with `serviceNames`/`filterGroup` over raising the limit.
+ * @minimum 1
+ * @maximum 5000
+ */
+ limit?: number;
+ /**
+ * Row offset for pagination. Combine with `limit` and the `next_offset` returned in the response to page through results beyond the first page.
+ * @minimum 0
+ */
+ offset?: number;
}
export interface _TracingAggregationRequest {
@@ -65456,6 +65490,23 @@ export namespace Schemas {
query: _TracingAggregationQueryBody;
}
+ export interface _TracingAggregationResponse {
+ /** One row per (service_name, name) group, ordered by total_duration_nano descending. */
+ results: _AggregatedSpanRow[];
+ /**
+ * Rows for the comparison window when compareFilter.compare is true, else null.
+ * @nullable
+ */
+ compare: _AggregatedSpanRow[] | null;
+ /** True when more rows exist beyond this page — page further with `next_offset`, or narrow the query. */
+ has_more: boolean;
+ /**
+ * Offset to request the next page, or null when this is the last page.
+ * @nullable
+ */
+ next_offset: number | null;
+ }
+
/**
* * `count` - count
* * `error_count` - error_count
diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.ts
index 08827c0ad513..51013fddfb19 100644
--- a/services/mcp/src/generated/tracing/api.ts
+++ b/services/mcp/src/generated/tracing/api.ts
@@ -18,6 +18,9 @@ export const TracingSpansAggregateCreateParams = /* @__PURE__ */ zod.object({
export const tracingSpansAggregateCreateBodyQueryOneCompareFilterOneCompareDefault = false
export const tracingSpansAggregateCreateBodyQueryOneFilterGroupDefault = []
+export const tracingSpansAggregateCreateBodyQueryOneLimitMax = 5000
+
+export const tracingSpansAggregateCreateBodyQueryOneOffsetMin = 0
export const TracingSpansAggregateCreateBody = /* @__PURE__ */ zod.object({
query: zod
@@ -102,6 +105,21 @@ export const TracingSpansAggregateCreateBody = /* @__PURE__ */ zod.object({
)
.default(tracingSpansAggregateCreateBodyQueryOneFilterGroupDefault)
.describe('Property filters applied to spans in both windows.'),
+ limit: zod
+ .number()
+ .min(1)
+ .max(tracingSpansAggregateCreateBodyQueryOneLimitMax)
+ .optional()
+ .describe(
+ 'Max rows to return, ordered by total_duration_nano DESC. Defaults to 100; hard max 5000. Keep this small to bound the response size — a high value on high-cardinality span names (e.g. untemplated URL paths) returns a very large payload. Prefer narrowing with `serviceNames`/`filterGroup` over raising the limit.'
+ ),
+ offset: zod
+ .number()
+ .min(tracingSpansAggregateCreateBodyQueryOneOffsetMin)
+ .optional()
+ .describe(
+ 'Row offset for pagination. Combine with `limit` and the `next_offset` returned in the response to page through results beyond the first page.'
+ ),
})
.describe('The span aggregation query to execute.'),
})
diff --git a/services/mcp/src/tools/generated/tracing.ts b/services/mcp/src/tools/generated/tracing.ts
index ab06266dfb90..fcaff2ba6c44 100644
--- a/services/mcp/src/tools/generated/tracing.ts
+++ b/services/mcp/src/tools/generated/tracing.ts
@@ -112,7 +112,7 @@ const apmServicesList = (): ToolBase<typeof ApmServicesListSchema, unknown> => (
const ApmSpansAggregateSchema = TracingSpansAggregateCreateBody
-const apmSpansAggregate = (): ToolBase<typeof ApmSpansAggregateSchema, unknown> => ({
+const apmSpansAggregate = (): ToolBase<typeof ApmSpansAggregateSchema, Schemas._TracingAggregationResponse> => ({
name: 'apm-spans-aggregate',
schema: ApmSpansAggregateSchema,
handler: async (context: Context, params: z.infer<typeof ApmSpansAggregateSchema>) => {
@@ -121,12 +121,12 @@ const apmSpansAggregate = (): ToolBase<typeof ApmSpansAggregateSchema, unknown>
if (params.query !== undefined) {
body['query'] = params.query
}
- const result = await context.api.request<unknown>({
+ const result = await context.api.request<Schemas._TracingAggregationResponse>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/tracing/spans/aggregate/`,
body,
})
- const filtered = pickResponseFields(result, ['results', 'compare']) as typeof result
+ const filtered = pickResponseFields(result, ['results', 'compare', 'has_more', 'next_offset']) as typeof result
return filtered
},
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-aggregate.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-aggregate.json
index 9a215231380d..4bd2ff0461fd 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-aggregate.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-aggregate.json
@@ -93,6 +93,17 @@
},
"type": "array"
},
+ "limit": {
+ "description": "Max rows to return, ordered by total_duration_nano DESC. Defaults to 100; hard max 5000. Keep this small to bound the response size — a high value on high-cardinality span names (e.g. untemplated URL paths) returns a very large payload. Prefer narrowing with `serviceNames`/`filterGroup` over raising the limit.",
+ "maximum": 5000,
+ "minimum": 1,
+ "type": "number"
+ },
+ "offset": {
+ "description": "Row offset for pagination. Combine with `limit` and the `next_offset` returned in the response to page through results beyond the first page.",
+ "minimum": 0,
+ "type": "number"
+ },
"serviceNames": {
"description": "Filter by service names.",
"items": {