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.

feat(tracing): add apm-spans-count tool for cheap pre-flight counts (#61423)

Jon McCallum873834c7f62f
diff --git a/products/tracing/backend/count_query_runner.py b/products/tracing/backend/count_query_runner.py
new file mode 100644
index 000000000000..409f3b53e5e6
--- /dev/null
+++ b/products/tracing/backend/count_query_runner.py
@@ -0,0 +1,102 @@
+from functools import cached_property
+from typing import TYPE_CHECKING
+
+from posthog.schema import (
+ CachedTraceSpansQueryResponse,
+ DateRange,
+ HogQLFilters,
+ PropertyGroupFilter,
+ TraceSpansQuery,
+ TraceSpansQueryResponse,
+)
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.parser import parse_expr, parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import Workload
+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, ExecutionMode
+
+from products.tracing.backend.logic import TraceSpansQueryRunnerMixin
+
+if TYPE_CHECKING:
+ from posthog.models import Team
+
+
+class TraceSpansCountQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[TraceSpansQueryResponse]):
+ """Returns a scalar count of trace spans matching the given filters.
+
+ Cheap pre-flight before query-apm-spans: lets a caller size the result set before
+ pulling rows. Reuses the shared filter builder so the count matches what the list query
+ would select."""
+
+ query: TraceSpansQuery
+ cached_response: CachedTraceSpansQueryResponse
+
+ @cached_property
+ def settings(self) -> HogQLGlobalSettings:
+ # A count should fail fast rather than scan unbounded data — matches the caps the
+ # logs count runner uses against the same kind of table.
+ return HogQLGlobalSettings(
+ max_execution_time=30,
+ max_bytes_to_read=10_000_000_000,
+ read_overflow_mode="throw",
+ )
+
+ def _calculate(self) -> TraceSpansQueryResponse:
+ response = execute_hogql_query(
+ query_type="TraceSpansQuery",
+ query=self.to_query(),
+ modifiers=self.modifiers,
+ team=self.team,
+ workload=Workload.LOGS,
+ timings=self.timings,
+ filters=HogQLFilters(dateRange=self.query.dateRange),
+ settings=self.settings,
+ )
+ count = response.results[0][0] if response.results else 0
+ return TraceSpansQueryResponse(results={"count": count})
+
+ def to_query(self) -> ast.SelectQuery:
+ # where() bounds the window by time_bucket (day precision); add explicit half-open
+ # per-row timestamp bounds so the count matches the requested window exactly.
+ where_with_timestamp = ast.And(
+ exprs=[
+ self.where(),
+ parse_expr(
+ "timestamp >= {date_from} AND timestamp < {date_to}",
+ placeholders={
+ "date_from": ast.Constant(value=self.query_date_range.date_from()),
+ "date_to": ast.Constant(value=self.query_date_range.date_to()),
+ },
+ ),
+ ]
+ )
+ query = parse_select(
+ "SELECT count() FROM posthog.trace_spans WHERE {where}",
+ placeholders={"where": where_with_timestamp},
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+
+def run_count_query(
+ *,
+ team: "Team",
+ date_range: DateRange,
+ service_names: list[str] | None = None,
+ status_codes: list[int] | None = None,
+ filter_group: PropertyGroupFilter | None = None,
+) -> TraceSpansQueryResponse | CachedTraceSpansQueryResponse:
+ """Facade-friendly entry point for running a span count query."""
+ query = TraceSpansQuery(
+ dateRange=date_range,
+ serviceNames=service_names,
+ statusCodes=status_codes,
+ filterGroup=filter_group,
+ )
+ runner = TraceSpansCountQueryRunner(query, team)
+ response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ assert isinstance(response, TraceSpansQueryResponse | CachedTraceSpansQueryResponse)
+ return response
diff --git a/products/tracing/backend/facade/api.py b/products/tracing/backend/facade/api.py
index fde72cffa77b..f02f4882bcc4 100644
--- a/products/tracing/backend/facade/api.py
+++ b/products/tracing/backend/facade/api.py
@@ -16,9 +16,36 @@ Do NOT:
- Return ORM instances or QuerySets
"""
+from typing import TYPE_CHECKING
+
+from posthog.schema import CachedTraceSpansQueryResponse, DateRange, PropertyGroupFilter, TraceSpansQueryResponse
+
+from products.tracing.backend.count_query_runner import run_count_query as _run_count_query
+
+if TYPE_CHECKING:
+ from posthog.models import Team
+
# --- Converters (model -> frozen dataclass) ---
#
# These look repetitive when fields align 1:1. The value is having ONE place
# where "internal" becomes "external contract". When models and contracts drift,
# the mapper absorbs the change instead of it leaking everywhere.
+
+
+def run_count_query(
+ *,
+ team: "Team",
+ date_range: DateRange,
+ service_names: list[str] | None = None,
+ status_codes: list[int] | None = None,
+ filter_group: PropertyGroupFilter | None = None,
+) -> TraceSpansQueryResponse | CachedTraceSpansQueryResponse:
+ """Run a cheap scalar count of trace spans matching the given filters."""
+ return _run_count_query(
+ team=team,
+ date_range=date_range,
+ service_names=service_names,
+ status_codes=status_codes,
+ filter_group=filter_group,
+ )
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index 53d519daa622..c39b24a11eff 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -39,6 +39,7 @@ from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.event_usage import report_user_action
from posthog.hogql_queries.query_runner import ExecutionMode
+from ..facade.api import run_count_query
from ..has_spans_query_runner import team_has_spans
from ..logic import (
TraceSpansQueryRunner,
@@ -286,6 +287,37 @@ class _HasSpansResponseSerializer(serializers.Serializer):
)
+class _TracingCountBodySerializer(serializers.Serializer):
+ dateRange = _TracingDateRangeSerializer(
+ required=False,
+ help_text="Date range for the count. 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 HTTP status codes.",
+ )
+ filterGroup = serializers.ListField(
+ child=_SpanPropertyFilterSerializer(),
+ required=False,
+ default=[],
+ help_text="Property filters for the count.",
+ )
+
+
+class _TracingCountRequestSerializer(serializers.Serializer):
+ query = _TracingCountBodySerializer(help_text="The span count query to execute.")
+
+
+class _TracingCountResponseSerializer(serializers.Serializer):
+ count = serializers.IntegerField(help_text="Number of spans matching the filters.")
+
+
class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
scope_object = "tracing"
serializer_class = _FallbackSerializer
@@ -423,6 +455,41 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
status=status.HTTP_200_OK,
)
+ @extend_schema(request=_TracingCountRequestSerializer, responses={200: _TracingCountResponseSerializer})
+ @action(detail=False, methods=["POST"], required_scopes=["tracing:read"])
+ def count(self, request: Request, *args, **kwargs) -> Response:
+ tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
+ query_data = request.data.get("query", {})
+
+ date_range = self.get_model(query_data.get("dateRange", {"date_from": "-1h"}), DateRange)
+ filter_group = (
+ self.get_model(self._normalize_filter_group(query_data.get("filterGroup")), PropertyGroupFilter)
+ if query_data.get("filterGroup")
+ else None
+ )
+
+ response = run_count_query(
+ team=self.team,
+ date_range=date_range,
+ service_names=query_data.get("serviceNames", None),
+ status_codes=query_data.get("statusCodes", None),
+ filter_group=filter_group,
+ )
+
+ report_user_action(
+ request.user,
+ "tracing count queried",
+ {
+ "has_filter_group": bool(query_data.get("filterGroup")),
+ "service_names_count": len(query_data.get("serviceNames") or []),
+ "status_codes_count": len(query_data.get("statusCodes") or []),
+ },
+ team=self.team,
+ request=request,
+ )
+
+ return Response(response.results, status=status.HTTP_200_OK)
+
@extend_schema(request=_TracingQueryRequestSerializer)
@action(detail=False, methods=["POST"], required_scopes=["tracing:read"])
def sparkline(self, request: Request, *args, **kwargs) -> Response:
diff --git a/products/tracing/backend/tests/test_count_query_runner.py b/products/tracing/backend/tests/test_count_query_runner.py
new file mode 100644
index 000000000000..15dfef246b2e
--- /dev/null
+++ b/products/tracing/backend/tests/test_count_query_runner.py
@@ -0,0 +1,104 @@
+import base64
+import datetime as dt
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from parameterized import parameterized
+
+from posthog.schema import DateRange
+
+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
+
+from products.tracing.backend.count_query_runner import run_count_query
+
+DATE_FROM = "2026-06-02T07:00:00Z"
+DATE_TO = "2026-06-02T09:00:00Z"
+NUM_TRACES = 3 # each trace = 1 root + 2 children = 3 spans → 9 spans total
+ROOT_NAME = "process_query_model"
+
+
+def _b64(raw: bytes) -> str:
+ return base64.b64encode(raw).decode("ascii")
+
+
+class TestTraceSpansCount(ClickhouseTestMixin, APIBaseTest):
+ 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())
+
+ base = dt.datetime(2026, 6, 2, 8, 0, 0)
+
+ def _row(uuid_suffix: int, trace_id: str, span_id: str, parent: str, name: str, ts_str: str) -> str:
+ return (
+ "("
+ f"'019e8754-0000-0000-0000-{uuid_suffix:012d}', {cls.team.id}, '{trace_id}', "
+ f"'{span_id}', '{parent}', '{name}', 2, '{ts_str}', '{ts_str}', '{ts_str}', 0, 'web'"
+ ")"
+ )
+
+ rows = []
+ for t in range(NUM_TRACES):
+ trace_id = _b64((t + 1).to_bytes(16, "big"))
+ root_span_id = _b64((t * 10 + 1).to_bytes(8, "big"))
+ ts_str = (base + dt.timedelta(seconds=t)).strftime("%Y-%m-%d %H:%M:%S.%f")
+ rows.append(_row(t * 10 + 1, trace_id, root_span_id, "", ROOT_NAME, ts_str))
+ rows.append(
+ _row(t * 10 + 2, trace_id, _b64((t * 10 + 2).to_bytes(8, "big")), root_span_id, "child.a", ts_str)
+ )
+ rows.append(
+ _row(t * 10 + 3, trace_id, _b64((t * 10 + 3).to_bytes(8, "big")), root_span_id, "child.b", ts_str)
+ )
+
+ 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)
+ )
+
+ @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()
+
+ @parameterized.expand(
+ [
+ # No service filter → every span in the window.
+ ("unfiltered_returns_all_spans", None, NUM_TRACES * 3),
+ # A service that emitted nothing → zero.
+ ("no_match_returns_zero", ["does-not-exist"], 0),
+ ]
+ )
+ def test_count(self, _name, service_names, expected_count):
+ response = run_count_query(
+ team=self.team,
+ date_range=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
+ service_names=service_names,
+ )
+ self.assertEqual(response.results, {"count": expected_count})
+
+ def test_count_via_api_with_name_filter(self):
+ body = {
+ "query": {
+ "dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO},
+ "filterGroup": [{"key": "name", "type": "span", "operator": "exact", "value": ROOT_NAME}],
+ }
+ }
+ res = self.client.post(f"/api/projects/{self.team.id}/tracing/spans/count/", body, format="json")
+ self.assertEqual(res.status_code, 200, res.content)
+ # One root span named process_query_model per trace.
+ self.assertEqual(res.json(), {"count": NUM_TRACES})
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index e706030132a0..89daac14f168 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -114,6 +114,27 @@ export interface _TracingAggregationRequestApi {
query: _TracingAggregationQueryBodyApi
}
+export interface _TracingCountBodyApi {
+ /** Date range for the count. Defaults to last hour. */
+ dateRange?: _TracingDateRangeApi
+ /** Filter by service names. */
+ serviceNames?: string[]
+ /** Filter by HTTP status codes. */
+ statusCodes?: number[]
+ /** Property filters for the count. */
+ filterGroup?: _SpanPropertyFilterApi[]
+}
+
+export interface _TracingCountRequestApi {
+ /** The span count query to execute. */
+ query: _TracingCountBodyApi
+}
+
+export interface _TracingCountResponseApi {
+ /** Number of spans matching the filters. */
+ count: number
+}
+
export interface _HasSpansResponseApi {
/** Whether the team has ingested any tracing spans yet. Used to gate the onboarding empty state. */
hasSpans: boolean
diff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.ts
index 552586b65871..efac62bee9fc 100644
--- a/products/tracing/frontend/generated/api.ts
+++ b/products/tracing/frontend/generated/api.ts
@@ -14,6 +14,8 @@ import type {
TracingSpansValuesRetrieveParams,
_HasSpansResponseApi,
_TracingAggregationRequestApi,
+ _TracingCountRequestApi,
+ _TracingCountResponseApi,
_TracingQueryRequestApi,
_TracingTraceRequestApi,
_TracingTreeRequestApi,
@@ -66,6 +68,23 @@ export const tracingSpansAttributesRetrieve = async (
})
}
+export const getTracingSpansCountCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/tracing/spans/count/`
+}
+
+export const tracingSpansCountCreate = async (
+ projectId: string,
+ _tracingCountRequestApi: _TracingCountRequestApi,
+ options?: RequestInit
+): Promise<_TracingCountResponseApi> => {
+ return apiMutator<_TracingCountResponseApi>(getTracingSpansCountCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(_tracingCountRequestApi),
+ })
+}
+
export const getTracingSpansHasSpansRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/tracing/spans/has_spans/`
}
diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.ts
index 05d034d2aa3e..7dc81595795a 100644
--- a/products/tracing/frontend/generated/api.zod.ts
+++ b/products/tracing/frontend/generated/api.zod.ts
@@ -99,6 +99,77 @@ export const TracingSpansAggregateCreateBody = /* @__PURE__ */ zod.object({
.describe('The span aggregation query to execute.'),
})
+export const tracingSpansCountCreateBodyQueryOneFilterGroupDefault = []
+
+export const TracingSpansCountCreateBody = /* @__PURE__ */ zod.object({
+ query: zod
+ .object({
+ dateRange: zod
+ .object({
+ date_from: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Start of the date range. Accepts ISO 8601 timestamps or relative formats: -1h, -6h, -1d, -7d, etc.'
+ ),
+ date_to: zod
+ .string()
+ .nullish()
+ .describe('End of the date range. Same format as date_from. Omit or null for \"now\".'),
+ })
+ .optional()
+ .describe('Date range for the count. Defaults to last hour.'),
+ serviceNames: zod.array(zod.string()).optional().describe('Filter by service names.'),
+ statusCodes: zod.array(zod.number()).optional().describe('Filter by HTTP status codes.'),
+ filterGroup: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .describe(
+ 'Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code). For \"span_attribute\"\/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").'
+ ),
+ type: zod
+ .enum(['span', 'span_attribute', 'span_resource_attribute'])
+ .describe(
+ '\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'
+ )
+ .describe(
+ '\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'
+ ),
+ operator: zod
+ .enum([
+ 'exact',
+ 'is_not',
+ 'icontains',
+ 'not_icontains',
+ 'regex',
+ 'not_regex',
+ 'gt',
+ 'lt',
+ 'is_set',
+ 'is_not_set',
+ ])
+ .describe(
+ '\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `lt` - lt\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'
+ )
+ .describe(
+ 'Comparison operator.\n\n\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `lt` - lt\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'
+ ),
+ value: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Value to compare against. String, number, or array of strings. Omit for is_set\/is_not_set operators.'
+ ),
+ })
+ )
+ .default(tracingSpansCountCreateBodyQueryOneFilterGroupDefault)
+ .describe('Property filters for the count.'),
+ })
+ .describe('The span count query to execute.'),
+})
+
export const tracingSpansQueryCreateBodyQueryOneFilterGroupDefault = []
export const tracingSpansQueryCreateBodyQueryOneLimitDefault = 100
export const tracingSpansQueryCreateBodyQueryOneRootSpansDefault = true
diff --git a/products/tracing/mcp/prompts/apm-spans-count.md b/products/tracing/mcp/prompts/apm-spans-count.md
new file mode 100644
index 000000000000..bbe5e0cf20ab
--- /dev/null
+++ b/products/tracing/mcp/prompts/apm-spans-count.md
@@ -0,0 +1,59 @@
+Return a scalar count of trace spans matching a filter set. Use this as a cheap pre-flight before `query-apm-spans` — if the count is large, narrow the filters (or set `excludeAttributes`) before pulling rows.
+
+All parameters must be nested inside a `query` object.
+
+# When to use
+
+- Before `query-apm-spans`, to confirm the filter set returns a tractable number of spans rather than pulling rows blind.
+- When the user asks "how many X spans are there?" and you don't need to see individual spans.
+- To check whether a filter combination matches anything at all before committing to a full query.
+
+This counts **spans**, not traces. A single trace contains many spans, so a count of matching spans will exceed the number of matching traces.
+
+# Parameters
+
+All parameters go inside `query`.
+
+## query.dateRange
+
+Date range for the count. Defaults to the last hour (`-1h`).
+
+- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.
+- `date_to`: End of the range. Same format. Omit or null for "now".
+
+## query.serviceNames
+
+Filter by service names. Unlike `query-apm-spans`, an unfiltered count is cheap and useful for sizing up a filter before narrowing. Use `apm-services-list` to discover services.
+
+## query.statusCodes
+
+Filter by HTTP status codes (list of integers).
+
+## query.filterGroup
+
+Property filters to narrow the count. Same format as `query-apm-spans` filters — each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`.
+
+# Examples
+
+## Count error spans in a service over the last day
+
+```json
+{
+ "query": {
+ "serviceNames": ["api-gateway"],
+ "statusCodes": [500, 503],
+ "dateRange": { "date_from": "-1d" }
+ }
+}
+```
+
+## Count how many spans match a name before fetching them
+
+```json
+{
+ "query": {
+ "filterGroup": [{ "key": "name", "operator": "exact", "type": "span", "value": "redis_cluster.discovery" }],
+ "dateRange": { "date_from": "-6h" }
+ }
+}
+```
diff --git a/products/tracing/mcp/tools.yaml b/products/tracing/mcp/tools.yaml
index 67e1a025cc94..150535fb688a 100644
--- a/products/tracing/mcp/tools.yaml
+++ b/products/tracing/mcp/tools.yaml
@@ -87,6 +87,21 @@ tools:
include:
- results
- compare
+ apm-spans-count:
+ operation: tracing_spans_count_create
+ enabled: true
+ scopes:
+ - tracing:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Count spans
+ description_file: ./prompts/apm-spans-count.md
+ feature_flag: tracing
+ response:
+ include:
+ - count
apm-spans-tree:
operation: tracing_spans_tree_create
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 7c92bbd414b8..3db408d4ef1d 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -460,6 +460,21 @@
},
"feature_flag": "tracing"
},
+ "apm-spans-count": {
+ "description": "Return a scalar count of trace spans matching a filter set. Use this as a cheap pre-flight before `query-apm-spans` — if the count is large, narrow the filters (or set `excludeAttributes`) before pulling rows.\n\nAll parameters must be nested inside a `query` object.\n\n# When to use\n\n- Before `query-apm-spans`, to confirm the filter set returns a tractable number of spans rather than pulling rows blind.\n- When the user asks \"how many X spans are there?\" and you don't need to see individual spans.\n- To check whether a filter combination matches anything at all before committing to a full query.\n\nThis counts **spans**, not traces. A single trace contains many spans, so a count of matching spans will exceed the number of matching traces.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range for the count. 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.serviceNames\n\nFilter by service names. Unlike `query-apm-spans`, an unfiltered count is cheap and useful for sizing up a filter before narrowing. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by HTTP status codes (list of integers).\n\n## query.filterGroup\n\nProperty filters to narrow the count. Same format as `query-apm-spans` filters — each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`.\n\n# Examples\n\n## Count error spans in a service over the last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"statusCodes\": [500, 503],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Count how many spans match a name before fetching them\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"name\", \"operator\": \"exact\", \"type\": \"span\", \"value\": \"redis_cluster.discovery\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```",
+ "category": "Tracing",
+ "feature": "tracing",
+ "summary": "Count spans",
+ "title": "Count spans",
+ "required_scopes": ["tracing:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "tracing"
+ },
"apm-spans-tree": {
"description": "Aggregate trace span statistics as a call tree — one row per `(parent_service, parent_name) → (service_name, name)` edge.\n\nRequires a `spanName` to bound the matched trace set (the `(trace_id, parent_span_id)` self-join is unsafe at high cardinality without it), and a `serviceName` to scope the returned tree to a single service. All traces that contain at least one span with the given name in the given service are included, and every span in those traces from that service is aggregated against its parent.\n\nReturns rows with:\n\n- `parent_service`, `parent_name` — the parent span identity (`parent_name` is `\"<ROOT>\"` for root spans)\n- `service_name`, `name` — the child span identity\n- `count` — number of spans matched for this `(parent, child)` edge\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano` — duration stats in nanoseconds\n- `error_count` — child spans with OTel status code `Error` (status_code = 2)\n- `avg_start_offset_nano` — average nanoseconds from the parent span's start to this child's start\n\nRows are ordered by `total_duration_nano` DESC and capped at 5000.\n\nUse to answer:\n\n- \"What does the `/checkout` flow actually call downstream?\"\n- \"Which child operation under `POST /orders` is the slowest?\"\n- \"Where is time spent inside `process_payment` — DB, external API, or something else?\"\n- \"Did the call tree under `/api/feed` change between last week and this week?\" (with `compareFilter`)\n\nFor a flat per-operation view (no parent linkage), use `apm-spans-aggregate` instead.\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.\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\n`query.filterGroup` narrows the matched span set. Same filter shape and operators as `apm-spans-aggregate` / `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values.\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`).\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.spanName (required)\n\nThe span name that anchors the matched trace set. Every trace containing at least one span with this name (in the given `serviceName`) is included.\n\nPick a high-level entry-point span (e.g. an HTTP route or job name). Generic names (`HTTP`, `GET`) match too many traces and produce noisy aggregates. Use `query-apm-spans` first if you need to discover concrete span names.\n\n## query.serviceName (required)\n\nThe service the tree should be scoped to. Applied to the spans CTE so the returned rows only contain spans from this service, even when the matched traces also touch other services. Use `apm-services-list` to discover service names.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Same shape as in `apm-spans-aggregate`.\n\n## query.serviceNames\n\nList of service names to filter the matched span set. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters applied to both windows. See the \"Property filters\" section.\n\n# Examples\n\n## Call tree under a specific operation in the last hour\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\"\n }\n}\n```\n\n## Call tree over the last day\n\n```json\n{\n \"query\": {\n \"spanName\": \"checkout_flow\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Compare today's call tree vs last week\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Restrict to error-bearing traces\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }]\n }\n}\n```\n\n# Reminders\n\n- `spanName` and `serviceName` are both required. Bound `spanName` to a specific high-level span (avoid generic names like `HTTP`); set `serviceName` to the one service whose call-tree you want.\n- Root spans have `parent_name = \"<ROOT>\"` and `avg_start_offset_nano = 0`.\n- Duration values are in nanoseconds.\n- Results are ordered by `total_duration_nano` DESC and capped at 5000 rows.\n- For a flat per-operation aggregate without parent linkage, use `apm-spans-aggregate`.\n- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.",
"category": "Tracing",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 07bdfee69cba..6ff8e5aa3484 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -476,6 +476,21 @@
},
"feature_flag": "tracing"
},
+ "apm-spans-count": {
+ "description": "Return a scalar count of trace spans matching a filter set. Use this as a cheap pre-flight before `query-apm-spans` — if the count is large, narrow the filters (or set `excludeAttributes`) before pulling rows.\n\nAll parameters must be nested inside a `query` object.\n\n# When to use\n\n- Before `query-apm-spans`, to confirm the filter set returns a tractable number of spans rather than pulling rows blind.\n- When the user asks \"how many X spans are there?\" and you don't need to see individual spans.\n- To check whether a filter combination matches anything at all before committing to a full query.\n\nThis counts **spans**, not traces. A single trace contains many spans, so a count of matching spans will exceed the number of matching traces.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range for the count. 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.serviceNames\n\nFilter by service names. Unlike `query-apm-spans`, an unfiltered count is cheap and useful for sizing up a filter before narrowing. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by HTTP status codes (list of integers).\n\n## query.filterGroup\n\nProperty filters to narrow the count. Same format as `query-apm-spans` filters — each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`.\n\n# Examples\n\n## Count error spans in a service over the last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"statusCodes\": [500, 503],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Count how many spans match a name before fetching them\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"name\", \"operator\": \"exact\", \"type\": \"span\", \"value\": \"redis_cluster.discovery\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```",
+ "category": "Tracing",
+ "feature": "tracing",
+ "summary": "Count spans",
+ "title": "Count spans",
+ "required_scopes": ["tracing:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "tracing"
+ },
"apm-spans-tree": {
"description": "Aggregate trace span statistics as a call tree — one row per `(parent_service, parent_name) → (service_name, name)` edge.\n\nRequires a `spanName` to bound the matched trace set (the `(trace_id, parent_span_id)` self-join is unsafe at high cardinality without it), and a `serviceName` to scope the returned tree to a single service. All traces that contain at least one span with the given name in the given service are included, and every span in those traces from that service is aggregated against its parent.\n\nReturns rows with:\n\n- `parent_service`, `parent_name` — the parent span identity (`parent_name` is `\"<ROOT>\"` for root spans)\n- `service_name`, `name` — the child span identity\n- `count` — number of spans matched for this `(parent, child)` edge\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano` — duration stats in nanoseconds\n- `error_count` — child spans with OTel status code `Error` (status_code = 2)\n- `avg_start_offset_nano` — average nanoseconds from the parent span's start to this child's start\n\nRows are ordered by `total_duration_nano` DESC and capped at 5000.\n\nUse to answer:\n\n- \"What does the `/checkout` flow actually call downstream?\"\n- \"Which child operation under `POST /orders` is the slowest?\"\n- \"Where is time spent inside `process_payment` — DB, external API, or something else?\"\n- \"Did the call tree under `/api/feed` change between last week and this week?\" (with `compareFilter`)\n\nFor a flat per-operation view (no parent linkage), use `apm-spans-aggregate` instead.\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.\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\n`query.filterGroup` narrows the matched span set. Same filter shape and operators as `apm-spans-aggregate` / `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values.\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`).\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.spanName (required)\n\nThe span name that anchors the matched trace set. Every trace containing at least one span with this name (in the given `serviceName`) is included.\n\nPick a high-level entry-point span (e.g. an HTTP route or job name). Generic names (`HTTP`, `GET`) match too many traces and produce noisy aggregates. Use `query-apm-spans` first if you need to discover concrete span names.\n\n## query.serviceName (required)\n\nThe service the tree should be scoped to. Applied to the spans CTE so the returned rows only contain spans from this service, even when the matched traces also touch other services. Use `apm-services-list` to discover service names.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Same shape as in `apm-spans-aggregate`.\n\n## query.serviceNames\n\nList of service names to filter the matched span set. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters applied to both windows. See the \"Property filters\" section.\n\n# Examples\n\n## Call tree under a specific operation in the last hour\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\"\n }\n}\n```\n\n## Call tree over the last day\n\n```json\n{\n \"query\": {\n \"spanName\": \"checkout_flow\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Compare today's call tree vs last week\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Restrict to error-bearing traces\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }]\n }\n}\n```\n\n# Reminders\n\n- `spanName` and `serviceName` are both required. Bound `spanName` to a specific high-level span (avoid generic names like `HTTP`); set `serviceName` to the one service whose call-tree you want.\n- Root spans have `parent_name = \"<ROOT>\"` and `avg_start_offset_nano = 0`.\n- Duration values are in nanoseconds.\n- Results are ordered by `total_duration_nano` DESC and capped at 5000 rows.\n- For a flat per-operation aggregate without parent linkage, use `apm-spans-aggregate`.\n- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.",
"category": "Tracing",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index fe8951348deb..3d5ddde1ab6c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -41603,6 +41603,27 @@ export namespace Schemas {
query: _TracingAggregationQueryBody;
}
+ export interface _TracingCountBody {
+ /** Date range for the count. Defaults to last hour. */
+ dateRange?: _TracingDateRange;
+ /** Filter by service names. */
+ serviceNames?: string[];
+ /** Filter by HTTP status codes. */
+ statusCodes?: number[];
+ /** Property filters for the count. */
+ filterGroup?: _SpanPropertyFilter[];
+ }
+
+ export interface _TracingCountRequest {
+ /** The span count query to execute. */
+ query: _TracingCountBody;
+ }
+
+ export interface _TracingCountResponse {
+ /** Number of spans matching the filters. */
+ count: number;
+ }
+
export interface _TracingQueryBody {
/** Date range for the query. Defaults to last hour. */
dateRange?: _TracingDateRange;
diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.ts
index 7a038575182b..4955e148d548 100644
--- a/services/mcp/src/generated/tracing/api.ts
+++ b/services/mcp/src/generated/tracing/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 7 enabled ops
+ * PostHog API - MCP 8 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -139,6 +139,85 @@ export const TracingSpansAttributesRetrieveQueryParams = /* @__PURE__ */ zod.obj
search: zod.string().min(1).optional().describe('Search filter for attribute names.'),
})
+export const TracingSpansCountCreateParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const tracingSpansCountCreateBodyQueryOneFilterGroupDefault = []
+
+export const TracingSpansCountCreateBody = /* @__PURE__ */ zod.object({
+ query: zod
+ .object({
+ dateRange: zod
+ .object({
+ date_from: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Start of the date range. Accepts ISO 8601 timestamps or relative formats: -1h, -6h, -1d, -7d, etc.'
+ ),
+ date_to: zod
+ .string()
+ .nullish()
+ .describe('End of the date range. Same format as date_from. Omit or null for "now".'),
+ })
+ .optional()
+ .describe('Date range for the count. Defaults to last hour.'),
+ serviceNames: zod.array(zod.string()).optional().describe('Filter by service names.'),
+ statusCodes: zod.array(zod.number()).optional().describe('Filter by HTTP status codes.'),
+ filterGroup: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .describe(
+ 'Attribute key. For type "span", use built-in fields (trace_id, span_id, duration, name, kind, status_code). For "span_attribute"/"span_resource_attribute", use the attribute key (e.g. "http.method").'
+ ),
+ type: zod
+ .enum(['span', 'span_attribute', 'span_resource_attribute'])
+ .describe(
+ '* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute'
+ )
+ .describe(
+ '"span" filters built-in span fields. "span_attribute" filters span-level attributes. "span_resource_attribute" filters resource-level attributes.\n\n* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute'
+ ),
+ operator: zod
+ .enum([
+ 'exact',
+ 'is_not',
+ 'icontains',
+ 'not_icontains',
+ 'regex',
+ 'not_regex',
+ 'gt',
+ 'lt',
+ 'is_set',
+ 'is_not_set',
+ ])
+ .describe(
+ '* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `is_set` - is_set\n* `is_not_set` - is_not_set'
+ )
+ .describe(
+ 'Comparison operator.\n\n* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `is_set` - is_set\n* `is_not_set` - is_not_set'
+ ),
+ value: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators.'
+ ),
+ })
+ )
+ .default(tracingSpansCountCreateBodyQueryOneFilterGroupDefault)
+ .describe('Property filters for the count.'),
+ })
+ .describe('The span count query to execute.'),
+})
+
export const TracingSpansQueryCreateParams = /* @__PURE__ */ zod.object({
project_id: zod
.string()
diff --git a/services/mcp/src/tools/generated/tracing.ts b/services/mcp/src/tools/generated/tracing.ts
index 5b21e732f190..b079eb42e540 100644
--- a/services/mcp/src/tools/generated/tracing.ts
+++ b/services/mcp/src/tools/generated/tracing.ts
@@ -1,9 +1,11 @@
// AUTO-GENERATED from products/tracing/mcp/tools.yaml + OpenAPI — do not edit
import { z } from 'zod'
+import type { Schemas } from '@/api/generated'
import {
TracingSpansAggregateCreateBody,
TracingSpansAttributesRetrieveQueryParams,
+ TracingSpansCountCreateBody,
TracingSpansQueryCreateBody,
TracingSpansServiceNamesRetrieveQueryParams,
TracingSpansTraceCreateBody,
@@ -101,6 +103,27 @@ const apmSpansAggregate = (): ToolBase<typeof ApmSpansAggregateSchema, unknown>
},
})
+const ApmSpansCountSchema = TracingSpansCountCreateBody
+
+const apmSpansCount = (): ToolBase<typeof ApmSpansCountSchema, Schemas._TracingCountResponse> => ({
+ name: 'apm-spans-count',
+ schema: ApmSpansCountSchema,
+ handler: async (context: Context, params: z.infer<typeof ApmSpansCountSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.query !== undefined) {
+ body['query'] = params.query
+ }
+ const result = await context.api.request<Schemas._TracingCountResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/tracing/spans/count/`,
+ body,
+ })
+ const filtered = pickResponseFields(result, ['count']) as typeof result
+ return filtered
+ },
+})
+
const ApmSpansTreeSchema = TracingSpansTreeCreateBody
const apmSpansTree = (): ToolBase<typeof ApmSpansTreeSchema, unknown> => ({
@@ -176,6 +199,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'apm-attributes-list': apmAttributesList,
'apm-services-list': apmServicesList,
'apm-spans-aggregate': apmSpansAggregate,
+ 'apm-spans-count': apmSpansCount,
'apm-spans-tree': apmSpansTree,
'apm-trace-get': apmTraceGet,
'query-apm-spans': queryApmSpans,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-count.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-count.json
new file mode 100644
index 000000000000..214692c147c3
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-count.json
@@ -0,0 +1,94 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "query": {
+ "description": "The span count query to execute.",
+ "properties": {
+ "dateRange": {
+ "description": "Date range for the count. Defaults to last hour.",
+ "properties": {
+ "date_from": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Start of the date range. Accepts ISO 8601 timestamps or relative formats: -1h, -6h, -1d, -7d, etc."
+ },
+ "date_to": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "End of the date range. Same format as date_from. Omit or null for \"now\"."
+ }
+ },
+ "type": "object"
+ },
+ "filterGroup": {
+ "default": [],
+ "description": "Property filters for the count.",
+ "items": {
+ "properties": {
+ "key": {
+ "description": "Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code). For \"span_attribute\"/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").",
+ "type": "string"
+ },
+ "operator": {
+ "description": "Comparison operator.\n\n* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `is_set` - is_set\n* `is_not_set` - is_not_set",
+ "enum": [
+ "exact",
+ "is_not",
+ "icontains",
+ "not_icontains",
+ "regex",
+ "not_regex",
+ "gt",
+ "lt",
+ "is_set",
+ "is_not_set"
+ ],
+ "type": "string"
+ },
+ "type": {
+ "description": "\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n* `span` - span\n* `span_attribute` - span_attribute\n* `span_resource_attribute` - span_resource_attribute",
+ "enum": ["span", "span_attribute", "span_resource_attribute"],
+ "type": "string"
+ },
+ "value": {
+ "description": "Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators."
+ }
+ },
+ "required": ["key", "type", "operator"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "serviceNames": {
+ "description": "Filter by service names.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "statusCodes": {
+ "description": "Filter by HTTP status codes.",
+ "items": {
+ "type": "number"
+ },
+ "type": "array"
+ }
+ },
+ "type": "object"
+ }
+ },
+ "required": ["query"],
+ "type": "object"
+}