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.

chore(tracing): declare the response schemas the frontend reads (#104380)

Julian Bez9995745deb15
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index bd5013fa0684..a787d9774ff8 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -759,6 +759,141 @@ class _TracingTreeRequestSerializer(serializers.Serializer):
query = _TracingTreeQueryBodySerializer(help_text="The span call-tree aggregation query to execute.")
+class _SpanSerializer(serializers.Serializer):
+ """One span row as the query and trace actions return it.
+
+ The runner assembles these from HogQL result columns by position, so the key set is fixed even
+ though the values come from a query. `trace_start` and `trace_duration` are the sort keys the
+ trace list orders on, carried in the row rather than recomputed by the caller.
+ """
+
+ uuid = serializers.CharField(help_text="Span's own UUID.")
+ trace_id = serializers.CharField(help_text="Trace this span belongs to.")
+ span_id = serializers.CharField(help_text="Span's ID within the trace.")
+ parent_span_id = serializers.CharField(help_text="Parent span's ID. Empty for a root span.")
+ name = serializers.CharField(help_text="Span name, which is the operation it represents.")
+ kind = serializers.IntegerField(help_text="OpenTelemetry span kind.")
+ service_name = serializers.CharField(help_text="Service that emitted the span.")
+ status_code = serializers.IntegerField(help_text="OpenTelemetry status code: 0 unset, 1 ok, 2 error.")
+ timestamp = serializers.DateTimeField(help_text="When the span started.")
+ end_time = serializers.DateTimeField(help_text="When the span ended.")
+ duration_nano = serializers.FloatField(help_text="Span duration in nanoseconds.")
+ is_root_span = serializers.BooleanField(help_text="Whether the span has no parent in the trace.")
+ matched_filter = serializers.IntegerField(
+ help_text=(
+ "1 when this span matched the request's filters, 0 when it is included as context. The query "
+ "selects it as an expression, so it arrives as a number rather than a boolean."
+ )
+ )
+ trace_start = serializers.DateTimeField(help_text="Start of the whole trace, for ordering traces by recency.")
+ trace_duration = serializers.FloatField(
+ help_text="Duration of the whole trace in nanoseconds. Falls back to this span's duration."
+ )
+ attributes = serializers.DictField(
+ child=serializers.CharField(),
+ help_text="Span attributes. Keys are whatever the instrumentation set.",
+ )
+ resource_attributes = serializers.DictField(
+ child=serializers.CharField(),
+ help_text="Resource attributes of the emitting service. Keys are whatever the instrumentation set.",
+ )
+
+
+class _TraceSpanSerializer(_SpanSerializer):
+ """A span in a single trace. The trace action adds self time, which the list does not compute."""
+
+ self_time_nano = serializers.FloatField(
+ help_text="Span duration minus the time spent in its children, in nanoseconds."
+ )
+
+
+class _TracingQueryResponseSerializer(serializers.Serializer):
+ results = _SpanSerializer(many=True, help_text="Matching spans, ordered by the requested column.")
+ hasMore = serializers.BooleanField(help_text="Whether a further page exists.")
+ nextCursor = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "Cursor for the next page, or null on the last page. Pass it back as the query's `after`. "
+ "Always null when ordering by duration, which pages by offset instead."
+ ),
+ )
+
+
+class _TracingTraceResponseSerializer(serializers.Serializer):
+ results = _TraceSpanSerializer(many=True, help_text="Spans in the trace, earliest first.")
+ hasMore = serializers.BooleanField(help_text="Whether a further page of spans exists.")
+ nextOffset = serializers.IntegerField(
+ allow_null=True, help_text="Offset for the next page, or null on the last page."
+ )
+
+
+class _TracingSparklineRowSerializer(serializers.Serializer):
+ time = serializers.DateTimeField(help_text="Start of the time bucket.")
+ service = serializers.CharField(help_text="Service the count belongs to.")
+ count = serializers.IntegerField(help_text="Spans in this bucket for this service.")
+
+
+class _TracingSparklineResponseSerializer(serializers.Serializer):
+ results = _TracingSparklineRowSerializer(
+ many=True, help_text="One row per time bucket and service, ordered by time."
+ )
+
+
+class _TracingDurationHistogramRowSerializer(serializers.Serializer):
+ bucket_ns = serializers.IntegerField(help_text="Lower bound of the duration bucket in nanoseconds.")
+ service = serializers.CharField(help_text="Service the count belongs to.")
+ count = serializers.IntegerField(help_text="Spans in this bucket for this service.")
+
+
+class _TracingDurationHistogramResponseSerializer(serializers.Serializer):
+ results = _TracingDurationHistogramRowSerializer(many=True, help_text="One row per duration bucket and service.")
+
+
+class _SpanTreeNodeSerializer(serializers.Serializer):
+ """One node of the aggregated call tree. Mirrors `SpanTreeNode` in posthog.schema."""
+
+ name = serializers.CharField(help_text="Span name for this node.")
+ service_name = serializers.CharField(help_text="Service that emitted the spans.")
+ parent_name = serializers.CharField(
+ help_text="Parent node's span name. The literal `<ROOT>` for a root node, which is how a client finds the roots."
+ )
+ parent_service = serializers.CharField(help_text="Parent node's service. Empty string at the root.")
+ count = serializers.IntegerField(help_text="Spans aggregated into this node.")
+ error_count = serializers.IntegerField(help_text="How many of them reported an error status.")
+ total_duration_nano = serializers.FloatField(help_text="Sum of durations in nanoseconds.")
+ avg_duration_nano = serializers.FloatField(help_text="Mean duration in nanoseconds.")
+ p50_duration_nano = serializers.FloatField(help_text="Median duration in nanoseconds.")
+ p95_duration_nano = serializers.FloatField(help_text="95th percentile duration in nanoseconds.")
+ p99_duration_nano = serializers.FloatField(help_text="99th percentile duration in nanoseconds.")
+ p999_duration_nano = serializers.FloatField(help_text="99.9th percentile duration in nanoseconds.")
+ avg_start_offset_nano = serializers.FloatField(
+ help_text="Mean nanoseconds from the parent's start to this node's start. Zero at the root."
+ )
+ calls_per_parent_invocation = serializers.FloatField(
+ allow_null=True, help_text="Mean calls per parent invocation. Null at the root."
+ )
+
+
+class _TracingTreeResponseSerializer(serializers.Serializer):
+ results = _SpanTreeNodeSerializer(many=True, help_text="Call tree nodes for the requested window.")
+ compare = _SpanTreeNodeSerializer(
+ many=True,
+ allow_null=True,
+ help_text=(
+ "Nodes for the comparison window when compareFilter.compare is true. Null when no comparison "
+ "was requested, and an empty list when one was requested and matched no spans."
+ ),
+ )
+
+
+class _TracingServiceNameSerializer(serializers.Serializer):
+ name = serializers.CharField(help_text="Service name.")
+
+
+class _TracingServiceNamesResponseSerializer(serializers.Serializer):
+ results = _TracingServiceNameSerializer(many=True, help_text="Services that emitted spans in the window.")
+
+
class _HasSpansResponseSerializer(serializers.Serializer):
hasSpans = serializers.BooleanField(
help_text="Whether the team has ingested any tracing spans yet. Used to gate the onboarding empty state."
@@ -1058,7 +1193,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
)
return Response(response.data, status=status.HTTP_200_OK)
- @extend_schema(parameters=[_TracingServiceNamesQuerySerializer])
+ @extend_schema(
+ parameters=[_TracingServiceNamesQuerySerializer],
+ responses={200: _TracingServiceNamesResponseSerializer},
+ )
@action(detail=False, methods=["GET"], url_path="service-names", required_scopes=["tracing:read"])
def service_names(self, request: Request, *args, **kwargs) -> Response:
tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
@@ -1088,7 +1226,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
return Response({"hasSpans": has_spans}, status=status.HTTP_200_OK)
- @extend_schema(request=_TracingQueryRequestSerializer)
+ @extend_schema(
+ request=_TracingQueryRequestSerializer,
+ responses={200: _TracingQueryResponseSerializer},
+ )
@action(detail=False, methods=["POST"], required_scopes=["tracing:read"])
def query(self, request: Request, *args, **kwargs) -> Response:
tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
@@ -1341,7 +1482,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
status=status.HTTP_200_OK,
)
- @extend_schema(request=_TracingSparklineRequestSerializer)
+ @extend_schema(
+ request=_TracingSparklineRequestSerializer,
+ responses={200: _TracingSparklineResponseSerializer},
+ )
@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)
@@ -1371,7 +1515,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
return Response({"results": response.results}, status=status.HTTP_200_OK)
- @extend_schema(request=_TracingDurationHistogramRequestSerializer)
+ @extend_schema(
+ request=_TracingDurationHistogramRequestSerializer,
+ responses={200: _TracingDurationHistogramResponseSerializer},
+ )
@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)
@@ -1509,7 +1656,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
status=status.HTTP_200_OK,
)
- @extend_schema(request=_TracingTreeRequestSerializer)
+ @extend_schema(
+ request=_TracingTreeRequestSerializer,
+ responses={200: _TracingTreeResponseSerializer},
+ )
@action(detail=False, methods=["POST"], url_path="tree", required_scopes=["tracing:read"])
def tree(self, request: Request, *args, **kwargs) -> Response:
tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
@@ -1633,7 +1783,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
status=status.HTTP_200_OK,
)
- @extend_schema(request=_TracingTraceRequestSerializer)
+ @extend_schema(
+ request=_TracingTraceRequestSerializer,
+ responses={200: _TracingTraceResponseSerializer},
+ )
@action(
detail=False, methods=["POST"], url_path="trace/(?P<trace_id>[a-zA-Z0-9]+)", required_scopes=["tracing:read"]
)
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index 6274aa40f407..e7f6d1ac7430 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -389,6 +389,20 @@ export interface _TracingDurationHistogramRequestApi {
query: _TracingDurationHistogramQueryBodyApi
}
+export interface _TracingDurationHistogramRowApi {
+ /** Lower bound of the duration bucket in nanoseconds. */
+ bucket_ns: number
+ /** Service the count belongs to. */
+ service: string
+ /** Spans in this bucket for this service. */
+ count: number
+}
+
+export interface _TracingDurationHistogramResponseApi {
+ /** One row per duration bucket and service. */
+ results: _TracingDurationHistogramRowApi[]
+}
+
export interface _TracingErrorCountsRequestApi {
/**
* Hex trace IDs to count exceptions for, matched against the exception's `$trace_id` property. Case insensitive. At most 200 per request.
@@ -562,6 +576,82 @@ export interface _TracingQueryRequestApi {
query: _TracingQueryBodyApi
}
+/**
+ * Span attributes. Keys are whatever the instrumentation set.
+ */
+export type _SpanApiAttributes = { [key: string]: string }
+
+/**
+ * Resource attributes of the emitting service. Keys are whatever the instrumentation set.
+ */
+export type _SpanApiResourceAttributes = { [key: string]: string }
+
+/**
+ * One span row as the query and trace actions return it.
+ *
+ * The runner assembles these from HogQL result columns by position, so the key set is fixed even
+ * though the values come from a query. `trace_start` and `trace_duration` are the sort keys the
+ * trace list orders on, carried in the row rather than recomputed by the caller.
+ */
+export interface _SpanApi {
+ /** Span's own UUID. */
+ uuid: string
+ /** Trace this span belongs to. */
+ trace_id: string
+ /** Span's ID within the trace. */
+ span_id: string
+ /** Parent span's ID. Empty for a root span. */
+ parent_span_id: string
+ /** Span name, which is the operation it represents. */
+ name: string
+ /** OpenTelemetry span kind. */
+ kind: number
+ /** Service that emitted the span. */
+ service_name: string
+ /** OpenTelemetry status code: 0 unset, 1 ok, 2 error. */
+ status_code: number
+ /** When the span started. */
+ timestamp: string
+ /** When the span ended. */
+ end_time: string
+ /** Span duration in nanoseconds. */
+ duration_nano: number
+ /** Whether the span has no parent in the trace. */
+ is_root_span: boolean
+ /** 1 when this span matched the request's filters, 0 when it is included as context. The query selects it as an expression, so it arrives as a number rather than a boolean. */
+ matched_filter: number
+ /** Start of the whole trace, for ordering traces by recency. */
+ trace_start: string
+ /** Duration of the whole trace in nanoseconds. Falls back to this span's duration. */
+ trace_duration: number
+ /** Span attributes. Keys are whatever the instrumentation set. */
+ attributes: _SpanApiAttributes
+ /** Resource attributes of the emitting service. Keys are whatever the instrumentation set. */
+ resource_attributes: _SpanApiResourceAttributes
+}
+
+export interface _TracingQueryResponseApi {
+ /** Matching spans, ordered by the requested column. */
+ results: _SpanApi[]
+ /** Whether a further page exists. */
+ hasMore: boolean
+ /**
+ * Cursor for the next page, or null on the last page. Pass it back as the query's `after`. Always null when ordering by duration, which pages by offset instead.
+ * @nullable
+ */
+ nextCursor: string | null
+}
+
+export interface _TracingServiceNameApi {
+ /** Service name. */
+ name: string
+}
+
+export interface _TracingServiceNamesResponseApi {
+ /** Services that emitted spans in the window. */
+ results: _TracingServiceNameApi[]
+}
+
export interface _TracingSparklineQueryBodyApi {
/** Date range for the query. Defaults to last hour. */
dateRange?: _TracingDateRangeApi
@@ -580,6 +670,20 @@ export interface _TracingSparklineRequestApi {
query: _TracingSparklineQueryBodyApi
}
+export interface _TracingSparklineRowApi {
+ /** Start of the time bucket. */
+ time: string
+ /** Service the count belongs to. */
+ service: string
+ /** Spans in this bucket for this service. */
+ count: number
+}
+
+export interface _TracingSparklineResponseApi {
+ /** One row per time bucket and service, ordered by time. */
+ results: _TracingSparklineRowApi[]
+}
+
export interface _SymbolStatsSymbolApi {
/**
* Opaque identifier (e.g. the function name) echoed back on the matching result row.
@@ -715,6 +819,70 @@ export interface _TracingTraceRequestApi {
offset?: number
}
+/**
+ * Span attributes. Keys are whatever the instrumentation set.
+ */
+export type _TraceSpanApiAttributes = { [key: string]: string }
+
+/**
+ * Resource attributes of the emitting service. Keys are whatever the instrumentation set.
+ */
+export type _TraceSpanApiResourceAttributes = { [key: string]: string }
+
+/**
+ * A span in a single trace. The trace action adds self time, which the list does not compute.
+ */
+export interface _TraceSpanApi {
+ /** Span's own UUID. */
+ uuid: string
+ /** Trace this span belongs to. */
+ trace_id: string
+ /** Span's ID within the trace. */
+ span_id: string
+ /** Parent span's ID. Empty for a root span. */
+ parent_span_id: string
+ /** Span name, which is the operation it represents. */
+ name: string
+ /** OpenTelemetry span kind. */
+ kind: number
+ /** Service that emitted the span. */
+ service_name: string
+ /** OpenTelemetry status code: 0 unset, 1 ok, 2 error. */
+ status_code: number
+ /** When the span started. */
+ timestamp: string
+ /** When the span ended. */
+ end_time: string
+ /** Span duration in nanoseconds. */
+ duration_nano: number
+ /** Whether the span has no parent in the trace. */
+ is_root_span: boolean
+ /** 1 when this span matched the request's filters, 0 when it is included as context. The query selects it as an expression, so it arrives as a number rather than a boolean. */
+ matched_filter: number
+ /** Start of the whole trace, for ordering traces by recency. */
+ trace_start: string
+ /** Duration of the whole trace in nanoseconds. Falls back to this span's duration. */
+ trace_duration: number
+ /** Span attributes. Keys are whatever the instrumentation set. */
+ attributes: _TraceSpanApiAttributes
+ /** Resource attributes of the emitting service. Keys are whatever the instrumentation set. */
+ resource_attributes: _TraceSpanApiResourceAttributes
+ /** Span duration minus the time spent in its children, in nanoseconds. */
+ self_time_nano: number
+}
+
+export interface _TracingTraceResponseApi {
+ /** Spans in the trace, earliest first. */
+ results: _TraceSpanApi[]
+ /** Whether a further page of spans exists. */
+ hasMore: boolean
+ /**
+ * Offset for the next page, or null on the last page.
+ * @nullable
+ */
+ nextOffset: number | null
+}
+
export interface _TracingTreeQueryBodyApi {
/** Span name to scope the matched trace set. Required because the (trace_id, parent_span_id) self-join is unsafe without bounding the matched traces. */
spanName: string
@@ -735,6 +903,53 @@ export interface _TracingTreeRequestApi {
query: _TracingTreeQueryBodyApi
}
+/**
+ * One node of the aggregated call tree. Mirrors `SpanTreeNode` in posthog.schema.
+ */
+export interface _SpanTreeNodeApi {
+ /** Span name for this node. */
+ name: string
+ /** Service that emitted the spans. */
+ service_name: string
+ /** Parent node's span name. The literal `<ROOT>` for a root node, which is how a client finds the roots. */
+ parent_name: string
+ /** Parent node's service. Empty string at the root. */
+ parent_service: string
+ /** Spans aggregated into this node. */
+ count: number
+ /** How many of them reported an error status. */
+ error_count: number
+ /** Sum of durations in nanoseconds. */
+ total_duration_nano: number
+ /** Mean duration in nanoseconds. */
+ avg_duration_nano: number
+ /** Median duration in nanoseconds. */
+ p50_duration_nano: number
+ /** 95th percentile duration in nanoseconds. */
+ p95_duration_nano: number
+ /** 99th percentile duration in nanoseconds. */
+ p99_duration_nano: number
+ /** 99.9th percentile duration in nanoseconds. */
+ p999_duration_nano: number
+ /** Mean nanoseconds from the parent's start to this node's start. Zero at the root. */
+ avg_start_offset_nano: number
+ /**
+ * Mean calls per parent invocation. Null at the root.
+ * @nullable
+ */
+ calls_per_parent_invocation: number | null
+}
+
+export interface _TracingTreeResponseApi {
+ /** Call tree nodes for the requested window. */
+ results: _SpanTreeNodeApi[]
+ /**
+ * Nodes for the comparison window when compareFilter.compare is true. Null when no comparison was requested, and an empty list when one was requested and matched no spans.
+ * @nullable
+ */
+ compare: _SpanTreeNodeApi[] | null
+}
+
/**
* * `engineering` - Engineering
* * `data` - Data
diff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.ts
index 87eeb2a5d650..02d94183f75d 100644
--- a/products/tracing/frontend/generated/api.ts
+++ b/products/tracing/frontend/generated/api.ts
@@ -29,6 +29,7 @@ import type {
_TracingCountRequestApi,
_TracingCountResponseApi,
_TracingDurationHistogramRequestApi,
+ _TracingDurationHistogramResponseApi,
_TracingErrorCountsRequestApi,
_TracingErrorCountsResponseApi,
_TracingImpactRequestApi,
@@ -36,9 +37,14 @@ import type {
_TracingLatencyHeatmapRequestApi,
_TracingLatencyHeatmapResponseApi,
_TracingQueryRequestApi,
+ _TracingQueryResponseApi,
+ _TracingServiceNamesResponseApi,
_TracingSparklineRequestApi,
+ _TracingSparklineResponseApi,
_TracingTraceRequestApi,
+ _TracingTraceResponseApi,
_TracingTreeRequestApi,
+ _TracingTreeResponseApi,
} from './api.schemas'
// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
@@ -192,8 +198,8 @@ export const tracingSpansDurationHistogramCreate = async (
projectId: string,
_tracingDurationHistogramRequestApi: _TracingDurationHistogramRequestApi,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getTracingSpansDurationHistogramCreateUrl(projectId), {
+): Promise<_TracingDurationHistogramResponseApi> => {
+ return apiMutator<_TracingDurationHistogramResponseApi>(getTracingSpansDurationHistogramCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -280,8 +286,8 @@ export const tracingSpansQueryCreate = async (
projectId: string,
_tracingQueryRequestApi: _TracingQueryRequestApi,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getTracingSpansQueryCreateUrl(projectId), {
+): Promise<_TracingQueryResponseApi> => {
+ return apiMutator<_TracingQueryResponseApi>(getTracingSpansQueryCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -312,8 +318,8 @@ export const tracingSpansServiceNamesRetrieve = async (
projectId: string,
params?: TracingSpansServiceNamesRetrieveParams,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getTracingSpansServiceNamesRetrieveUrl(projectId, params), {
+): Promise<_TracingServiceNamesResponseApi> => {
+ return apiMutator<_TracingServiceNamesResponseApi>(getTracingSpansServiceNamesRetrieveUrl(projectId, params), {
...options,
method: 'GET',
})
@@ -327,8 +333,8 @@ export const tracingSpansSparklineCreate = async (
projectId: string,
_tracingSparklineRequestApi: _TracingSparklineRequestApi,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getTracingSpansSparklineCreateUrl(projectId), {
+): Promise<_TracingSparklineResponseApi> => {
+ return apiMutator<_TracingSparklineResponseApi>(getTracingSpansSparklineCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -362,8 +368,8 @@ export const tracingSpansTraceCreate = async (
traceId: string,
_tracingTraceRequestApi?: _TracingTraceRequestApi,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getTracingSpansTraceCreateUrl(projectId, traceId), {
+): Promise<_TracingTraceResponseApi> => {
+ return apiMutator<_TracingTraceResponseApi>(getTracingSpansTraceCreateUrl(projectId, traceId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -379,8 +385,8 @@ export const tracingSpansTreeCreate = async (
projectId: string,
_tracingTreeRequestApi: _TracingTreeRequestApi,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getTracingSpansTreeCreateUrl(projectId), {
+): Promise<_TracingTreeResponseApi> => {
+ return apiMutator<_TracingTreeResponseApi>(getTracingSpansTreeCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bf66516d9c80..6d947db7cf39 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -101023,6 +101023,60 @@ export namespace Schemas {
services: _MetricsOverviewService[];
}
+ /**
+ * Span attributes. Keys are whatever the instrumentation set.
+ */
+ export type _SpanAttributes = {[key: string]: string};
+
+ /**
+ * Resource attributes of the emitting service. Keys are whatever the instrumentation set.
+ */
+ export type _SpanResourceAttributes = {[key: string]: string};
+
+ /**
+ * One span row as the query and trace actions return it.
+ *
+ * The runner assembles these from HogQL result columns by position, so the key set is fixed even
+ * though the values come from a query. `trace_start` and `trace_duration` are the sort keys the
+ * trace list orders on, carried in the row rather than recomputed by the caller.
+ */
+ export interface _Span {
+ /** Span's own UUID. */
+ uuid: string;
+ /** Trace this span belongs to. */
+ trace_id: string;
+ /** Span's ID within the trace. */
+ span_id: string;
+ /** Parent span's ID. Empty for a root span. */
+ parent_span_id: string;
+ /** Span name, which is the operation it represents. */
+ name: string;
+ /** OpenTelemetry span kind. */
+ kind: number;
+ /** Service that emitted the span. */
+ service_name: string;
+ /** OpenTelemetry status code: 0 unset, 1 ok, 2 error. */
+ status_code: number;
+ /** When the span started. */
+ timestamp: string;
+ /** When the span ended. */
+ end_time: string;
+ /** Span duration in nanoseconds. */
+ duration_nano: number;
+ /** Whether the span has no parent in the trace. */
+ is_root_span: boolean;
+ /** 1 when this span matched the request's filters, 0 when it is included as context. The query selects it as an expression, so it arrives as a number rather than a boolean. */
+ matched_filter: number;
+ /** Start of the whole trace, for ordering traces by recency. */
+ trace_start: string;
+ /** Duration of the whole trace in nanoseconds. Falls back to this span's duration. */
+ trace_duration: number;
+ /** Span attributes. Keys are whatever the instrumentation set. */
+ attributes: _SpanAttributes;
+ /** Resource attributes of the emitting service. Keys are whatever the instrumentation set. */
+ resource_attributes: _SpanResourceAttributes;
+ }
+
/**
* * `exact` - exact
* * `is_not` - is_not
@@ -101089,6 +101143,43 @@ export namespace Schemas {
value?: unknown;
}
+ /**
+ * One node of the aggregated call tree. Mirrors `SpanTreeNode` in posthog.schema.
+ */
+ export interface _SpanTreeNode {
+ /** Span name for this node. */
+ name: string;
+ /** Service that emitted the spans. */
+ service_name: string;
+ /** Parent node's span name. The literal `<ROOT>` for a root node, which is how a client finds the roots. */
+ parent_name: string;
+ /** Parent node's service. Empty string at the root. */
+ parent_service: string;
+ /** Spans aggregated into this node. */
+ count: number;
+ /** How many of them reported an error status. */
+ error_count: number;
+ /** Sum of durations in nanoseconds. */
+ total_duration_nano: number;
+ /** Mean duration in nanoseconds. */
+ avg_duration_nano: number;
+ /** Median duration in nanoseconds. */
+ p50_duration_nano: number;
+ /** 95th percentile duration in nanoseconds. */
+ p95_duration_nano: number;
+ /** 99th percentile duration in nanoseconds. */
+ p99_duration_nano: number;
+ /** 99.9th percentile duration in nanoseconds. */
+ p999_duration_nano: number;
+ /** Mean nanoseconds from the parent's start to this node's start. Zero at the root. */
+ avg_start_offset_nano: number;
+ /**
+ * Mean calls per parent invocation. Null at the root.
+ * @nullable
+ */
+ calls_per_parent_invocation: number | null;
+ }
+
export interface _SymbolSetDownloadResponse {
/** Presigned URL to download the source map file. Use immediately; expires after one hour. */
url: string;
@@ -101219,6 +101310,58 @@ export namespace Schemas {
granularity: GranularityEnum;
}
+ /**
+ * Span attributes. Keys are whatever the instrumentation set.
+ */
+ export type _TraceSpanAttributes = {[key: string]: string};
+
+ /**
+ * Resource attributes of the emitting service. Keys are whatever the instrumentation set.
+ */
+ export type _TraceSpanResourceAttributes = {[key: string]: string};
+
+ /**
+ * A span in a single trace. The trace action adds self time, which the list does not compute.
+ */
+ export interface _TraceSpan {
+ /** Span's own UUID. */
+ uuid: string;
+ /** Trace this span belongs to. */
+ trace_id: string;
+ /** Span's ID within the trace. */
+ span_id: string;
+ /** Parent span's ID. Empty for a root span. */
+ parent_span_id: string;
+ /** Span name, which is the operation it represents. */
+ name: string;
+ /** OpenTelemetry span kind. */
+ kind: number;
+ /** Service that emitted the span. */
+ service_name: string;
+ /** OpenTelemetry status code: 0 unset, 1 ok, 2 error. */
+ status_code: number;
+ /** When the span started. */
+ timestamp: string;
+ /** When the span ended. */
+ end_time: string;
+ /** Span duration in nanoseconds. */
+ duration_nano: number;
+ /** Whether the span has no parent in the trace. */
+ is_root_span: boolean;
+ /** 1 when this span matched the request's filters, 0 when it is included as context. The query selects it as an expression, so it arrives as a number rather than a boolean. */
+ matched_filter: number;
+ /** Start of the whole trace, for ordering traces by recency. */
+ trace_start: string;
+ /** Duration of the whole trace in nanoseconds. Falls back to this span's duration. */
+ trace_duration: number;
+ /** Span attributes. Keys are whatever the instrumentation set. */
+ attributes: _TraceSpanAttributes;
+ /** Resource attributes of the emitting service. Keys are whatever the instrumentation set. */
+ resource_attributes: _TraceSpanResourceAttributes;
+ /** Span duration minus the time spent in its children, in nanoseconds. */
+ self_time_nano: number;
+ }
+
export interface _TracingAggregationQueryBody {
/** Date range for the primary window. Defaults to last hour. */
dateRange?: _TracingDateRange;
@@ -101413,6 +101556,20 @@ export namespace Schemas {
query: _TracingDurationHistogramQueryBody;
}
+ export interface _TracingDurationHistogramRow {
+ /** Lower bound of the duration bucket in nanoseconds. */
+ bucket_ns: number;
+ /** Service the count belongs to. */
+ service: string;
+ /** Spans in this bucket for this service. */
+ count: number;
+ }
+
+ export interface _TracingDurationHistogramResponse {
+ /** One row per duration bucket and service. */
+ results: _TracingDurationHistogramRow[];
+ }
+
export interface _TracingErrorCountsRequest {
/**
* Hex trace IDs to count exceptions for, matched against the exception's `$trace_id` property. Case insensitive. At most 200 per request.
@@ -101570,6 +101727,28 @@ export namespace Schemas {
query: _TracingQueryBody;
}
+ export interface _TracingQueryResponse {
+ /** Matching spans, ordered by the requested column. */
+ results: _Span[];
+ /** Whether a further page exists. */
+ hasMore: boolean;
+ /**
+ * Cursor for the next page, or null on the last page. Pass it back as the query's `after`. Always null when ordering by duration, which pages by offset instead.
+ * @nullable
+ */
+ nextCursor: string | null;
+ }
+
+ export interface _TracingServiceName {
+ /** Service name. */
+ name: string;
+ }
+
+ export interface _TracingServiceNamesResponse {
+ /** Services that emitted spans in the window. */
+ results: _TracingServiceName[];
+ }
+
export interface _TracingSparklineQueryBody {
/** Date range for the query. Defaults to last hour. */
dateRange?: _TracingDateRange;
@@ -101588,6 +101767,20 @@ export namespace Schemas {
query: _TracingSparklineQueryBody;
}
+ export interface _TracingSparklineRow {
+ /** Start of the time bucket. */
+ time: string;
+ /** Service the count belongs to. */
+ service: string;
+ /** Spans in this bucket for this service. */
+ count: number;
+ }
+
+ export interface _TracingSparklineResponse {
+ /** One row per time bucket and service, ordered by time. */
+ results: _TracingSparklineRow[];
+ }
+
export interface _TracingTraceRequest {
/** Date range for the query. Defaults to last 24 hours. */
dateRange?: _TracingDateRange;
@@ -101600,6 +101793,18 @@ export namespace Schemas {
offset?: number;
}
+ export interface _TracingTraceResponse {
+ /** Spans in the trace, earliest first. */
+ results: _TraceSpan[];
+ /** Whether a further page of spans exists. */
+ hasMore: boolean;
+ /**
+ * Offset for the next page, or null on the last page.
+ * @nullable
+ */
+ nextOffset: number | null;
+ }
+
export interface _TracingTreeQueryBody {
/** Span name to scope the matched trace set. Required because the (trace_id, parent_span_id) self-join is unsafe without bounding the matched traces. */
spanName: string;
@@ -101620,6 +101825,16 @@ export namespace Schemas {
query: _TracingTreeQueryBody;
}
+ export interface _TracingTreeResponse {
+ /** Call tree nodes for the requested window. */
+ results: _SpanTreeNode[];
+ /**
+ * Nodes for the comparison window when compareFilter.compare is true. Null when no comparison was requested, and an empty list when one was requested and matched no spans.
+ * @nullable
+ */
+ compare: _SpanTreeNode[] | null;
+ }
+
export type BillingSpendRetrieveParams = {
/**
* The `next` cursor from the previous page. Opaque. Ignored without page_size.
diff --git a/services/mcp/src/tools/generated/tracing.ts b/services/mcp/src/tools/generated/tracing.ts
index 1f9701ea369a..65eb6c091572 100644
--- a/services/mcp/src/tools/generated/tracing.ts
+++ b/services/mcp/src/tools/generated/tracing.ts
@@ -4,7 +4,7 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/tracing/api'
import { withUiApp } from '@/resources/ui-apps'
-import { withPostHogUrl, pickResponseFields } from '@/tools/tool-utils'
+import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
const ApmAttributeBreakdownSchema = () => {
@@ -94,12 +94,15 @@ const ApmServicesListSchema = () => {
return TracingSpansServiceNamesRetrieveQueryParams
}
-const apmServicesList = (): ToolBase<ReturnType<typeof ApmServicesListSchema>, unknown> => ({
+const apmServicesList = (): ToolBase<
+ ReturnType<typeof ApmServicesListSchema>,
+ Schemas._TracingServiceNamesResponse
+> => ({
name: 'apm-services-list',
schema: ApmServicesListSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof ApmServicesListSchema>>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<unknown>({
+ const result = await context.api.request<Schemas._TracingServiceNamesResponse>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/tracing/spans/service-names/`,
query: {
@@ -168,7 +171,10 @@ const ApmSpansDurationHistogramSchema = () => {
return TracingSpansDurationHistogramCreateBody
}
-const apmSpansDurationHistogram = (): ToolBase<ReturnType<typeof ApmSpansDurationHistogramSchema>, unknown> => ({
+const apmSpansDurationHistogram = (): ToolBase<
+ ReturnType<typeof ApmSpansDurationHistogramSchema>,
+ Schemas._TracingDurationHistogramResponse
+> => ({
name: 'apm-spans-duration-histogram',
schema: ApmSpansDurationHistogramSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof ApmSpansDurationHistogramSchema>>) => {
@@ -177,7 +183,7 @@ const apmSpansDurationHistogram = (): ToolBase<ReturnType<typeof ApmSpansDuratio
if (params.query !== undefined) {
body['query'] = params.query
}
- const result = await context.api.request<unknown>({
+ const result = await context.api.request<Schemas._TracingDurationHistogramResponse>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/tracing/spans/duration-histogram/`,
body,
@@ -219,7 +225,10 @@ const ApmSpansSparklineSchema = () => {
return TracingSpansSparklineCreateBody
}
-const apmSpansSparkline = (): ToolBase<ReturnType<typeof ApmSpansSparklineSchema>, unknown> => ({
+const apmSpansSparkline = (): ToolBase<
+ ReturnType<typeof ApmSpansSparklineSchema>,
+ Schemas._TracingSparklineResponse
+> => ({
name: 'apm-spans-sparkline',
schema: ApmSpansSparklineSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof ApmSpansSparklineSchema>>) => {
@@ -228,7 +237,7 @@ const apmSpansSparkline = (): ToolBase<ReturnType<typeof ApmSpansSparklineSchema
if (params.query !== undefined) {
body['query'] = params.query
}
- const result = await context.api.request<unknown>({
+ const result = await context.api.request<Schemas._TracingSparklineResponse>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/tracing/spans/sparkline/`,
body,
@@ -243,7 +252,7 @@ const ApmSpansTreeSchema = () => {
return TracingSpansTreeCreateBody
}
-const apmSpansTree = (): ToolBase<ReturnType<typeof ApmSpansTreeSchema>, unknown> => ({
+const apmSpansTree = (): ToolBase<ReturnType<typeof ApmSpansTreeSchema>, Schemas._TracingTreeResponse> => ({
name: 'apm-spans-tree',
schema: ApmSpansTreeSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof ApmSpansTreeSchema>>) => {
@@ -252,7 +261,7 @@ const apmSpansTree = (): ToolBase<ReturnType<typeof ApmSpansTreeSchema>, unknown
if (params.query !== undefined) {
body['query'] = params.query
}
- const result = await context.api.request<unknown>({
+ const result = await context.api.request<Schemas._TracingTreeResponse>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/tracing/spans/tree/`,
body,
@@ -268,7 +277,7 @@ const ApmTraceGetSchema = () => {
return TracingSpansTraceCreateParams.omit({ project_id: true }).extend(TracingSpansTraceCreateBody.shape)
}
-const apmTraceGet = (): ToolBase<ReturnType<typeof ApmTraceGetSchema>, unknown> =>
+const apmTraceGet = (): ToolBase<ReturnType<typeof ApmTraceGetSchema>, WithPostHogUrl<Schemas._TracingTraceResponse>> =>
withUiApp('trace-span-list', {
name: 'apm-trace-get',
schema: ApmTraceGetSchema(),
@@ -284,7 +293,7 @@ const apmTraceGet = (): ToolBase<ReturnType<typeof ApmTraceGetSchema>, unknown>
if (params.offset !== undefined) {
body['offset'] = params.offset
}
- const result = await context.api.request<unknown>({
+ const result = await context.api.request<Schemas._TracingTraceResponse>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/tracing/spans/trace/${encodeURIComponent(String(params.trace_id))}/`,
body,
@@ -299,7 +308,7 @@ const QueryApmSpansSchema = () => {
return TracingSpansQueryCreateBody
}
-const queryApmSpans = (): ToolBase<ReturnType<typeof QueryApmSpansSchema>, unknown> =>
+const queryApmSpans = (): ToolBase<ReturnType<typeof QueryApmSpansSchema>, Schemas._TracingQueryResponse> =>
withUiApp('trace-span-list', {
name: 'query-apm-spans',
schema: QueryApmSpansSchema(),
@@ -309,7 +318,7 @@ const queryApmSpans = (): ToolBase<ReturnType<typeof QueryApmSpansSchema>, unkno
if (params.query !== undefined) {
body['query'] = params.query
}
- const result = await context.api.request<unknown>({
+ const result = await context.api.request<Schemas._TracingQueryResponse>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/tracing/spans/query/`,
body,