: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(tracing): add flat span-list query mode for span-level search (#64000)
Jon McCallum869bd723997f
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 49ec26a6d2a9..da5e2d7f461a 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -42125,6 +42125,10 @@"filterGroup": {"$ref": "#/definitions/PropertyGroupFilter"},+ "flatSpans": {+ "description": "Return the matching spans themselves, one row per span (root and child), instead of the whole-trace grouping. Streams the matches under `ORDER BY … LIMIT` rather than grouping every matching span by trace, so a filter on a hot child attribute (e.g. `code.filepath`) stays bounded. Distinct from `rootSpans`, which scopes whole-trace selection. The single-trace waterfall never sets this.",+ "type": "boolean"+ },"kind": {"const": "TraceSpansQuery","type": "string"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex d665e6f24ed4..b39a68ecf4e0 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -3227,6 +3227,14 @@ export interface TraceSpansQuery extends DataNode<TraceSpansQueryResponse> {statusCodes?: integer[]traceId?: stringrootSpans?: boolean+ /**+ * Return the matching spans themselves, one row per span (root and child), instead of the+ * whole-trace grouping. Streams the matches under `ORDER BY … LIMIT` rather than grouping every+ * matching span by trace, so a filter on a hot child attribute (e.g. `code.filepath`) stays+ * bounded. Distinct from `rootSpans`, which scopes whole-trace selection. The single-trace+ * waterfall never sets this.+ */+ flatSpans?: boolean/** Cursor for fetching the next page of results */after?: string/** Prefetch up to this many spans per trace and include them in results */diff --git a/posthog/schema.py b/posthog/schema.pyindex 24a9c619150e..4053c5c61011 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -22192,6 +22192,17 @@ class TraceSpansQuery(BaseModel):description=("Omit the per-span `attributes` map from results to keep payloads compact"),)filterGroup: PropertyGroupFilter | None = None+ flatSpans: bool | None = Field(+ default=None,+ description=(+ "Return the matching spans themselves, one row per span (root and child),"+ " instead of the whole-trace grouping. Streams the matches under `ORDER BY"+ " … LIMIT` rather than grouping every matching span by trace, so a filter"+ " on a hot child attribute (e.g. `code.filepath`) stays bounded. Distinct"+ " from `rootSpans`, which scopes whole-trace selection. The single-trace"+ " waterfall never sets this."+ ),+ )kind: Literal["TraceSpansQuery"] = "TraceSpansQuery"limit: int | None = Nonemodifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.pyindex d88320bf4f72..f9a4139b2b70 100644--- a/products/tracing/backend/logic.py+++ b/products/tracing/backend/logic.py@@ -380,14 +380,19 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Traraise UserAccessControlError("tracing", "viewer")def _calculate(self) -> TraceSpansQueryResponse:- limit_by_n = self.query.prefetchSpans or 1+ flat = self._flat_spans+ # Flat mode returns one row per matching span (no per-trace prefetch), so don't inflate the+ # page size. Grouped mode locks pagination into the trace-id subquery (outer paginator at+ # offset 0); flat mode has no subquery, so its duration-order offset rides the paginator here+ # (timestamp order keysets in the WHERE instead).+ limit_by_n = 1 if flat else (self.query.prefetchSpans or 1)query = self.to_query()# original pagination settings are locked in in the trace id subquery already# override limit to allow for N * limit for the trace spansself.paginator = HogQLHasMorePaginator.from_limit_context(limit_context=LimitContext.QUERY,limit=self.query.limit * limit_by_n if self.query.limit else None,- offset=0,+ offset=self.query.offset if flat else 0,)response = self.paginator.execute_hogql_query(@@ -441,26 +446,41 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra"""Ordering by duration paginates via offset; ordering by timestamp via the time keyset."""return self.query.orderBy == "duration"- def _parse_after_cursor(self) -> tuple[dt.datetime, str] | None:- """Decode the opaque `after` cursor into (trace_start_ts, trace_id_base64).+ @property+ def _flat_spans(self) -> bool:+ """Return the matching spans themselves (one row per span), not whole-trace groups.++ Set explicitly by the viewer's "Spans" mode. The whole-trace path groups every matching span+ by trace_id to rank traces — an unbounded, high-cardinality aggregation that exceeds+ ClickHouse's memory limit for hot child attributes (e.g. code.filepath). Flat mode skips the+ GROUP BY + window and streams matches under ORDER BY ... LIMIT instead. Distinct from+ `rootSpans` (whole-trace scoping); the single-trace waterfall never sets it.+ """+ return self.query.flatSpans is True++ def _parse_after_cursor(self, secondary_key: str = "trace_id") -> tuple[dt.datetime, str] | None:+ """Decode the opaque `after` cursor into (timestamp, secondary_id_base64).- The cursor identifies the last trace of the previous page by its start time (the root- span's timestamp) and trace id. `trace_id` travels as hex (the human form the rest of the- API uses) and is re-encoded to the table's base64 storage form for comparison.+ `secondary_key` selects the keyset tiebreaker for the previous page's boundary row: "trace_id"+ for the whole-trace list (keyed on the trace's start time) or "span_id" for the flat span list+ (keyed on the span's own timestamp). The secondary id travels as hex (the human form the rest of+ the API uses) and is re-encoded to the table's base64 storage form for comparison."""if not self.query.after:return Nonetry:cursor = json.loads(base64.b64decode(self.query.after).decode("utf-8"))cursor_ts = dt.datetime.fromisoformat(cursor["timestamp"])- cursor_trace_id_b64 = base64.b64encode(bytes.fromhex(cursor["trace_id"])).decode("ascii")+ cursor_id_b64 = base64.b64encode(bytes.fromhex(cursor[secondary_key])).decode("ascii")except (KeyError, ValueError, json.JSONDecodeError) as e:raise ValueError(f"Invalid cursor format: {e}")- return cursor_ts, cursor_trace_id_b64+ return cursor_ts, cursor_id_b64def to_query(self) -> ast.SelectQuery:by_duration = self._by_durationorder_dir = "ASC" if self.query.orderDirection == "ASC" else "DESC"+ if self._flat_spans:+ return self._build_flat_spans_query(by_duration=by_duration, order_dir=order_dir)limit_by_n = self.query.prefetchSpans or 1# The list paginates by trace. We GROUP BY trace_id so the page key lands on a stable@@ -608,6 +628,87 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Trareturn query+ def _build_flat_spans_query(self, *, by_duration: bool, order_dir: str) -> ast.SelectQuery:+ """Flat span list: the matching spans themselves, no whole-trace expansion (see _flat_spans).++ Streams matches under ORDER BY ... LIMIT (keyset on timestamp, offset on duration) instead of a+ per-trace GROUP BY + window, so a filter on a hot child attribute stays bounded. Returns the+ same positional columns as the whole-trace query so _calculate's row mapping stays shared:+ matched_filter is a constant 1 (every returned row matched), and trace_start / trace_duration+ are the span's own timestamp / duration.+ """+ where_exprs: list[ast.Expr] = [self.where()]++ # Time order keysets on (timestamp, span_id) in the WHERE; duration order offset-paginates via+ # the paginator (see _calculate). The coarse UTC day bound lets ClickHouse prune parts first —+ # pin UTC for the same reason as the date bound in where(): the cursor constant prints UTC, so+ # an unpinned toStartOfDay would truncate on the session-tz day grid and drop same-day rows.+ if not by_duration:+ cursor = self._parse_after_cursor("span_id")+ if cursor is not None:+ cursor_ts, cursor_span_id = cursor+ row_op = ">" if order_dir == "ASC" else "<"+ day_op = ">=" if order_dir == "ASC" else "<="+ where_exprs.append(+ parse_expr(+ f"toStartOfDay(time_bucket, 'UTC') {day_op} toStartOfDay({{cursor_ts}}, 'UTC')",+ placeholders={"cursor_ts": ast.Constant(value=cursor_ts)},+ )+ )+ where_exprs.append(+ parse_expr(+ f"(timestamp, span_id) {row_op} ({{cursor_ts}}, {{cursor_span_id}})",+ placeholders={+ "cursor_ts": ast.Constant(value=cursor_ts),+ "cursor_span_id": ast.Constant(value=cursor_span_id),+ },+ )+ )++ where: ast.Expr = where_exprs[0] if len(where_exprs) == 1 else ast.And(exprs=where_exprs)++ query = parse_select(+ """+ SELECT+ uuid,+ hex(tryBase64Decode(trace_id)),+ hex(tryBase64Decode(span_id)),+ hex(tryBase64Decode(parent_span_id)),+ name,+ kind,+ service_name,+ status_code,+ timestamp,+ end_time,+ duration_nano,+ is_root_span,+ 1 as matched_filter,+ timestamp as trace_start,+ {attributes},+ {resource_attributes},+ duration_nano as trace_duration+ FROM posthog.trace_spans+ WHERE {where}+ """,+ placeholders={+ "where": where,+ "attributes": parse_expr("map() AS attributes" if self.query.excludeAttributes else "attributes"),+ "resource_attributes": parse_expr(+ "map() AS resource_attributes" if self.query.excludeAttributes else "resource_attributes"+ ),+ },+ )+ assert isinstance(query, ast.SelectQuery)++ # span_id is the per-span tiebreaker (base64 storage form, matching the cursor) — keeps the+ # ORDER BY and the keyset WHERE on the same representation so pagination is stable.+ sort_col = "duration_nano" if by_duration else "timestamp"+ query.order_by = [+ parse_order_expr(f"{sort_col} {order_dir}"),+ parse_order_expr(f"span_id {order_dir}"),+ ]+ return query+def run_service_names_query(team: "Team",diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.pyindex 1062e9218698..5552876f5491 100644--- a/products/tracing/backend/presentation/views.py+++ b/products/tracing/backend/presentation/views.py@@ -158,6 +158,15 @@ class _TracingQueryBodySerializer(serializers.Serializer):default=True,help_text="Filter to root spans only. Defaults to true.",)+ flatSpans = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "Return the matching spans themselves, one row per span (root and child), instead of "+ "collapsing to traces. Use this to search by a child-span attribute (e.g. code.filepath) "+ "without the whole-trace grouping. Distinct from rootSpans. Defaults to false."+ ),+ )prefetchSpans = serializers.IntegerField(required=False,help_text="Number of child spans to prefetch per trace (1-100).",@@ -173,6 +182,36 @@ class _TracingQueryRequestSerializer(serializers.Serializer):query = _TracingQueryBodySerializer(help_text="The tracing spans query to execute.")+class _TracingTimeseriesQueryBodySerializer(serializers.Serializer):+ # The sparkline and duration-histogram actions read only these filter fields. They deliberately do+ # NOT subclass the span-query body: that body's result-shaping fields (orderBy, limit, pagination,+ # rootSpans, flatSpans, …) are silently ignored here, so advertising them would mislead callers.+ dateRange = _TracingDateRangeSerializer(+ required=False,+ help_text="Date range for the query. Defaults to last hour.",+ )+ serviceNames = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ help_text="Filter by service names.",+ )+ statusCodes = serializers.ListField(+ child=serializers.IntegerField(),+ required=False,+ help_text="Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans.",+ )+ filterGroup = serializers.ListField(+ child=_SpanPropertyFilterSerializer(),+ required=False,+ default=[],+ help_text="Property filters for the query.",+ )+++class _TracingTimeseriesRequestSerializer(serializers.Serializer):+ query = _TracingTimeseriesQueryBodySerializer(help_text="The sparkline / duration-histogram query to execute.")++class _TracingTraceRequestSerializer(serializers.Serializer):dateRange = _TracingDateRangeSerializer(required=False,@@ -376,6 +415,15 @@ class _TracingCountResponseSerializer(serializers.Serializer):count = serializers.IntegerField(help_text="Number of spans matching the filters.")+def _encode_after_cursor(timestamp: str, **secondary: str) -> str:+ """Encode a keyset `after` cursor as base64(json) of the boundary row's timestamp + secondary id.++ Mirrors TraceSpansQueryRunner._parse_after_cursor on the read side; `secondary` is the tiebreaker+ field (trace_id for the trace list, span_id for the flat span list).+ """+ return base64.b64encode(json.dumps({"timestamp": timestamp, **secondary}).encode("utf-8")).decode("utf-8")++class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):scope_object = "tracing"serializer_class = _FallbackSerializer@@ -441,6 +489,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)prefetch_spans = query_data.get("prefetchSpans", None)if prefetch_spans is not None:prefetch_spans = min(int(prefetch_spans), 100)+ flat_spans = bool(query_data.get("flatSpans", False))filter_group = (self.get_model(self._normalize_filter_group(query_data.get("filterGroup")), PropertyGroupFilter)@@ -460,6 +509,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)offset=offset,after=after_cursor,rootSpans=query_data.get("rootSpans", True),+ flatSpans=flat_spans,prefetchSpans=prefetch_spans,excludeAttributes=query_data.get("excludeAttributes", False),)@@ -476,33 +526,43 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)# `trace_duration`) is carried on every span row (see TraceSpansQueryRunner.to_query) — read it# directly rather than re-deriving over the prefetched spans, which can disagree with the SQL key.by_duration = order_by == "duration"- descending = order_direction == "DESC"- sort_key = "trace_duration" if by_duration else "trace_start"- trace_keys: dict[str, object] = {span["trace_id"]: span[sort_key] for span in all_results}-- ordered_traces = sorted(- trace_keys.items(),- key=lambda item: (item[1], base64.b64encode(bytes.fromhex(item[0])).decode("ascii")),- reverse=descending,- )- has_more = len(ordered_traces) > requested_limit- kept_trace_ids = {tid for tid, _ in ordered_traces[:requested_limit]}- results = [span for span in all_results if span["trace_id"] in kept_trace_ids]-- # Duration ordering paginates via `offset`; only the timestamp keyset emits an `after` cursor.next_cursor = None- if has_more and not by_duration:- boundary_trace_id, boundary_ts = ordered_traces[requested_limit - 1]- next_cursor = base64.b64encode(- json.dumps({"timestamp": boundary_ts.isoformat(), "trace_id": boundary_trace_id}).encode("utf-8")- ).decode("utf-8")++ if flat_spans:+ # Flat mode already returns one row per matching span in sort order, so paginate at the span+ # level: keep the page, decide hasMore on the span count, and (timestamp order only) emit a+ # keyset cursor on the last kept span's (timestamp, span_id).+ has_more = len(all_results) > requested_limit+ results = all_results[:requested_limit]+ if has_more and not by_duration and results:+ last = results[-1]+ next_cursor = _encode_after_cursor(last["timestamp"].isoformat(), span_id=last["span_id"])+ else:+ descending = order_direction == "DESC"+ sort_key = "trace_duration" if by_duration else "trace_start"+ trace_keys: dict[str, object] = {span["trace_id"]: span[sort_key] for span in all_results}++ ordered_traces = sorted(+ trace_keys.items(),+ key=lambda item: (item[1], base64.b64encode(bytes.fromhex(item[0])).decode("ascii")),+ reverse=descending,+ )+ has_more = len(ordered_traces) > requested_limit+ kept_trace_ids = {tid for tid, _ in ordered_traces[:requested_limit]}+ results = [span for span in all_results if span["trace_id"] in kept_trace_ids]++ # Duration ordering paginates via `offset`; only the timestamp keyset emits an `after` cursor.+ if has_more and not by_duration:+ boundary_trace_id, boundary_ts = ordered_traces[requested_limit - 1]+ next_cursor = _encode_after_cursor(boundary_ts.isoformat(), trace_id=boundary_trace_id)report_user_action(request.user,"tracing query executed",{- "traces_count": len(kept_trace_ids),+ "traces_count": len({span["trace_id"] for span in results}),"spans_count": len(results),+ "flat_spans": flat_spans,"has_more": has_more,"has_filter_group": bool(query_data.get("filterGroup")),"service_names_count": len(query_data.get("serviceNames") or []),@@ -559,7 +619,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)return Response(response.results, status=status.HTTP_200_OK)- @extend_schema(request=_TracingQueryRequestSerializer)+ @extend_schema(request=_TracingTimeseriesRequestSerializer)@action(detail=False, methods=["POST"], required_scopes=["tracing:read"])def sparkline(self, request: Request, *args, **kwargs) -> Response:tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)@@ -588,7 +648,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)return Response({"results": response.results}, status=status.HTTP_200_OK)- @extend_schema(request=_TracingQueryRequestSerializer)+ @extend_schema(request=_TracingTimeseriesRequestSerializer)@action(detail=False, methods=["POST"], url_path="duration-histogram", required_scopes=["tracing:read"])def duration_histogram(self, request: Request, *args, **kwargs) -> Response:tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)diff --git a/products/tracing/backend/tests/test_flat_span_query.py b/products/tracing/backend/tests/test_flat_span_query.pynew file mode 100644index 000000000000..96496d759509--- /dev/null+++ b/products/tracing/backend/tests/test_flat_span_query.py@@ -0,0 +1,152 @@+import base64+import datetime as dt++from posthog.test.base import APIBaseTest, ClickhouseTestMixin++from parameterized import parameterized++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.query_tagging import tag_queries+from posthog.clickhouse.traces.spans import TRACE_SPANS_DISTRIBUTED_TABLE_SQL, TRACE_SPANS_TABLE_SQL++DATE_FROM = "2026-06-02T07:00:00Z"+DATE_TO = "2026-06-02T09:00:00Z"++ROOT_SVC = "web"+CHILD_SVC = "flags"+ROOT_NAME = "GET /api"+CHILD_NAME = "match_flags"+FILEPATH = "feature-flags/src/flags/flag_matching.rs"+++def _b64(raw: bytes) -> str:+ return base64.b64encode(raw).decode("ascii")+++class TestFlatSpanQuery(ClickhouseTestMixin, APIBaseTest):+ """flatSpans=True returns the matching spans themselves, one row per span. code.filepath lives on a+ non-root (child) span, so the default Traces view (root-filtered) shows nothing; flat mode surfaces+ the child directly, without the whole-trace GROUP BY that OOMs on hot child attributes at volume.+ """++ CLASS_DATA_LEVEL_SETUP = True++ @classmethod+ def setUpTestData(cls):+ super().setUpTestData()+ tag_queries(product="tracing", feature="query")+ sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")+ sync_execute("DROP TABLE IF EXISTS trace_spans")+ sync_execute(TRACE_SPANS_TABLE_SQL())+ sync_execute(+ "ALTER TABLE trace_spans ADD COLUMN IF NOT EXISTS "+ "is_root_span Bool MATERIALIZED (replaceAll(trimRight(parent_span_id, '='), 'A', '')) = ''"+ )+ sync_execute(TRACE_SPANS_DISTRIBUTED_TABLE_SQL())++ # Three traces 10s apart. Each: a root ("web", no code.filepath) + one child ("flags", carries+ # code.filepath). Child end_time grows with i so duration ordering is distinguishable.+ base = dt.datetime(2026, 6, 2, 8, 0, 0)+ rows = []+ for i in range(1, 4):+ trace = _b64(i.to_bytes(16, "big"))+ root_id = _b64((i * 10 + 1).to_bytes(8, "big"))+ child_id = _b64((i * 10 + 2).to_bytes(8, "big"))+ ts = (base + dt.timedelta(seconds=i * 10)).strftime("%Y-%m-%d %H:%M:%S.%f")+ root_end = (base + dt.timedelta(seconds=i * 10, milliseconds=2)).strftime("%Y-%m-%d %H:%M:%S.%f")+ child_end = (base + dt.timedelta(seconds=i * 10, milliseconds=5 + i)).strftime("%Y-%m-%d %H:%M:%S.%f")+ rows.append(+ f"('019e8754-0000-0000-0000-{2 * i - 1:012d}', {cls.team.id}, '{trace}', '{root_id}', '', "+ f"'{ROOT_NAME}', 2, '{ts}', '{root_end}', '{ts}', 0, '{ROOT_SVC}', map(), map())"+ )+ rows.append(+ f"('019e8754-0000-0000-0000-{2 * i:012d}', {cls.team.id}, '{trace}', '{child_id}', '{root_id}', "+ f"'{CHILD_NAME}', 2, '{ts}', '{child_end}', '{ts}', 0, '{CHILD_SVC}', "+ f"map('code.filepath__str', '{FILEPATH}'), map())"+ )+ 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, attributes_map_str, "+ "resource_attributes) VALUES " + ",".join(rows)+ )++ @classmethod+ def tearDownClass(cls):+ sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")+ sync_execute("DROP TABLE IF EXISTS trace_spans")+ sync_execute(TRACE_SPANS_TABLE_SQL())+ sync_execute(TRACE_SPANS_DISTRIBUTED_TABLE_SQL())+ super().tearDownClass()++ def _query(self, **overrides) -> dict:+ body = {+ "query": {+ "dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO},+ **overrides,+ }+ }+ res = self.client.post(f"/api/projects/{self.team.id}/tracing/spans/query/", body, format="json")+ self.assertEqual(res.status_code, 200, res.content)+ return res.json()++ _CODE_FILTER = {"key": "code.filepath", "type": "span_attribute", "operator": "exact", "value": FILEPATH}++ @parameterized.expand(+ [+ # A child-only attribute filter (code.filepath) and the child service filter both select+ # exactly the three child spans directly — one row per span, no roots.+ ("attribute_filter", {"filterGroup": [_CODE_FILTER]}),+ ("service_name_filter", {"serviceNames": [CHILD_SVC]}),+ ]+ )+ def test_flat_respects_filters(self, _name, filter_kwargs):+ data = self._query(flatSpans=True, limit=100, **filter_kwargs)+ results = data["results"]+ self.assertEqual(len(results), 3)+ self.assertEqual({r["name"] for r in results}, {CHILD_NAME})+ self.assertTrue(all(r["is_root_span"] is False for r in results))+ self.assertTrue(all(r["service_name"] == CHILD_SVC for r in results))+ # Every returned row matched the filter.+ self.assertTrue(all(r["matched_filter"] for r in results))++ def test_default_traces_view_hides_child_only_match(self):+ # The bug this fixes: with the default (Traces) view, a child-only attribute filter matches no+ # root, so the table is empty even though the spans exist. flatSpans is the escape hatch.+ data = self._query(filterGroup=[self._CODE_FILTER], limit=100)+ self.assertEqual(data["results"], [])++ def test_flat_without_attribute_filter_returns_all_spans(self):+ data = self._query(flatSpans=True, limit=100)+ results = data["results"]+ self.assertEqual(len(results), 6)+ names = [r["name"] for r in results]+ self.assertEqual(names.count(ROOT_NAME), 3)+ self.assertEqual(names.count(CHILD_NAME), 3)++ @parameterized.expand(+ [+ # timestamp order paginates via the `after` keyset cursor; duration order via `offset`.+ ("timestamp_keyset", "timestamp"),+ ("duration_offset", "duration"),+ ]+ )+ def test_flat_pagination_walks_every_span_once(self, _name, order_by):+ seen_uuids: list[str] = []+ cursor: str | None = None+ offset = 0+ for _ in range(10): # generous upper bound; 6 spans at limit 2 = 3 pages+ paging = {"after": cursor} if cursor else {"offset": offset}+ page = self._query(flatSpans=True, orderBy=order_by, orderDirection="DESC", limit=2, **paging)+ results = page["results"]+ self.assertLessEqual(len(results), 2)+ seen_uuids.extend(r["uuid"] for r in results)+ if not page["hasMore"]:+ break+ if order_by == "duration":+ offset += 2+ else:+ cursor = page["nextCursor"]+ self.assertIsNotNone(cursor)+ # Every span seen exactly once, no duplicates or drops across the pages.+ self.assertEqual(len(seen_uuids), 6)+ self.assertEqual(len(set(seen_uuids)), 6)diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.tsindex a82899ac7f8c..441d92d12a89 100644--- a/products/tracing/frontend/generated/api.schemas.ts+++ b/products/tracing/frontend/generated/api.schemas.ts@@ -186,6 +186,27 @@ export interface _TracingCountResponseApi {count: number}+export interface _TracingTimeseriesQueryBodyApi {+ /** Date range for the query. Defaults to last hour. */+ dateRange?: _TracingDateRangeApi+ /** Filter by service names. */+ serviceNames?: string[]+ /** Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans. */+ statusCodes?: number[]+ /** Property filters for the query. */+ filterGroup?: _SpanPropertyFilterApi[]+}++export interface _TracingTimeseriesRequestApi {+ /** The sparkline / duration-histogram query to execute. */+ query: _TracingTimeseriesQueryBodyApi+}++export interface _HasSpansResponseApi {+ /** Whether the team has ingested any tracing spans yet. Used to gate the onboarding empty state. */+ hasSpans: boolean+}+/*** * `timestamp` - timestamp* * `duration` - duration@@ -241,6 +262,8 @@ export interface _TracingQueryBodyApi {offset?: number/** Filter to root spans only. Defaults to true. */rootSpans?: boolean+ /** Return the matching spans themselves, one row per span (root and child), instead of collapsing to traces. Use this to search by a child-span attribute (e.g. code.filepath) without the whole-trace grouping. Distinct from rootSpans. Defaults to false. */+ flatSpans?: boolean/** Number of child spans to prefetch per trace (1-100). */prefetchSpans?: number/** Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false. */@@ -252,11 +275,6 @@ export interface _TracingQueryRequestApi {query: _TracingQueryBodyApi}-export interface _HasSpansResponseApi {- /** Whether the team has ingested any tracing spans yet. Used to gate the onboarding empty state. */- hasSpans: boolean-}-export interface _TracingTraceRequestApi {/** Date range for the query. Defaults to last 24 hours. */dateRange?: _TracingDateRangeApidiff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.tsindex d8a920b27c9a..714aa0ad19c4 100644--- a/products/tracing/frontend/generated/api.ts+++ b/products/tracing/frontend/generated/api.ts@@ -18,6 +18,7 @@ import type {_TracingCountRequestApi,_TracingCountResponseApi,_TracingQueryRequestApi,+ _TracingTimeseriesRequestApi,_TracingTraceRequestApi,_TracingTreeRequestApi,} from './api.schemas'@@ -109,14 +110,14 @@ export const getTracingSpansDurationHistogramCreateUrl = (projectId: string) =>export const tracingSpansDurationHistogramCreate = async (projectId: string,- _tracingQueryRequestApi: _TracingQueryRequestApi,+ _tracingTimeseriesRequestApi: _TracingTimeseriesRequestApi,options?: RequestInit): Promise<void> => {return apiMutator<void>(getTracingSpansDurationHistogramCreateUrl(projectId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(_tracingQueryRequestApi),+ body: JSON.stringify(_tracingTimeseriesRequestApi),})}@@ -187,14 +188,14 @@ export const getTracingSpansSparklineCreateUrl = (projectId: string) => {export const tracingSpansSparklineCreate = async (projectId: string,- _tracingQueryRequestApi: _TracingQueryRequestApi,+ _tracingTimeseriesRequestApi: _TracingTimeseriesRequestApi,options?: RequestInit): Promise<void> => {return apiMutator<void>(getTracingSpansSparklineCreateUrl(projectId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(_tracingQueryRequestApi),+ body: JSON.stringify(_tracingTimeseriesRequestApi),})}diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.tsindex 49d77784299b..5b7db493f17d 100644--- a/products/tracing/frontend/generated/api.zod.ts+++ b/products/tracing/frontend/generated/api.zod.ts@@ -286,11 +286,6 @@ export const TracingSpansCountCreateBody = /* @__PURE__ */ zod.object({})export const tracingSpansDurationHistogramCreateBodyQueryOneFilterGroupDefault = []-export const tracingSpansDurationHistogramCreateBodyQueryOneLimitDefault = 100-export const tracingSpansDurationHistogramCreateBodyQueryOneOffsetMin = 0--export const tracingSpansDurationHistogramCreateBodyQueryOneRootSpansDefault = true-export const tracingSpansDurationHistogramCreateBodyQueryOneExcludeAttributesDefault = falseexport const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.object({query: zod@@ -317,20 +312,6 @@ export const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.objec.describe('Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans.'),- orderBy: zod- .enum(['timestamp', 'duration'])- .describe('\* `timestamp` - timestamp\n\* `duration` - duration')- .optional()- .describe(- "Column to order by. Defaults to timestamp. Ordering by timestamp paginates via the keyset cursor ('after'); ordering by duration paginates via 'offset'.\n\n\* `timestamp` - timestamp\n\* `duration` - duration"- ),- orderDirection: zod- .enum(['ASC', 'DESC'])- .describe('\* `ASC` - ASC\n\* `DESC` - DESC')- .optional()- .describe(- 'Order direction. Defaults to DESC (e.g. timestamp+DESC = newest first, duration+DESC = slowest first).\n\n\* `ASC` - ASC\n\* `DESC` - DESC'- ),filterGroup: zod.array(zod.object({@@ -376,33 +357,8 @@ export const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.objec).default(tracingSpansDurationHistogramCreateBodyQueryOneFilterGroupDefault).describe('Property filters for the query.'),- traceId: zod.string().optional().describe('Filter to a specific trace ID (hex string).'),- limit: zod- .number()- .default(tracingSpansDurationHistogramCreateBodyQueryOneLimitDefault)- .describe('Max results (1-1000). Defaults to 100.'),- after: zod- .string()- .optional()- .describe('Keyset pagination cursor from a previous timestamp-ordered response.'),- offset: zod- .number()- .min(tracingSpansDurationHistogramCreateBodyQueryOneOffsetMin)- .optional()- .describe('Pagination offset, used when ordering by a column (e.g. duration). Defaults to 0.'),- rootSpans: zod- .boolean()- .default(tracingSpansDurationHistogramCreateBodyQueryOneRootSpansDefault)- .describe('Filter to root spans only. Defaults to true.'),- prefetchSpans: zod.number().optional().describe('Number of child spans to prefetch per trace (1-100).'),- excludeAttributes: zod- .boolean()- .default(tracingSpansDurationHistogramCreateBodyQueryOneExcludeAttributesDefault)- .describe(- 'Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.'- ),})- .describe('The tracing spans query to execute.'),+ .describe('The sparkline \/ duration-histogram query to execute.'),})export const tracingSpansQueryCreateBodyQueryOneFilterGroupDefault = []@@ -410,6 +366,7 @@ export const tracingSpansQueryCreateBodyQueryOneLimitDefault = 100export const tracingSpansQueryCreateBodyQueryOneOffsetMin = 0export const tracingSpansQueryCreateBodyQueryOneRootSpansDefault = true+export const tracingSpansQueryCreateBodyQueryOneFlatSpansDefault = falseexport const tracingSpansQueryCreateBodyQueryOneExcludeAttributesDefault = falseexport const TracingSpansQueryCreateBody = /* @__PURE__ */ zod.object({@@ -514,6 +471,12 @@ export const TracingSpansQueryCreateBody = /* @__PURE__ */ zod.object({.boolean().default(tracingSpansQueryCreateBodyQueryOneRootSpansDefault).describe('Filter to root spans only. Defaults to true.'),+ flatSpans: zod+ .boolean()+ .default(tracingSpansQueryCreateBodyQueryOneFlatSpansDefault)+ .describe(+ 'Return the matching spans themselves, one row per span (root and child), instead of collapsing to traces. Use this to search by a child-span attribute (e.g. code.filepath) without the whole-trace grouping. Distinct from rootSpans. Defaults to false.'+ ),prefetchSpans: zod.number().optional().describe('Number of child spans to prefetch per trace (1-100).'),excludeAttributes: zod.boolean()@@ -526,11 +489,6 @@ export const TracingSpansQueryCreateBody = /* @__PURE__ */ zod.object({})export const tracingSpansSparklineCreateBodyQueryOneFilterGroupDefault = []-export const tracingSpansSparklineCreateBodyQueryOneLimitDefault = 100-export const tracingSpansSparklineCreateBodyQueryOneOffsetMin = 0--export const tracingSpansSparklineCreateBodyQueryOneRootSpansDefault = true-export const tracingSpansSparklineCreateBodyQueryOneExcludeAttributesDefault = falseexport const TracingSpansSparklineCreateBody = /* @__PURE__ */ zod.object({query: zod@@ -557,20 +515,6 @@ export const TracingSpansSparklineCreateBody = /* @__PURE__ */ zod.object({.describe('Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans.'),- orderBy: zod- .enum(['timestamp', 'duration'])- .describe('\* `timestamp` - timestamp\n\* `duration` - duration')- .optional()- .describe(- "Column to order by. Defaults to timestamp. Ordering by timestamp paginates via the keyset cursor ('after'); ordering by duration paginates via 'offset'.\n\n\* `timestamp` - timestamp\n\* `duration` - duration"- ),- orderDirection: zod- .enum(['ASC', 'DESC'])- .describe('\* `ASC` - ASC\n\* `DESC` - DESC')- .optional()- .describe(- 'Order direction. Defaults to DESC (e.g. timestamp+DESC = newest first, duration+DESC = slowest first).\n\n\* `ASC` - ASC\n\* `DESC` - DESC'- ),filterGroup: zod.array(zod.object({@@ -616,33 +560,8 @@ export const TracingSpansSparklineCreateBody = /* @__PURE__ */ zod.object({).default(tracingSpansSparklineCreateBodyQueryOneFilterGroupDefault).describe('Property filters for the query.'),- traceId: zod.string().optional().describe('Filter to a specific trace ID (hex string).'),- limit: zod- .number()- .default(tracingSpansSparklineCreateBodyQueryOneLimitDefault)- .describe('Max results (1-1000). Defaults to 100.'),- after: zod- .string()- .optional()- .describe('Keyset pagination cursor from a previous timestamp-ordered response.'),- offset: zod- .number()- .min(tracingSpansSparklineCreateBodyQueryOneOffsetMin)- .optional()- .describe('Pagination offset, used when ordering by a column (e.g. duration). Defaults to 0.'),- rootSpans: zod- .boolean()- .default(tracingSpansSparklineCreateBodyQueryOneRootSpansDefault)- .describe('Filter to root spans only. Defaults to true.'),- prefetchSpans: zod.number().optional().describe('Number of child spans to prefetch per trace (1-100).'),- excludeAttributes: zod- .boolean()- .default(tracingSpansSparklineCreateBodyQueryOneExcludeAttributesDefault)- .describe(- 'Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.'- ),})- .describe('The tracing spans query to execute.'),+ .describe('The sparkline \/ duration-histogram query to execute.'),})export const tracingSpansTraceCreateBodyExcludeAttributesDefault = falsediff --git a/products/tracing/mcp/prompts/query-apm-spans.md b/products/tracing/mcp/prompts/query-apm-spans.mdindex 4b351596d0f8..9d015d9b9ad1 100644--- a/products/tracing/mcp/prompts/query-apm-spans.md+++ b/products/tracing/mcp/prompts/query-apm-spans.md@@ -78,6 +78,10 @@ Filter to a specific trace ID (hex string). Use this when you already know the tSet `true` to return **only root spans** — one entry span per matching trace, which collapses each trace to a single row. Useful for "list the traces matching X" without sifting through `matched_filter`. Leave unset (or `false`) to get all spans of matching traces, where you read `matched_filter` to find the ones that matched. The frontend leaves this unset.+## query.flatSpans++Set `true` to return **the matching spans themselves, one row per span** (root and child), rather than collapsing to traces. This is the way to search by a child-span attribute (e.g. `code.filepath`) — the result is the matching child spans directly, not the traces that contain them. Streams under `ORDER BY … LIMIT`, so it stays bounded on hot child attributes where the whole-trace grouping would not. Distinct from `rootSpans` (which scopes whole-trace selection); `prefetchSpans` is ignored. Defaults to false.+## query.limitMaximum number of results (1-1000). Defaults to 100.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex c142b75a3390..c69d02b0d2a2 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -5222,7 +5222,7 @@}},"query-apm-spans": {- "description": "Query trace spans with filtering by service name, status code, date range, and structured attribute filters. Supports cursor-based pagination. Returns spans with uuid, trace_id, span_id, parent_span_id, name, kind, service_name, status_code, timestamp, end_time, duration_nano, is_root_span, matched_filter, and attributes (the span-level OTel attribute map, e.g. db.statement, http.url).\n\nUse 'apm-attributes-list' and 'apm-attribute-values-list' to discover available attributes before building filters. Use 'apm-services-list' to discover available services.\n\n# Return shape\n\nResults are **grouped by trace**, not a flat list of matching spans. For each trace that contains at least one span matching your filters, the response includes spans from that trace (up to `prefetchSpans` per trace, root span first). Two fields tell you which spans actually matched:\n\n- `matched_filter` — `1` if **this span** satisfies your `filterGroup`/`serviceNames`/`statusCodes`, `0` if it's only included because it shares a trace with a match (e.g. a prefetched sibling or the trace's root). When you filter by a child span's name, the matching child has `matched_filter: 1` and its root/siblings have `matched_filter: 0`.\n- `is_root_span` — `true` for the trace's entry span.\n\nTo collapse each matching trace to a **single row — its root span**, set `rootSpans: true` — see below. (The row is the trace's entry span, which may itself carry `matched_filter: 0` when the match was on a child.) To inspect a single trace's full tree, take a `trace_id` from the results and call `apm-trace-get`.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Span property types are:\n - `span` — filters built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span).\n - `span_attribute` — filters span-level attributes (e.g. \"http.method\", \"http.status_code\").\n - `span_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `apm-attributes-list` to discover available attribute keys** before building filters.\n- **Use `apm-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\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\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window. If the question doesn't mention time, the default is the last hour (`-1h`). Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.serviceNames\n\nFilter by service names. Use `apm-services-list` to discover available services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Defaults to the last hour (`-1h`).\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.traceId\n\nFilter to a specific trace ID (hex string). Use this when you already know the trace ID.\n\n## query.rootSpans\n\nSet `true` to return **only root spans** — one entry span per matching trace, which collapses each trace to a single row. Useful for \"list the traces matching X\" without sifting through `matched_filter`. Leave unset (or `false`) to get all spans of matching traces, where you read `matched_filter` to find the ones that matched. The frontend leaves this unset.\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.prefetchSpans\n\nNumber of spans to return per matching trace (1-100), root span first. Useful to preview trace structure without a separate `apm-trace-get`. With the default (1) you get one span per trace (the root); raise it to also pull the matching children and their siblings (check `matched_filter` to tell them apart). Ignored when `rootSpans: true`, which always returns just the root.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-span `attributes` map from results (the map stays present but empty). The attribute map holds multi-KB values like `db.statement`, so excluding it keeps large result sets compact — set it when you only need span structure/timing (`name`, `service_name`, `duration_nano`, `parent_span_id`) and not the OTel attributes. Defaults to false.\n\n# Examples\n\n## List recent error spans\n\n```json\n{\n \"query\": {\n \"statusCodes\": [2]\n }\n}\n```\n\n## Search spans from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a span attribute\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"http.method\", \"operator\": \"exact\", \"type\": \"span_attribute\", \"value\": \"POST\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Find slow spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"duration\", \"operator\": \"gt\", \"type\": \"span\", \"value\": \"1000000000\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine service and attribute filters\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"web-server\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"gt\", \"type\": \"span_attribute\", \"value\": \"399\" }],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Check if a resource attribute exists\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"k8s.pod.name\", \"operator\": \"is_set\", \"type\": \"span_resource_attribute\" }]\n }\n}\n```\n\n# Reminders\n\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Use `apm-services-list` to discover available services before filtering by service name.\n- Duration values are in nanoseconds (1 second = 1,000,000,000 nanoseconds).",+ "description": "Query trace spans with filtering by service name, status code, date range, and structured attribute filters. Supports cursor-based pagination. Returns spans with uuid, trace_id, span_id, parent_span_id, name, kind, service_name, status_code, timestamp, end_time, duration_nano, is_root_span, matched_filter, and attributes (the span-level OTel attribute map, e.g. db.statement, http.url).\n\nUse 'apm-attributes-list' and 'apm-attribute-values-list' to discover available attributes before building filters. Use 'apm-services-list' to discover available services.\n\n# Return shape\n\nResults are **grouped by trace**, not a flat list of matching spans. For each trace that contains at least one span matching your filters, the response includes spans from that trace (up to `prefetchSpans` per trace, root span first). Two fields tell you which spans actually matched:\n\n- `matched_filter` — `1` if **this span** satisfies your `filterGroup`/`serviceNames`/`statusCodes`, `0` if it's only included because it shares a trace with a match (e.g. a prefetched sibling or the trace's root). When you filter by a child span's name, the matching child has `matched_filter: 1` and its root/siblings have `matched_filter: 0`.\n- `is_root_span` — `true` for the trace's entry span.\n\nTo collapse each matching trace to a **single row — its root span**, set `rootSpans: true` — see below. (The row is the trace's entry span, which may itself carry `matched_filter: 0` when the match was on a child.) To inspect a single trace's full tree, take a `trace_id` from the results and call `apm-trace-get`.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Span property types are:\n - `span` — filters built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span).\n - `span_attribute` — filters span-level attributes (e.g. \"http.method\", \"http.status_code\").\n - `span_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `apm-attributes-list` to discover available attribute keys** before building filters.\n- **Use `apm-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\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\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window. If the question doesn't mention time, the default is the last hour (`-1h`). Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.serviceNames\n\nFilter by service names. Use `apm-services-list` to discover available services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Defaults to the last hour (`-1h`).\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.traceId\n\nFilter to a specific trace ID (hex string). Use this when you already know the trace ID.\n\n## query.rootSpans\n\nSet `true` to return **only root spans** — one entry span per matching trace, which collapses each trace to a single row. Useful for \"list the traces matching X\" without sifting through `matched_filter`. Leave unset (or `false`) to get all spans of matching traces, where you read `matched_filter` to find the ones that matched. The frontend leaves this unset.\n\n## query.flatSpans\n\nSet `true` to return **the matching spans themselves, one row per span** (root and child), rather than collapsing to traces. This is the way to search by a child-span attribute (e.g. `code.filepath`) — the result is the matching child spans directly, not the traces that contain them. Streams under `ORDER BY … LIMIT`, so it stays bounded on hot child attributes where the whole-trace grouping would not. Distinct from `rootSpans` (which scopes whole-trace selection); `prefetchSpans` is ignored. Defaults to false.\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.prefetchSpans\n\nNumber of spans to return per matching trace (1-100), root span first. Useful to preview trace structure without a separate `apm-trace-get`. With the default (1) you get one span per trace (the root); raise it to also pull the matching children and their siblings (check `matched_filter` to tell them apart). Ignored when `rootSpans: true`, which always returns just the root.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-span `attributes` map from results (the map stays present but empty). The attribute map holds multi-KB values like `db.statement`, so excluding it keeps large result sets compact — set it when you only need span structure/timing (`name`, `service_name`, `duration_nano`, `parent_span_id`) and not the OTel attributes. Defaults to false.\n\n# Examples\n\n## List recent error spans\n\n```json\n{\n \"query\": {\n \"statusCodes\": [2]\n }\n}\n```\n\n## Search spans from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a span attribute\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"http.method\", \"operator\": \"exact\", \"type\": \"span_attribute\", \"value\": \"POST\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Find slow spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"duration\", \"operator\": \"gt\", \"type\": \"span\", \"value\": \"1000000000\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine service and attribute filters\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"web-server\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"gt\", \"type\": \"span_attribute\", \"value\": \"399\" }],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Check if a resource attribute exists\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"k8s.pod.name\", \"operator\": \"is_set\", \"type\": \"span_resource_attribute\" }]\n }\n}\n```\n\n# Reminders\n\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Use `apm-services-list` to discover available services before filtering by service name.\n- Duration values are in nanoseconds (1 second = 1,000,000,000 nanoseconds).","category": "Tracing","feature": "tracing","summary": "Query tracing spans",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 25dca73e7e30..3fd4eea6ba46 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5659,7 +5659,7 @@}},"query-apm-spans": {- "description": "Query trace spans with filtering by service name, status code, date range, and structured attribute filters. Supports cursor-based pagination. Returns spans with uuid, trace_id, span_id, parent_span_id, name, kind, service_name, status_code, timestamp, end_time, duration_nano, is_root_span, matched_filter, and attributes (the span-level OTel attribute map, e.g. db.statement, http.url).\n\nUse 'apm-attributes-list' and 'apm-attribute-values-list' to discover available attributes before building filters. Use 'apm-services-list' to discover available services.\n\n# Return shape\n\nResults are **grouped by trace**, not a flat list of matching spans. For each trace that contains at least one span matching your filters, the response includes spans from that trace (up to `prefetchSpans` per trace, root span first). Two fields tell you which spans actually matched:\n\n- `matched_filter` — `1` if **this span** satisfies your `filterGroup`/`serviceNames`/`statusCodes`, `0` if it's only included because it shares a trace with a match (e.g. a prefetched sibling or the trace's root). When you filter by a child span's name, the matching child has `matched_filter: 1` and its root/siblings have `matched_filter: 0`.\n- `is_root_span` — `true` for the trace's entry span.\n\nTo collapse each matching trace to a **single row — its root span**, set `rootSpans: true` — see below. (The row is the trace's entry span, which may itself carry `matched_filter: 0` when the match was on a child.) To inspect a single trace's full tree, take a `trace_id` from the results and call `apm-trace-get`.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Span property types are:\n - `span` — filters built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span).\n - `span_attribute` — filters span-level attributes (e.g. \"http.method\", \"http.status_code\").\n - `span_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `apm-attributes-list` to discover available attribute keys** before building filters.\n- **Use `apm-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\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\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window. If the question doesn't mention time, the default is the last hour (`-1h`). Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.serviceNames\n\nFilter by service names. Use `apm-services-list` to discover available services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Defaults to the last hour (`-1h`).\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.traceId\n\nFilter to a specific trace ID (hex string). Use this when you already know the trace ID.\n\n## query.rootSpans\n\nSet `true` to return **only root spans** — one entry span per matching trace, which collapses each trace to a single row. Useful for \"list the traces matching X\" without sifting through `matched_filter`. Leave unset (or `false`) to get all spans of matching traces, where you read `matched_filter` to find the ones that matched. The frontend leaves this unset.\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.prefetchSpans\n\nNumber of spans to return per matching trace (1-100), root span first. Useful to preview trace structure without a separate `apm-trace-get`. With the default (1) you get one span per trace (the root); raise it to also pull the matching children and their siblings (check `matched_filter` to tell them apart). Ignored when `rootSpans: true`, which always returns just the root.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-span `attributes` map from results (the map stays present but empty). The attribute map holds multi-KB values like `db.statement`, so excluding it keeps large result sets compact — set it when you only need span structure/timing (`name`, `service_name`, `duration_nano`, `parent_span_id`) and not the OTel attributes. Defaults to false.\n\n# Examples\n\n## List recent error spans\n\n```json\n{\n \"query\": {\n \"statusCodes\": [2]\n }\n}\n```\n\n## Search spans from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a span attribute\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"http.method\", \"operator\": \"exact\", \"type\": \"span_attribute\", \"value\": \"POST\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Find slow spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"duration\", \"operator\": \"gt\", \"type\": \"span\", \"value\": \"1000000000\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine service and attribute filters\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"web-server\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"gt\", \"type\": \"span_attribute\", \"value\": \"399\" }],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Check if a resource attribute exists\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"k8s.pod.name\", \"operator\": \"is_set\", \"type\": \"span_resource_attribute\" }]\n }\n}\n```\n\n# Reminders\n\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Use `apm-services-list` to discover available services before filtering by service name.\n- Duration values are in nanoseconds (1 second = 1,000,000,000 nanoseconds).",+ "description": "Query trace spans with filtering by service name, status code, date range, and structured attribute filters. Supports cursor-based pagination. Returns spans with uuid, trace_id, span_id, parent_span_id, name, kind, service_name, status_code, timestamp, end_time, duration_nano, is_root_span, matched_filter, and attributes (the span-level OTel attribute map, e.g. db.statement, http.url).\n\nUse 'apm-attributes-list' and 'apm-attribute-values-list' to discover available attributes before building filters. Use 'apm-services-list' to discover available services.\n\n# Return shape\n\nResults are **grouped by trace**, not a flat list of matching spans. For each trace that contains at least one span matching your filters, the response includes spans from that trace (up to `prefetchSpans` per trace, root span first). Two fields tell you which spans actually matched:\n\n- `matched_filter` — `1` if **this span** satisfies your `filterGroup`/`serviceNames`/`statusCodes`, `0` if it's only included because it shares a trace with a match (e.g. a prefetched sibling or the trace's root). When you filter by a child span's name, the matching child has `matched_filter: 1` and its root/siblings have `matched_filter: 0`.\n- `is_root_span` — `true` for the trace's entry span.\n\nTo collapse each matching trace to a **single row — its root span**, set `rootSpans: true` — see below. (The row is the trace's entry span, which may itself carry `matched_filter: 0` when the match was on a child.) To inspect a single trace's full tree, take a `trace_id` from the results and call `apm-trace-get`.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Span property types are:\n - `span` — filters built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span).\n - `span_attribute` — filters span-level attributes (e.g. \"http.method\", \"http.status_code\").\n - `span_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `apm-attributes-list` to discover available attribute keys** before building filters.\n- **Use `apm-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\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\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window. If the question doesn't mention time, the default is the last hour (`-1h`). Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.serviceNames\n\nFilter by service names. Use `apm-services-list` to discover available services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Defaults to the last hour (`-1h`).\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.traceId\n\nFilter to a specific trace ID (hex string). Use this when you already know the trace ID.\n\n## query.rootSpans\n\nSet `true` to return **only root spans** — one entry span per matching trace, which collapses each trace to a single row. Useful for \"list the traces matching X\" without sifting through `matched_filter`. Leave unset (or `false`) to get all spans of matching traces, where you read `matched_filter` to find the ones that matched. The frontend leaves this unset.\n\n## query.flatSpans\n\nSet `true` to return **the matching spans themselves, one row per span** (root and child), rather than collapsing to traces. This is the way to search by a child-span attribute (e.g. `code.filepath`) — the result is the matching child spans directly, not the traces that contain them. Streams under `ORDER BY … LIMIT`, so it stays bounded on hot child attributes where the whole-trace grouping would not. Distinct from `rootSpans` (which scopes whole-trace selection); `prefetchSpans` is ignored. Defaults to false.\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.prefetchSpans\n\nNumber of spans to return per matching trace (1-100), root span first. Useful to preview trace structure without a separate `apm-trace-get`. With the default (1) you get one span per trace (the root); raise it to also pull the matching children and their siblings (check `matched_filter` to tell them apart). Ignored when `rootSpans: true`, which always returns just the root.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-span `attributes` map from results (the map stays present but empty). The attribute map holds multi-KB values like `db.statement`, so excluding it keeps large result sets compact — set it when you only need span structure/timing (`name`, `service_name`, `duration_nano`, `parent_span_id`) and not the OTel attributes. Defaults to false.\n\n# Examples\n\n## List recent error spans\n\n```json\n{\n \"query\": {\n \"statusCodes\": [2]\n }\n}\n```\n\n## Search spans from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a span attribute\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"http.method\", \"operator\": \"exact\", \"type\": \"span_attribute\", \"value\": \"POST\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Find slow spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"duration\", \"operator\": \"gt\", \"type\": \"span\", \"value\": \"1000000000\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine service and attribute filters\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"web-server\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"gt\", \"type\": \"span_attribute\", \"value\": \"399\" }],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Check if a resource attribute exists\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"k8s.pod.name\", \"operator\": \"is_set\", \"type\": \"span_resource_attribute\" }]\n }\n}\n```\n\n# Reminders\n\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Use `apm-services-list` to discover available services before filtering by service name.\n- Duration values are in nanoseconds (1 second = 1,000,000,000 nanoseconds).","category": "Tracing","feature": "tracing","summary": "Query tracing spans",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 665d1a9c779e..8ec1e6f51da7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -22516,6 +22516,8 @@ export namespace Schemas {/** Omit the per-span `attributes` map from results to keep payloads compact */excludeAttributes?: boolean | null;filterGroup?: PropertyGroupFilter | null;+ /** Return the matching spans themselves, one row per span (root and child), instead of the whole-trace grouping. Streams the matches under `ORDER BY … LIMIT` rather than grouping every matching span by trace, so a filter on a hot child attribute (e.g. `code.filepath`) stays bounded. Distinct from `rootSpans`, which scopes whole-trace selection. The single-trace waterfall never sets this. */+ flatSpans?: boolean | null;kind?: 'TraceSpansQuery';limit?: number | null;/** Modifiers used when performing the query */@@ -46125,6 +46127,8 @@ export namespace Schemas {offset?: number;/** Filter to root spans only. Defaults to true. */rootSpans?: boolean;+ /** Return the matching spans themselves, one row per span (root and child), instead of collapsing to traces. Use this to search by a child-span attribute (e.g. code.filepath) without the whole-trace grouping. Distinct from rootSpans. Defaults to false. */+ flatSpans?: boolean;/** Number of child spans to prefetch per trace (1-100). */prefetchSpans?: number;/** Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false. */@@ -46136,6 +46140,22 @@ export namespace Schemas {query: _TracingQueryBody;}+ export interface _TracingTimeseriesQueryBody {+ /** Date range for the query. Defaults to last hour. */+ dateRange?: _TracingDateRange;+ /** Filter by service names. */+ serviceNames?: string[];+ /** Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans. */+ statusCodes?: number[];+ /** Property filters for the query. */+ filterGroup?: _SpanPropertyFilter[];+ }++ export interface _TracingTimeseriesRequest {+ /** The sparkline / duration-histogram query to execute. */+ query: _TracingTimeseriesQueryBody;+ }+export interface _TracingTraceRequest {/** Date range for the query. Defaults to last 24 hours. */dateRange?: _TracingDateRange;diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.tsindex bf5d404a8611..07c78c088c23 100644--- a/services/mcp/src/generated/tracing/api.ts+++ b/services/mcp/src/generated/tracing/api.ts@@ -348,11 +348,6 @@ export const TracingSpansDurationHistogramCreateParams = /* @__PURE__ */ zod.obj})export const tracingSpansDurationHistogramCreateBodyQueryOneFilterGroupDefault = []-export const tracingSpansDurationHistogramCreateBodyQueryOneLimitDefault = 100-export const tracingSpansDurationHistogramCreateBodyQueryOneOffsetMin = 0--export const tracingSpansDurationHistogramCreateBodyQueryOneRootSpansDefault = true-export const tracingSpansDurationHistogramCreateBodyQueryOneExcludeAttributesDefault = falseexport const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.object({query: zod@@ -379,20 +374,6 @@ export const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.objec.describe('Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans.'),- orderBy: zod- .enum(['timestamp', 'duration'])- .describe('* `timestamp` - timestamp\n* `duration` - duration')- .optional()- .describe(- "Column to order by. Defaults to timestamp. Ordering by timestamp paginates via the keyset cursor ('after'); ordering by duration paginates via 'offset'.\n\n* `timestamp` - timestamp\n* `duration` - duration"- ),- orderDirection: zod- .enum(['ASC', 'DESC'])- .describe('* `ASC` - ASC\n* `DESC` - DESC')- .optional()- .describe(- 'Order direction. Defaults to DESC (e.g. timestamp+DESC = newest first, duration+DESC = slowest first).\n\n* `ASC` - ASC\n* `DESC` - DESC'- ),filterGroup: zod.array(zod.object({@@ -438,33 +419,8 @@ export const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.objec).default(tracingSpansDurationHistogramCreateBodyQueryOneFilterGroupDefault).describe('Property filters for the query.'),- traceId: zod.string().optional().describe('Filter to a specific trace ID (hex string).'),- limit: zod- .number()- .default(tracingSpansDurationHistogramCreateBodyQueryOneLimitDefault)- .describe('Max results (1-1000). Defaults to 100.'),- after: zod- .string()- .optional()- .describe('Keyset pagination cursor from a previous timestamp-ordered response.'),- offset: zod- .number()- .min(tracingSpansDurationHistogramCreateBodyQueryOneOffsetMin)- .optional()- .describe('Pagination offset, used when ordering by a column (e.g. duration). Defaults to 0.'),- rootSpans: zod- .boolean()- .default(tracingSpansDurationHistogramCreateBodyQueryOneRootSpansDefault)- .describe('Filter to root spans only. Defaults to true.'),- prefetchSpans: zod.number().optional().describe('Number of child spans to prefetch per trace (1-100).'),- excludeAttributes: zod- .boolean()- .default(tracingSpansDurationHistogramCreateBodyQueryOneExcludeAttributesDefault)- .describe(- 'Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.'- ),})- .describe('The tracing spans query to execute.'),+ .describe('The sparkline / duration-histogram query to execute.'),})export const TracingSpansQueryCreateParams = /* @__PURE__ */ zod.object({@@ -480,6 +436,7 @@ export const tracingSpansQueryCreateBodyQueryOneLimitDefault = 100export const tracingSpansQueryCreateBodyQueryOneOffsetMin = 0export const tracingSpansQueryCreateBodyQueryOneRootSpansDefault = true+export const tracingSpansQueryCreateBodyQueryOneFlatSpansDefault = falseexport const tracingSpansQueryCreateBodyQueryOneExcludeAttributesDefault = falseexport const TracingSpansQueryCreateBody = /* @__PURE__ */ zod.object({@@ -584,6 +541,12 @@ export const TracingSpansQueryCreateBody = /* @__PURE__ */ zod.object({.boolean().default(tracingSpansQueryCreateBodyQueryOneRootSpansDefault).describe('Filter to root spans only. Defaults to true.'),+ flatSpans: zod+ .boolean()+ .default(tracingSpansQueryCreateBodyQueryOneFlatSpansDefault)+ .describe(+ 'Return the matching spans themselves, one row per span (root and child), instead of collapsing to traces. Use this to search by a child-span attribute (e.g. code.filepath) without the whole-trace grouping. Distinct from rootSpans. Defaults to false.'+ ),prefetchSpans: zod.number().optional().describe('Number of child spans to prefetch per trace (1-100).'),excludeAttributes: zod.boolean()@@ -617,11 +580,6 @@ export const TracingSpansSparklineCreateParams = /* @__PURE__ */ zod.object({})export const tracingSpansSparklineCreateBodyQueryOneFilterGroupDefault = []-export const tracingSpansSparklineCreateBodyQueryOneLimitDefault = 100-export const tracingSpansSparklineCreateBodyQueryOneOffsetMin = 0--export const tracingSpansSparklineCreateBodyQueryOneRootSpansDefault = true-export const tracingSpansSparklineCreateBodyQueryOneExcludeAttributesDefault = falseexport const TracingSpansSparklineCreateBody = /* @__PURE__ */ zod.object({query: zod@@ -648,20 +606,6 @@ export const TracingSpansSparklineCreateBody = /* @__PURE__ */ zod.object({.describe('Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans.'),- orderBy: zod- .enum(['timestamp', 'duration'])- .describe('* `timestamp` - timestamp\n* `duration` - duration')- .optional()- .describe(- "Column to order by. Defaults to timestamp. Ordering by timestamp paginates via the keyset cursor ('after'); ordering by duration paginates via 'offset'.\n\n* `timestamp` - timestamp\n* `duration` - duration"- ),- orderDirection: zod- .enum(['ASC', 'DESC'])- .describe('* `ASC` - ASC\n* `DESC` - DESC')- .optional()- .describe(- 'Order direction. Defaults to DESC (e.g. timestamp+DESC = newest first, duration+DESC = slowest first).\n\n* `ASC` - ASC\n* `DESC` - DESC'- ),filterGroup: zod.array(zod.object({@@ -707,33 +651,8 @@ export const TracingSpansSparklineCreateBody = /* @__PURE__ */ zod.object({).default(tracingSpansSparklineCreateBodyQueryOneFilterGroupDefault).describe('Property filters for the query.'),- traceId: zod.string().optional().describe('Filter to a specific trace ID (hex string).'),- limit: zod- .number()- .default(tracingSpansSparklineCreateBodyQueryOneLimitDefault)- .describe('Max results (1-1000). Defaults to 100.'),- after: zod- .string()- .optional()- .describe('Keyset pagination cursor from a previous timestamp-ordered response.'),- offset: zod- .number()- .min(tracingSpansSparklineCreateBodyQueryOneOffsetMin)- .optional()- .describe('Pagination offset, used when ordering by a column (e.g. duration). Defaults to 0.'),- rootSpans: zod- .boolean()- .default(tracingSpansSparklineCreateBodyQueryOneRootSpansDefault)- .describe('Filter to root spans only. Defaults to true.'),- prefetchSpans: zod.number().optional().describe('Number of child spans to prefetch per trace (1-100).'),- excludeAttributes: zod- .boolean()- .default(tracingSpansSparklineCreateBodyQueryOneExcludeAttributesDefault)- .describe(- 'Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.'- ),})- .describe('The tracing spans query to execute.'),+ .describe('The sparkline / duration-histogram query to execute.'),})export const tracingSpansTraceCreatePathTraceIdRegExp = new RegExp('^[a-zA-Z0-9]+$')diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-duration-histogram.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-duration-histogram.jsonindex 566e17b7f3ab..0ead90f92166 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-duration-histogram.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-duration-histogram.json@@ -2,12 +2,8 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"query": {- "description": "The tracing spans query to execute.",+ "description": "The sparkline / duration-histogram query to execute.","properties": {- "after": {- "description": "Keyset pagination cursor from a previous timestamp-ordered response.",- "type": "string"- },"dateRange": {"description": "Date range for the query. Defaults to last hour.","properties": {@@ -36,11 +32,6 @@},"type": "object"},- "excludeAttributes": {- "default": false,- "description": "Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.",- "type": "boolean"- },"filterGroup": {"default": [],"description": "Property filters for the query.",@@ -80,35 +71,6 @@},"type": "array"},- "limit": {- "default": 100,- "description": "Max results (1-1000). Defaults to 100.",- "type": "number"- },- "offset": {- "description": "Pagination offset, used when ordering by a column (e.g. duration). Defaults to 0.",- "minimum": 0,- "type": "number"- },- "orderBy": {- "description": "Column to order by. Defaults to timestamp. Ordering by timestamp paginates via the keyset cursor ('after'); ordering by duration paginates via 'offset'.\n\n* `timestamp` - timestamp\n* `duration` - duration",- "enum": ["timestamp", "duration"],- "type": "string"- },- "orderDirection": {- "description": "Order direction. Defaults to DESC (e.g. timestamp+DESC = newest first, duration+DESC = slowest first).\n\n* `ASC` - ASC\n* `DESC` - DESC",- "enum": ["ASC", "DESC"],- "type": "string"- },- "prefetchSpans": {- "description": "Number of child spans to prefetch per trace (1-100).",- "type": "number"- },- "rootSpans": {- "default": true,- "description": "Filter to root spans only. Defaults to true.",- "type": "boolean"- },"serviceNames": {"description": "Filter by service names.","items": {@@ -122,10 +84,6 @@"type": "number"},"type": "array"- },- "traceId": {- "description": "Filter to a specific trace ID (hex string).",- "type": "string"}},"type": "object"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-sparkline.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-sparkline.jsonindex 566e17b7f3ab..0ead90f92166 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-sparkline.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-sparkline.json@@ -2,12 +2,8 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"query": {- "description": "The tracing spans query to execute.",+ "description": "The sparkline / duration-histogram query to execute.","properties": {- "after": {- "description": "Keyset pagination cursor from a previous timestamp-ordered response.",- "type": "string"- },"dateRange": {"description": "Date range for the query. Defaults to last hour.","properties": {@@ -36,11 +32,6 @@},"type": "object"},- "excludeAttributes": {- "default": false,- "description": "Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.",- "type": "boolean"- },"filterGroup": {"default": [],"description": "Property filters for the query.",@@ -80,35 +71,6 @@},"type": "array"},- "limit": {- "default": 100,- "description": "Max results (1-1000). Defaults to 100.",- "type": "number"- },- "offset": {- "description": "Pagination offset, used when ordering by a column (e.g. duration). Defaults to 0.",- "minimum": 0,- "type": "number"- },- "orderBy": {- "description": "Column to order by. Defaults to timestamp. Ordering by timestamp paginates via the keyset cursor ('after'); ordering by duration paginates via 'offset'.\n\n* `timestamp` - timestamp\n* `duration` - duration",- "enum": ["timestamp", "duration"],- "type": "string"- },- "orderDirection": {- "description": "Order direction. Defaults to DESC (e.g. timestamp+DESC = newest first, duration+DESC = slowest first).\n\n* `ASC` - ASC\n* `DESC` - DESC",- "enum": ["ASC", "DESC"],- "type": "string"- },- "prefetchSpans": {- "description": "Number of child spans to prefetch per trace (1-100).",- "type": "number"- },- "rootSpans": {- "default": true,- "description": "Filter to root spans only. Defaults to true.",- "type": "boolean"- },"serviceNames": {"description": "Filter by service names.","items": {@@ -122,10 +84,6 @@"type": "number"},"type": "array"- },- "traceId": {- "description": "Filter to a specific trace ID (hex string).",- "type": "string"}},"type": "object"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-apm-spans.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-apm-spans.jsonindex 566e17b7f3ab..1a3572ebe953 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-apm-spans.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-apm-spans.json@@ -80,6 +80,11 @@},"type": "array"},+ "flatSpans": {+ "default": false,+ "description": "Return the matching spans themselves, one row per span (root and child), instead of collapsing to traces. Use this to search by a child-span attribute (e.g. code.filepath) without the whole-trace grouping. Distinct from rootSpans. Defaults to false.",+ "type": "boolean"+ },"limit": {"default": 100,"description": "Max results (1-1000). Defaults to 100.",