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 MCP tools (#54443)

Frank Hamand6b8de970df03
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 119764cbbf35..1d6124f2290f 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -223,6 +223,7 @@ export const MCP_SERVER_OAUTH_SCOPES = [
'event_definition:write',
'error_tracking:read',
'logs:read',
+ 'tracing:read',
]
export const getScopeDescription = (scope: string): string | undefined => {
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index 896cbf685ef9..36ec5c760bb1 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -31,6 +31,7 @@ MCP_READ_SCOPES: list[str] = [
"logs:read",
"notebook:read",
"organization:read",
+ "tracing:read",
"project:read",
"property_definition:read",
"query:read",
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index e25c84f7d9af..a05ecec52d49 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -12,8 +12,9 @@ No business logic here - that belongs in logic.py via the facade.
import json
+from drf_spectacular.utils import extend_schema
from pydantic import ValidationError
-from rest_framework import status, viewsets
+from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import ParseError
from rest_framework.request import Request
@@ -43,12 +44,164 @@ from ..logic import (
)
from ..sparkline_query_runner import TraceSpansSparklineQueryRunner
-
+# Serializers below are used exclusively for OpenAPI spec generation via
+# drf-spectacular. They are NOT used for request validation — the existing
+# manual parsing in SpansViewSet is unchanged.
+
+
+class _TracingDateRangeSerializer(serializers.Serializer):
+ date_from = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Start of the date range. Accepts ISO 8601 timestamps or relative formats: -1h, -6h, -1d, -7d, etc.",
+ )
+ date_to = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text='End of the date range. Same format as date_from. Omit or null for "now".',
+ )
+
+
+_SPAN_PROPERTY_TYPE_CHOICES = ["span", "span_attribute", "span_resource_attribute"]
+_SPAN_STRING_OPERATORS = ["exact", "is_not", "icontains", "not_icontains", "regex", "not_regex"]
+_SPAN_NUMERIC_OPERATORS = ["exact", "gt", "lt"]
+_SPAN_EXISTENCE_OPERATORS = ["is_set", "is_not_set"]
+_SPAN_ALL_OPERATORS = _SPAN_STRING_OPERATORS + _SPAN_NUMERIC_OPERATORS + _SPAN_EXISTENCE_OPERATORS
+
+
+class _SpanPropertyFilterSerializer(serializers.Serializer):
+ key = serializers.CharField(
+ help_text='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 = serializers.ChoiceField(
+ choices=_SPAN_PROPERTY_TYPE_CHOICES,
+ help_text='"span" filters built-in span fields. "span_attribute" filters span-level attributes. "span_resource_attribute" filters resource-level attributes.',
+ )
+ operator = serializers.ChoiceField(
+ choices=_SPAN_ALL_OPERATORS,
+ help_text="Comparison operator.",
+ )
+ value = serializers.JSONField(
+ required=False,
+ allow_null=True,
+ help_text="Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators.",
+ )
+
+
+class _TracingQueryBodySerializer(serializers.Serializer):
+ 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 HTTP status codes.",
+ )
+ orderBy = serializers.ChoiceField(
+ choices=["latest", "earliest"],
+ required=False,
+ help_text="Order results by timestamp. Defaults to latest.",
+ )
+ filterGroup = serializers.ListField(
+ child=_SpanPropertyFilterSerializer(),
+ required=False,
+ default=[],
+ help_text="Property filters for the query.",
+ )
+ traceId = serializers.CharField(
+ required=False,
+ help_text="Filter to a specific trace ID (hex string).",
+ )
+ limit = serializers.IntegerField(
+ required=False,
+ default=100,
+ help_text="Max results (1-1000). Defaults to 100.",
+ )
+ after = serializers.CharField(
+ required=False,
+ help_text="Pagination cursor from previous response.",
+ )
+ rootSpans = serializers.BooleanField(
+ required=False,
+ default=True,
+ help_text="Filter to root spans only. Defaults to true.",
+ )
+ prefetchSpans = serializers.IntegerField(
+ required=False,
+ help_text="Number of child spans to prefetch per trace (1-100).",
+ )
+
+
+class _TracingQueryRequestSerializer(serializers.Serializer):
+ query = _TracingQueryBodySerializer(help_text="The tracing spans query to execute.")
+
+
+class _TracingTraceRequestSerializer(serializers.Serializer):
+ dateRange = _TracingDateRangeSerializer(
+ required=False,
+ help_text="Date range for the query. Defaults to last 24 hours.",
+ )
+
+
+class _TracingServiceNamesQuerySerializer(serializers.Serializer):
+ search = serializers.CharField(required=False, help_text="Search filter for service names.")
+ dateRange = serializers.CharField(
+ required=False,
+ help_text='JSON-encoded date range, e.g. \'{"date_from": "-1h"}\'.',
+ )
+
+
+class _TracingAttributesQuerySerializer(serializers.Serializer):
+ search = serializers.CharField(required=False, help_text="Search filter for attribute names.")
+ attribute_type = serializers.ChoiceField(
+ choices=["span", "resource"],
+ required=False,
+ help_text='Type of attributes: "span" for span attributes, "resource" for resource attributes.',
+ )
+ limit = serializers.IntegerField(
+ required=False, min_value=1, max_value=100, help_text="Max results (default: 100)."
+ )
+ offset = serializers.IntegerField(required=False, min_value=0, help_text="Pagination offset (default: 0).")
+
+
+class _TracingValuesQuerySerializer(serializers.Serializer):
+ key = serializers.CharField(help_text="The attribute key to get values for.")
+ attribute_type = serializers.ChoiceField(
+ choices=["span", "resource"],
+ required=False,
+ help_text='Type of attribute: "span" or "resource".',
+ )
+ value = serializers.CharField(required=False, help_text="Search filter for attribute values.")
+ limit = serializers.IntegerField(
+ required=False, min_value=1, max_value=100, help_text="Max results (default: 100)."
+ )
+ offset = serializers.IntegerField(required=False, min_value=0, help_text="Pagination offset (default: 0).")
+
+
+@extend_schema(tags=["tracing"])
class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
- scope_object = "INTERNAL"
+ scope_object = "tracing"
serializer_class = _FallbackSerializer
- @action(detail=False, methods=["GET"], url_path="service-names")
+ @staticmethod
+ def _normalize_filter_group(filter_group: object) -> dict:
+ """Normalize a flat filter array (from MCP) to the nested PropertyGroupFilter structure."""
+ if isinstance(filter_group, list):
+ if len(filter_group) > 0:
+ return {"type": "AND", "values": [{"type": "AND", "values": filter_group}]}
+ return {"type": "AND", "values": []}
+ if isinstance(filter_group, dict):
+ return filter_group
+ return {"type": "AND", "values": []}
+
+ @extend_schema(parameters=[_TracingServiceNamesQuerySerializer])
+ @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)
search = request.GET.get("search", "")
@@ -60,7 +213,8 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
results = run_service_names_query(team=self.team, date_range=date_range, search=search)
return Response({"results": results}, status=status.HTTP_200_OK)
- @action(detail=False, methods=["POST"])
+ @extend_schema(request=_TracingQueryRequestSerializer)
+ @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)
query_data = request.data.get("query", {})
@@ -78,7 +232,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
prefetch_spans = min(int(prefetch_spans), 100)
filter_group = (
- self.get_model(query_data.get("filterGroup"), PropertyGroupFilter)
+ self.get_model(self._normalize_filter_group(query_data.get("filterGroup")), PropertyGroupFilter)
if query_data.get("filterGroup")
else None
)
@@ -116,7 +270,8 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
status=status.HTTP_200_OK,
)
- @action(detail=False, methods=["POST"])
+ @extend_schema(request=_TracingQueryRequestSerializer)
+ @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)
query_data = request.data.get("query", {})
@@ -124,7 +279,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
try:
filter_group = (
- self.get_model(query_data["filterGroup"], PropertyGroupFilter)
+ self.get_model(self._normalize_filter_group(query_data["filterGroup"]), PropertyGroupFilter)
if query_data.get("filterGroup")
else None
)
@@ -144,7 +299,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
return Response({"results": response.results}, status=status.HTTP_200_OK)
- @action(detail=False, methods=["POST"], url_path="trace/(?P<trace_id>[a-zA-Z0-9]+)")
+ @extend_schema(request=_TracingTraceRequestSerializer)
+ @action(
+ detail=False, methods=["POST"], url_path="trace/(?P<trace_id>[a-zA-Z0-9]+)", required_scopes=["tracing:read"]
+ )
def trace(self, request: Request, trace_id: str, *args, **kwargs) -> Response:
tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
query_data = request.data or {}
@@ -184,7 +342,8 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
status=status.HTTP_200_OK,
)
- @action(detail=False, methods=["get"])
+ @extend_schema(parameters=[_TracingAttributesQuerySerializer])
+ @action(detail=False, methods=["get"], required_scopes=["tracing:read"])
def attributes(self, request: Request, *args, **kwargs) -> Response:
tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
search = request.GET.get("search", "")
@@ -211,7 +370,8 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
return Response({"results": results, "count": count}, status=status.HTTP_200_OK)
- @action(detail=False, methods=["GET"])
+ @extend_schema(parameters=[_TracingValuesQuerySerializer])
+ @action(detail=False, methods=["GET"], required_scopes=["tracing:read"])
def values(self, request: Request, *args, **kwargs) -> Response:
tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
attribute_key = request.GET.get("key", "")
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index 9f8941edee6b..a792d66a2290 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -7,3 +7,218 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+export interface _TracingDateRangeApi {
+ /**
+ * Start of the date range. Accepts ISO 8601 timestamps or relative formats: -1h, -6h, -1d, -7d, etc.
+ * @nullable
+ */
+ date_from?: string | null
+ /**
+ * End of the date range. Same format as date_from. Omit or null for "now".
+ * @nullable
+ */
+ date_to?: string | null
+}
+
+/**
+ * * `latest` - latest
+ * `earliest` - earliest
+ */
+export type OrderByEnumApi = (typeof OrderByEnumApi)[keyof typeof OrderByEnumApi]
+
+export const OrderByEnumApi = {
+ Latest: 'latest',
+ Earliest: 'earliest',
+} as const
+
+/**
+ * * `span` - span
+ * `span_attribute` - span_attribute
+ * `span_resource_attribute` - span_resource_attribute
+ */
+export type _SpanPropertyFilterTypeEnumApi =
+ (typeof _SpanPropertyFilterTypeEnumApi)[keyof typeof _SpanPropertyFilterTypeEnumApi]
+
+export const _SpanPropertyFilterTypeEnumApi = {
+ Span: 'span',
+ SpanAttribute: 'span_attribute',
+ SpanResourceAttribute: 'span_resource_attribute',
+} as const
+
+/**
+ * * `exact` - exact
+ * `is_not` - is_not
+ * `icontains` - icontains
+ * `not_icontains` - not_icontains
+ * `regex` - regex
+ * `not_regex` - not_regex
+ * `gt` - gt
+ * `lt` - lt
+ * `is_set` - is_set
+ * `is_not_set` - is_not_set
+ */
+export type _SpanPropertyFilterOperatorEnumApi =
+ (typeof _SpanPropertyFilterOperatorEnumApi)[keyof typeof _SpanPropertyFilterOperatorEnumApi]
+
+export const _SpanPropertyFilterOperatorEnumApi = {
+ Exact: 'exact',
+ IsNot: 'is_not',
+ Icontains: 'icontains',
+ NotIcontains: 'not_icontains',
+ Regex: 'regex',
+ NotRegex: 'not_regex',
+ Gt: 'gt',
+ Lt: 'lt',
+ IsSet: 'is_set',
+ IsNotSet: 'is_not_set',
+} as const
+
+export interface _SpanPropertyFilterApi {
+ /** 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"). */
+ key: string
+ /** "span" filters built-in span fields. "span_attribute" filters span-level attributes. "span_resource_attribute" filters resource-level attributes.
+
+* `span` - span
+* `span_attribute` - span_attribute
+* `span_resource_attribute` - span_resource_attribute */
+ type: _SpanPropertyFilterTypeEnumApi
+ /** Comparison operator.
+
+* `exact` - exact
+* `is_not` - is_not
+* `icontains` - icontains
+* `not_icontains` - not_icontains
+* `regex` - regex
+* `not_regex` - not_regex
+* `gt` - gt
+* `lt` - lt
+* `is_set` - is_set
+* `is_not_set` - is_not_set */
+ operator: _SpanPropertyFilterOperatorEnumApi
+ /** Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators. */
+ value?: unknown | null
+}
+
+export interface _TracingQueryBodyApi {
+ /** Date range for the query. Defaults to last hour. */
+ dateRange?: _TracingDateRangeApi
+ /** Filter by service names. */
+ serviceNames?: string[]
+ /** Filter by HTTP status codes. */
+ statusCodes?: number[]
+ /** Order results by timestamp. Defaults to latest.
+
+* `latest` - latest
+* `earliest` - earliest */
+ orderBy?: OrderByEnumApi
+ /** Property filters for the query. */
+ filterGroup?: _SpanPropertyFilterApi[]
+ /** Filter to a specific trace ID (hex string). */
+ traceId?: string
+ /** Max results (1-1000). Defaults to 100. */
+ limit?: number
+ /** Pagination cursor from previous response. */
+ after?: string
+ /** Filter to root spans only. Defaults to true. */
+ rootSpans?: boolean
+ /** Number of child spans to prefetch per trace (1-100). */
+ prefetchSpans?: number
+}
+
+export interface _TracingQueryRequestApi {
+ /** The tracing spans query to execute. */
+ query: _TracingQueryBodyApi
+}
+
+export interface _TracingTraceRequestApi {
+ /** Date range for the query. Defaults to last 24 hours. */
+ dateRange?: _TracingDateRangeApi
+}
+
+export type TracingSpansAttributesRetrieveParams = {
+ /**
+ * Type of attributes: "span" for span attributes, "resource" for resource attributes.
+
+* `span` - span
+* `resource` - resource
+ * @minLength 1
+ */
+ attribute_type?: TracingSpansAttributesRetrieveAttributeType
+ /**
+ * Max results (default: 100).
+ * @minimum 1
+ * @maximum 100
+ */
+ limit?: number
+ /**
+ * Pagination offset (default: 0).
+ * @minimum 0
+ */
+ offset?: number
+ /**
+ * Search filter for attribute names.
+ * @minLength 1
+ */
+ search?: string
+}
+
+export type TracingSpansAttributesRetrieveAttributeType =
+ (typeof TracingSpansAttributesRetrieveAttributeType)[keyof typeof TracingSpansAttributesRetrieveAttributeType]
+
+export const TracingSpansAttributesRetrieveAttributeType = {
+ Span: 'span',
+ Resource: 'resource',
+} as const
+
+export type TracingSpansServiceNamesRetrieveParams = {
+ /**
+ * JSON-encoded date range, e.g. '{"date_from": "-1h"}'.
+ * @minLength 1
+ */
+ dateRange?: string
+ /**
+ * Search filter for service names.
+ * @minLength 1
+ */
+ search?: string
+}
+
+export type TracingSpansValuesRetrieveParams = {
+ /**
+ * Type of attribute: "span" or "resource".
+
+* `span` - span
+* `resource` - resource
+ * @minLength 1
+ */
+ attribute_type?: TracingSpansValuesRetrieveAttributeType
+ /**
+ * The attribute key to get values for.
+ * @minLength 1
+ */
+ key: string
+ /**
+ * Max results (default: 100).
+ * @minimum 1
+ * @maximum 100
+ */
+ limit?: number
+ /**
+ * Pagination offset (default: 0).
+ * @minimum 0
+ */
+ offset?: number
+ /**
+ * Search filter for attribute values.
+ * @minLength 1
+ */
+ value?: string
+}
+
+export type TracingSpansValuesRetrieveAttributeType =
+ (typeof TracingSpansValuesRetrieveAttributeType)[keyof typeof TracingSpansValuesRetrieveAttributeType]
+
+export const TracingSpansValuesRetrieveAttributeType = {
+ Span: 'span',
+ Resource: 'resource',
+} as const
diff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.ts
index bbba5d4d295b..68549d1179cb 100644
--- a/products/tracing/frontend/generated/api.ts
+++ b/products/tracing/frontend/generated/api.ts
@@ -1,3 +1,4 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
/**
* Auto-generated from the Django backend OpenAPI schema.
* To modify these types, update the Django serializers or views, then run:
@@ -7,14 +8,39 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
-import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+import type {
+ TracingSpansAttributesRetrieveParams,
+ TracingSpansServiceNamesRetrieveParams,
+ TracingSpansValuesRetrieveParams,
+ _TracingQueryRequestApi,
+ _TracingTraceRequestApi,
+} from './api.schemas'
+
+export const getTracingSpansAttributesRetrieveUrl = (
+ projectId: string,
+ params?: TracingSpansAttributesRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
-export const getTracingSpansAttributesRetrieveUrl = (projectId: string) => {
- return `/api/environments/${projectId}/tracing/spans/attributes/`
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/environments/${projectId}/tracing/spans/attributes/?${stringifiedParams}`
+ : `/api/environments/${projectId}/tracing/spans/attributes/`
}
-export const tracingSpansAttributesRetrieve = async (projectId: string, options?: RequestInit): Promise<void> => {
- return apiMutator<void>(getTracingSpansAttributesRetrieveUrl(projectId), {
+export const tracingSpansAttributesRetrieve = async (
+ projectId: string,
+ params?: TracingSpansAttributesRetrieveParams,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getTracingSpansAttributesRetrieveUrl(projectId, params), {
...options,
method: 'GET',
})
@@ -24,19 +50,44 @@ export const getTracingSpansQueryCreateUrl = (projectId: string) => {
return `/api/environments/${projectId}/tracing/spans/query/`
}
-export const tracingSpansQueryCreate = async (projectId: string, options?: RequestInit): Promise<void> => {
+export const tracingSpansQueryCreate = async (
+ projectId: string,
+ _tracingQueryRequestApi: _TracingQueryRequestApi,
+ options?: RequestInit
+): Promise<void> => {
return apiMutator<void>(getTracingSpansQueryCreateUrl(projectId), {
...options,
method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(_tracingQueryRequestApi),
})
}
-export const getTracingSpansServiceNamesRetrieveUrl = (projectId: string) => {
- return `/api/environments/${projectId}/tracing/spans/service-names/`
+export const getTracingSpansServiceNamesRetrieveUrl = (
+ projectId: string,
+ params?: TracingSpansServiceNamesRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/environments/${projectId}/tracing/spans/service-names/?${stringifiedParams}`
+ : `/api/environments/${projectId}/tracing/spans/service-names/`
}
-export const tracingSpansServiceNamesRetrieve = async (projectId: string, options?: RequestInit): Promise<void> => {
- return apiMutator<void>(getTracingSpansServiceNamesRetrieveUrl(projectId), {
+export const tracingSpansServiceNamesRetrieve = async (
+ projectId: string,
+ params?: TracingSpansServiceNamesRetrieveParams,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getTracingSpansServiceNamesRetrieveUrl(projectId, params), {
...options,
method: 'GET',
})
@@ -46,10 +97,16 @@ export const getTracingSpansSparklineCreateUrl = (projectId: string) => {
return `/api/environments/${projectId}/tracing/spans/sparkline/`
}
-export const tracingSpansSparklineCreate = async (projectId: string, options?: RequestInit): Promise<void> => {
+export const tracingSpansSparklineCreate = async (
+ projectId: string,
+ _tracingQueryRequestApi: _TracingQueryRequestApi,
+ options?: RequestInit
+): Promise<void> => {
return apiMutator<void>(getTracingSpansSparklineCreateUrl(projectId), {
...options,
method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(_tracingQueryRequestApi),
})
}
@@ -60,20 +117,39 @@ export const getTracingSpansTraceCreateUrl = (projectId: string, traceId: string
export const tracingSpansTraceCreate = async (
projectId: string,
traceId: string,
+ _tracingTraceRequestApi: _TracingTraceRequestApi,
options?: RequestInit
): Promise<void> => {
return apiMutator<void>(getTracingSpansTraceCreateUrl(projectId, traceId), {
...options,
method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(_tracingTraceRequestApi),
})
}
-export const getTracingSpansValuesRetrieveUrl = (projectId: string) => {
- return `/api/environments/${projectId}/tracing/spans/values/`
+export const getTracingSpansValuesRetrieveUrl = (projectId: string, params: TracingSpansValuesRetrieveParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/environments/${projectId}/tracing/spans/values/?${stringifiedParams}`
+ : `/api/environments/${projectId}/tracing/spans/values/`
}
-export const tracingSpansValuesRetrieve = async (projectId: string, options?: RequestInit): Promise<void> => {
- return apiMutator<void>(getTracingSpansValuesRetrieveUrl(projectId), {
+export const tracingSpansValuesRetrieve = async (
+ projectId: string,
+ params: TracingSpansValuesRetrieveParams,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getTracingSpansValuesRetrieveUrl(projectId, params), {
...options,
method: 'GET',
})
diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.ts
index e8a15d4e1b52..e370b1001643 100644
--- a/products/tracing/frontend/generated/api.zod.ts
+++ b/products/tracing/frontend/generated/api.zod.ts
@@ -7,3 +7,204 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+import * as zod from 'zod'
+
+export const tracingSpansQueryCreateBodyQueryOneFilterGroupDefault = []
+export const tracingSpansQueryCreateBodyQueryOneLimitDefault = 100
+export const tracingSpansQueryCreateBodyQueryOneRootSpansDefault = true
+
+export const TracingSpansQueryCreateBody = /* @__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 query. 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.'),
+ orderBy: zod
+ .enum(['latest', 'earliest'])
+ .describe('* `latest` - latest\n* `earliest` - earliest')
+ .optional()
+ .describe(
+ 'Order results by timestamp. Defaults to latest.\n\n* `latest` - latest\n* `earliest` - earliest'
+ ),
+ 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()
+ .nullish()
+ .describe(
+ 'Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators.'
+ ),
+ })
+ )
+ .default(tracingSpansQueryCreateBodyQueryOneFilterGroupDefault)
+ .describe('Property filters for the query.'),
+ traceId: zod.string().optional().describe('Filter to a specific trace ID (hex string).'),
+ limit: zod
+ .number()
+ .default(tracingSpansQueryCreateBodyQueryOneLimitDefault)
+ .describe('Max results (1-1000). Defaults to 100.'),
+ after: zod.string().optional().describe('Pagination cursor from previous response.'),
+ rootSpans: zod
+ .boolean()
+ .default(tracingSpansQueryCreateBodyQueryOneRootSpansDefault)
+ .describe('Filter to root spans only. Defaults to true.'),
+ prefetchSpans: zod.number().optional().describe('Number of child spans to prefetch per trace (1-100).'),
+ })
+ .describe('The tracing spans query to execute.'),
+})
+
+export const tracingSpansSparklineCreateBodyQueryOneFilterGroupDefault = []
+export const tracingSpansSparklineCreateBodyQueryOneLimitDefault = 100
+export const tracingSpansSparklineCreateBodyQueryOneRootSpansDefault = true
+
+export const TracingSpansSparklineCreateBody = /* @__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 query. 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.'),
+ orderBy: zod
+ .enum(['latest', 'earliest'])
+ .describe('* `latest` - latest\n* `earliest` - earliest')
+ .optional()
+ .describe(
+ 'Order results by timestamp. Defaults to latest.\n\n* `latest` - latest\n* `earliest` - earliest'
+ ),
+ 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()
+ .nullish()
+ .describe(
+ 'Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators.'
+ ),
+ })
+ )
+ .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('Pagination cursor from previous response.'),
+ 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).'),
+ })
+ .describe('The tracing spans query to execute.'),
+})
+
+export const TracingSpansTraceCreateBody = /* @__PURE__ */ 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 query. Defaults to last 24 hours.'),
+})
diff --git a/products/tracing/mcp/apps/TraceSpanListView.tsx b/products/tracing/mcp/apps/TraceSpanListView.tsx
new file mode 100644
index 000000000000..f3edb898dc96
--- /dev/null
+++ b/products/tracing/mcp/apps/TraceSpanListView.tsx
@@ -0,0 +1,141 @@
+import { type ReactElement, type ReactNode } from 'react'
+
+import { Badge, DataTable, type DataTableColumn, ListDetailView, Stack } from '@posthog/mosaic'
+
+import { TraceSpanView, type TraceSpanData } from './TraceSpanView'
+
+export interface TraceSpanListData {
+ results: TraceSpanData[]
+ hasMore?: boolean
+ _posthogUrl?: string
+}
+
+export interface TraceSpanListViewProps {
+ data: TraceSpanListData
+ onSpanClick?: (span: TraceSpanData) => Promise<TraceSpanData | null>
+}
+
+function formatDuration(nanos: number): string {
+ if (nanos < 1_000_000) {
+ return `${(nanos / 1_000).toFixed(1)} \u00b5s`
+ }
+ if (nanos < 1_000_000_000) {
+ return `${(nanos / 1_000_000).toFixed(1)} ms`
+ }
+ return `${(nanos / 1_000_000_000).toFixed(2)} s`
+}
+
+function formatTimestamp(ts: string): string {
+ try {
+ const d = new Date(ts)
+ return d.toLocaleString(undefined, {
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ fractionalSecondDigits: 3,
+ })
+ } catch {
+ return ts
+ }
+}
+
+const statusVariant: Record<string, 'success' | 'danger' | 'neutral'> = {
+ '0': 'neutral',
+ '1': 'success',
+ '2': 'danger',
+}
+
+const statusLabel: Record<string, string> = {
+ '0': 'Unset',
+ '1': 'OK',
+ '2': 'Error',
+}
+
+export function TraceSpanListView({ data, onSpanClick }: TraceSpanListViewProps): ReactElement {
+ return (
+ <ListDetailView<TraceSpanData>
+ onItemClick={onSpanClick}
+ backLabel="All spans"
+ getItemName={(span) => span.name}
+ renderDetail={(span) => <TraceSpanView data={span} />}
+ renderList={(handleClick) => {
+ const columns: DataTableColumn<TraceSpanData>[] = [
+ {
+ key: 'name',
+ header: 'Name',
+ sortable: true,
+ render: (row): ReactNode =>
+ onSpanClick ? (
+ <button
+ onClick={() => handleClick(row)}
+ className="text-link underline decoration-border-primary hover:decoration-link cursor-pointer text-left transition-colors max-w-xs truncate block"
+ >
+ {row.name}
+ </button>
+ ) : (
+ <span className="max-w-xs truncate block">{row.name}</span>
+ ),
+ },
+ {
+ key: 'service_name',
+ header: 'Service',
+ sortable: true,
+ render: (row): ReactNode => (
+ <span className="text-text-secondary">{row.service_name ?? '\u2014'}</span>
+ ),
+ },
+ {
+ key: 'status_code',
+ header: 'Status',
+ render: (row): ReactNode => {
+ const key = String(row.status_code ?? '0')
+ return (
+ <Badge variant={statusVariant[key] ?? 'neutral'} size="sm">
+ {statusLabel[key] ?? key}
+ </Badge>
+ )
+ },
+ },
+ {
+ key: 'duration_nano',
+ header: 'Duration',
+ sortable: true,
+ render: (row): ReactNode => (
+ <span className="text-text-secondary font-mono text-xs">
+ {row.duration_nano != null ? formatDuration(row.duration_nano) : '\u2014'}
+ </span>
+ ),
+ },
+ {
+ key: 'timestamp',
+ header: 'Time',
+ sortable: true,
+ render: (row): ReactNode => (
+ <span className="text-text-secondary text-xs">{formatTimestamp(row.timestamp)}</span>
+ ),
+ },
+ ]
+
+ return (
+ <div className="p-4">
+ <Stack gap="sm">
+ <div className="flex items-center justify-between">
+ <span className="text-sm text-text-secondary">
+ {data.results.length} span{data.results.length === 1 ? '' : 's'}
+ {data.hasMore ? '+' : ''}
+ </span>
+ </div>
+ <DataTable<TraceSpanData>
+ columns={columns}
+ data={data.results}
+ pageSize={20}
+ defaultSort={{ key: 'timestamp', direction: 'desc' }}
+ emptyMessage="No trace spans found"
+ />
+ </Stack>
+ </div>
+ )
+ }}
+ />
+ )
+}
diff --git a/products/tracing/mcp/apps/TraceSpanView.tsx b/products/tracing/mcp/apps/TraceSpanView.tsx
new file mode 100644
index 000000000000..cce5ae63edbc
--- /dev/null
+++ b/products/tracing/mcp/apps/TraceSpanView.tsx
@@ -0,0 +1,111 @@
+import type { ReactElement } from 'react'
+
+import { Badge, Card, DescriptionList, Stack } from '@posthog/mosaic'
+
+export interface TraceSpanData {
+ uuid: string
+ trace_id: string
+ span_id: string
+ parent_span_id?: string | null
+ name: string
+ kind?: string | null
+ service_name?: string | null
+ status_code?: number | null
+ timestamp: string
+ end_time?: string | null
+ duration_nano?: number | null
+ is_root_span?: boolean
+ matched_filter?: boolean
+ _posthogUrl?: string
+}
+
+function formatDuration(nanos: number): string {
+ if (nanos < 1_000_000) {
+ return `${(nanos / 1_000).toFixed(1)} \u00b5s`
+ }
+ if (nanos < 1_000_000_000) {
+ return `${(nanos / 1_000_000).toFixed(1)} ms`
+ }
+ return `${(nanos / 1_000_000_000).toFixed(2)} s`
+}
+
+function formatTimestamp(ts: string): string {
+ try {
+ const d = new Date(ts)
+ return d.toLocaleString(undefined, {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ fractionalSecondDigits: 3,
+ })
+ } catch {
+ return ts
+ }
+}
+
+const statusVariant: Record<string, 'success' | 'danger' | 'warning' | 'neutral'> = {
+ '0': 'neutral',
+ '1': 'success',
+ '2': 'danger',
+}
+
+const statusLabel: Record<string, string> = {
+ '0': 'Unset',
+ '1': 'OK',
+ '2': 'Error',
+}
+
+const kindLabel: Record<string, string> = {
+ '0': 'Unspecified',
+ '1': 'Internal',
+ '2': 'Server',
+ '3': 'Client',
+ '4': 'Producer',
+ '5': 'Consumer',
+}
+
+export function TraceSpanView({ data }: { data: TraceSpanData }): ReactElement {
+ const statusKey = String(data.status_code ?? '0')
+
+ return (
+ <div className="p-4">
+ <Stack gap="md">
+ <Stack gap="xs">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-lg font-semibold text-text-primary break-all">{data.name}</span>
+ <Badge variant={statusVariant[statusKey] ?? 'neutral'} size="md">
+ {statusLabel[statusKey] ?? `Status ${statusKey}`}
+ </Badge>
+ {data.is_root_span && (
+ <Badge variant="neutral" size="sm">
+ Root
+ </Badge>
+ )}
+ </div>
+ {data.service_name && <span className="text-sm text-text-secondary">{data.service_name}</span>}
+ </Stack>
+
+ <Card padding="md">
+ <DescriptionList
+ columns={2}
+ items={[
+ { label: 'Trace ID', value: data.trace_id },
+ { label: 'Span ID', value: data.span_id },
+ ...(data.parent_span_id ? [{ label: 'Parent span ID', value: data.parent_span_id }] : []),
+ ...(data.kind != null
+ ? [{ label: 'Kind', value: kindLabel[String(data.kind)] ?? String(data.kind) }]
+ : []),
+ { label: 'Timestamp', value: formatTimestamp(data.timestamp) },
+ ...(data.duration_nano != null
+ ? [{ label: 'Duration', value: formatDuration(data.duration_nano) }]
+ : []),
+ ]}
+ />
+ </Card>
+ </Stack>
+ </div>
+ )
+}
diff --git a/products/tracing/mcp/apps/index.ts b/products/tracing/mcp/apps/index.ts
new file mode 100644
index 000000000000..64a1d475bf98
--- /dev/null
+++ b/products/tracing/mcp/apps/index.ts
@@ -0,0 +1,2 @@
+export { TraceSpanView, type TraceSpanData } from './TraceSpanView'
+export { TraceSpanListView, type TraceSpanListData, type TraceSpanListViewProps } from './TraceSpanListView'
diff --git a/products/tracing/mcp/prompts/query-apm-spans.md b/products/tracing/mcp/prompts/query-apm-spans.md
new file mode 100644
index 000000000000..282870c19ef3
--- /dev/null
+++ b/products/tracing/mcp/prompts/query-apm-spans.md
@@ -0,0 +1,156 @@
+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, and is_root_span.
+
+Use 'apm-attributes-list' and 'apm-attribute-values-list' to discover available attributes before building filters. Use 'apm-services-list' to discover available services.
+
+CRITICAL: 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.
+
+All parameters must be nested inside a `query` object.
+
+# Data narrowing
+
+## Property filters
+
+Use 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.
+
+When using a property filter, you should:
+
+- **Choose the right type.** Span property types are:
+ - `span` — filters built-in span fields (trace_id, span_id, duration, name, kind, status_code).
+ - `span_attribute` — filters span-level attributes (e.g. "http.method", "http.status_code").
+ - `span_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).
+- **Use `apm-attributes-list` to discover available attribute keys** before building filters.
+- **Use `apm-attribute-values-list` to discover valid values** for a specific attribute key.
+- **Find the suitable operator for the value type** (see supported operators below).
+
+Supported operators:
+
+- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`
+- Numeric: `exact`, `gt`, `lt`
+- Existence (no value needed): `is_set`, `is_not_set`
+
+The `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.
+
+## Time period
+
+Use 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`.
+
+# Parameters
+
+All parameters go inside `query`.
+
+## query.serviceNames
+
+Filter by service names. Use `apm-services-list` to discover available services.
+
+## query.statusCodes
+
+Filter by HTTP status codes (list of integers).
+
+## query.orderBy
+
+Sort by timestamp: `latest` (default) or `earliest`.
+
+## query.filterGroup
+
+A 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.
+
+## query.dateRange
+
+Date range to filter results. 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.traceId
+
+Filter to a specific trace ID (hex string). Use this when you already know the trace ID.
+
+## query.rootSpans
+
+Filter to root spans only. Defaults to true. Set to false to include all spans in the trace tree.
+
+## query.limit
+
+Maximum number of results (1-1000). Defaults to 100.
+
+## query.after
+
+Cursor for pagination. Use the `nextCursor` value from the previous response.
+
+## query.prefetchSpans
+
+Number of child spans to prefetch per trace (1-100). Useful to get a preview of trace structure without fetching the full trace.
+
+# Examples
+
+## List recent error spans
+
+```json
+{
+ "query": {
+ "statusCodes": [500, 503]
+ }
+}
+```
+
+## Search spans from a specific service
+
+```json
+{
+ "query": {
+ "serviceNames": ["api-gateway"],
+ "dateRange": { "date_from": "-1d" }
+ }
+}
+```
+
+## Filter by a span attribute
+
+```json
+{
+ "query": {
+ "filterGroup": [{ "key": "http.method", "operator": "exact", "type": "span_attribute", "value": "POST" }],
+ "dateRange": { "date_from": "-6h" }
+ }
+}
+```
+
+## Find slow spans
+
+```json
+{
+ "query": {
+ "filterGroup": [{ "key": "duration", "operator": "gt", "type": "span", "value": "1000000000" }],
+ "dateRange": { "date_from": "-1d" }
+ }
+}
+```
+
+## Combine service and attribute filters
+
+```json
+{
+ "query": {
+ "serviceNames": ["web-server"],
+ "filterGroup": [{ "key": "http.status_code", "operator": "gt", "type": "span_attribute", "value": "399" }],
+ "dateRange": { "date_from": "-12h" }
+ }
+}
+```
+
+## Check if a resource attribute exists
+
+```json
+{
+ "query": {
+ "filterGroup": [{ "key": "k8s.pod.name", "operator": "is_set", "type": "span_resource_attribute" }]
+ }
+}
+```
+
+# Reminders
+
+- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.
+- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attributes before guessing filter keys/values.
+- Use `apm-services-list` to discover available services before filtering by service name.
+- Duration values are in nanoseconds (1 second = 1,000,000,000 nanoseconds).
diff --git a/products/tracing/mcp/tools.yaml b/products/tracing/mcp/tools.yaml
new file mode 100644
index 000000000000..606f9e5333c6
--- /dev/null
+++ b/products/tracing/mcp/tools.yaml
@@ -0,0 +1,111 @@
+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.
+# The tool list and operation IDs are kept in sync automatically:
+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all
+#
+# To enable a tool, set enabled: true and add required scopes + annotations.
+# All other fields (title, description, enrich_url, etc.) are yours to configure.
+category: Tracing
+feature: tracing
+url_prefix: /tracing
+ui_apps:
+ trace-span:
+ type: detail
+ view_prop: data
+ trace-span-list:
+ type: list
+ detail_tool: apm-trace-get
+ detail_args: '{ trace_id: item.trace_id }'
+ item_name_field: name
+ click_prop: onSpanClick
+tools:
+ apm-attribute-values-list:
+ operation: tracing_spans_values_retrieve
+ enabled: true
+ scopes:
+ - tracing:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List tracing attribute values
+ description: >
+ List values for a specific span or resource attribute key. Use to discover what values exist for a given
+ attribute before building filters.
+ feature_flag: tracing
+ response:
+ include:
+ - results
+ apm-attributes-list:
+ operation: tracing_spans_attributes_retrieve
+ enabled: true
+ scopes:
+ - tracing:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List tracing span attributes
+ description: >
+ List available span or resource attribute names. Use attribute_type "span" for span-level attributes or
+ "resource" for resource-level attributes (e.g. k8s labels). Use this to discover available attribute keys
+ before building filters.
+ feature_flag: tracing
+ response:
+ include:
+ - results
+ - count
+ apm-services-list:
+ operation: tracing_spans_service_names_retrieve
+ enabled: true
+ scopes:
+ - tracing:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List tracing service names
+ description: >
+ List distinct service names that have emitted trace spans. Use to discover available services before
+ filtering spans by service name.
+ feature_flag: tracing
+ response:
+ include:
+ - results
+ apm-sparkline-query:
+ operation: tracing_spans_sparkline_create
+ enabled: false
+ apm-trace-get:
+ operation: tracing_spans_trace_create
+ enabled: true
+ scopes:
+ - tracing:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Retrieve trace spans
+ description: >
+ Fetch all spans for a specific trace by its hex trace ID. Returns the full span tree for the trace including
+ parent-child relationships, timing, and status information. Use this to inspect a specific trace in detail
+ after discovering it via the query tool.
+ ui_app: trace-span-list
+ feature_flag: tracing
+ response:
+ include:
+ - results
+ query-apm-spans:
+ operation: tracing_spans_query_create
+ enabled: true
+ scopes:
+ - tracing:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Query tracing spans
+ description_file: ./prompts/query-apm-spans.md
+ ui_app: trace-span-list
+ feature_flag: tracing
+ response:
+ include:
+ - results
diff --git a/products/tracing/skills/exploring-apm-traces/SKILL.md b/products/tracing/skills/exploring-apm-traces/SKILL.md
new file mode 100644
index 000000000000..f62a439888ba
--- /dev/null
+++ b/products/tracing/skills/exploring-apm-traces/SKILL.md
@@ -0,0 +1,70 @@
+---
+name: exploring-apm-traces
+description: >
+ Investigates distributed application performance using PostHog APM (OpenTelemetry span) data via MCP.
+ Use when the user asks about service traces, slow HTTP/database spans, error spans, trace IDs, or span
+ attributes — not LLM analytics traces or product logs. Uses posthog:query-apm-spans, posthog:apm-trace-get,
+ posthog:apm-services-list, posthog:apm-attributes-list, and posthog:apm-attribute-values-list.
+---
+
+# Exploring APM traces (OpenTelemetry spans)
+
+PostHog captures distributed traces from OpenTelemetry. Each trace is a tree of spans representing a request’s path through services.
+
+**Disambiguation:** This skill is for **APM / OpenTelemetry traces**. Do not confuse with **LLM analytics traces** (agent/model `$ai_*` events and LLM observability tools) or **logs** (`posthog:query-logs`, `posthog:logs-*`).
+
+## MCP tools
+
+| Tool | Purpose |
+| ----------------------------------- | ------------------------------------------------------------------------------ |
+| `posthog:query-apm-spans` | Search and filter spans (analytics-style query; parameters live under `query`) |
+| `posthog:apm-trace-get` | Fetch all spans for a hex `trace_id` |
+| `posthog:apm-services-list` | List distinct service names |
+| `posthog:apm-attributes-list` | List span or resource attribute keys |
+| `posthog:apm-attribute-values-list` | List values for a specific attribute key |
+
+For aggregates or joins not covered by these tools, `posthog:execute-sql` may be appropriate once the span schema is confirmed for the project.
+
+## Span data model
+
+| Field | Description |
+| ---------------- | --------------------------------------------------------------------- |
+| `trace_id` | Hex ID linking spans in one trace |
+| `span_id` | Hex ID for this span |
+| `parent_span_id` | Parent span hex ID (null for root) |
+| `name` | Operation name (e.g. `HTTP GET /api/users`) |
+| `kind` | 0=Unspecified, 1=Internal, 2=Server, 3=Client, 4=Producer, 5=Consumer |
+| `service_name` | Emitting service |
+| `status_code` | 0=Unset, 1=OK, 2=Error |
+| `timestamp` | Start time (ISO 8601) |
+| `end_time` | End time (ISO 8601) |
+| `duration_nano` | Duration in nanoseconds |
+| `is_root_span` | Whether this is the trace entry |
+
+### Property filter types (`query.filterGroup`)
+
+- `span` — built-in fields: `trace_id`, `span_id`, `duration`, `name`, `kind`, `status_code`
+- `span_attribute` — span-level attributes (e.g. `http.method`)
+- `span_resource_attribute` — resource attributes (e.g. Kubernetes labels)
+
+## Workflow: investigate slow requests
+
+1. Discover services: call `posthog:apm-services-list` with `{}` (or applicable filters per tool schema).
+2. Find slow spans: `posthog:query-apm-spans` with a `query` that filters by service and `duration` (remember nanoseconds: 1s = 1_000_000_000).
+3. Drill in: `posthog:apm-trace-get` with `{ "trace_id": "<hex from step 2>" }`.
+
+## Workflow: find error traces
+
+Use `posthog:query-apm-spans` with `query.filterGroup` on `status_code` `exact` / numeric operators as appropriate — OpenTelemetry status **2** means error.
+
+## Workflow: explore unknown attributes
+
+1. `posthog:apm-attributes-list` — narrow keys (e.g. search `"http"`).
+2. `posthog:apm-attribute-values-list` — inspect values for a chosen key.
+3. Build filters in `posthog:query-apm-spans` using the discovered keys.
+
+## Reminders
+
+- Prefer discovering attribute keys and services before guessing filters.
+- Durations in filters are in **nanoseconds**.
+- `query-apm-spans` expects a **`query`** wrapper object; defaults often assume a recent time window — tighten `query.dateRange` when the question implies it.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 86492bd36d2e..5caf9520bbed 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -284,6 +284,70 @@
"readOnlyHint": false
}
},
+ "apm-attribute-values-list": {
+ "description": "List values for a specific span or resource attribute key. Use to discover what values exist for a given attribute before building filters.",
+ "category": "Tracing",
+ "feature": "tracing",
+ "summary": "List tracing attribute values",
+ "title": "List tracing attribute values",
+ "required_scopes": ["tracing:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "tracing"
+ },
+ "apm-attributes-list": {
+ "description": "List available span or resource attribute names. Use attribute_type \"span\" for span-level attributes or \"resource\" for resource-level attributes (e.g. k8s labels). Use this to discover available attribute keys before building filters.",
+ "category": "Tracing",
+ "feature": "tracing",
+ "summary": "List tracing span attributes",
+ "title": "List tracing span attributes",
+ "required_scopes": ["tracing:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "tracing"
+ },
+ "apm-services-list": {
+ "description": "List distinct service names that have emitted trace spans. Use to discover available services before filtering spans by service name.",
+ "category": "Tracing",
+ "feature": "tracing",
+ "summary": "List tracing service names",
+ "title": "List tracing service names",
+ "required_scopes": ["tracing:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "tracing"
+ },
+ "apm-trace-get": {
+ "description": "Fetch all spans for a specific trace by its hex trace ID. Returns the full span tree for the trace including parent-child relationships, timing, and status information. Use this to inspect a specific trace in detail after discovering it via the query tool.",
+ "category": "Tracing",
+ "feature": "tracing",
+ "summary": "Retrieve trace spans",
+ "title": "Retrieve trace spans",
+ "required_scopes": ["tracing:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "tracing"
+ },
"approval-policies-list": {
"description": "List all approval policies configured for this project. Shows which actions require approval, who can approve, and bypass rules.",
"category": "Platform Features",
@@ -3441,6 +3505,22 @@
"readOnlyHint": false
}
},
+ "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, and is_root_span.\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\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).\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 HTTP status codes (list of integers).\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\nFilter to root spans only. Defaults to true. Set to false to include all spans in the trace tree.\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 child spans to prefetch per trace (1-100). Useful to get a preview of trace structure without fetching the full trace.\n\n# Examples\n\n## List recent error spans\n\n```json\n{\n \"query\": {\n \"statusCodes\": [500, 503]\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",
+ "title": "Query tracing spans",
+ "required_scopes": ["tracing:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "tracing"
+ },
"query-error-tracking-issues": {
"description": "Query error tracking issues to find, filter, and inspect errors in the project. Returns aggregated metrics per issue including occurrence count, affected users, sessions, and volume data.\n\nUse 'read-data-schema' to discover available events, actions, and properties for filters.\n\nThis is a unified query tool — use it both to list issues and to get details on a specific issue:\n\n- **List issues**: omit `issueId` to get a filtered, sorted list of error tracking issues.\n- **Get issue details**: provide `issueId` to get aggregated metrics for a single issue.\n\nUse `error-tracking-issues-retrieve` to get the full issue model (description, assignee, external references) and `error-tracking-issues-partial-update` to change status or assignee.\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\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question. Avoid adding them if the question can be addressed without additional filtering and always use the minimum set of property filters needed.\n\nIMPORTANT: Do not check if a property is set unless the user explicitly asks for it.\n\nWhen using a property filter, you should:\n\n- **Prioritize properties directly related to the context or objective of the user's query.** Avoid using properties for identification like IDs. Instead, prioritize filtering based on general properties like `$browser`, `$os`, or `$geoip_country_code`.\n- **Ensure that you find both the property group and name.** Property groups should be one of the following: event, person, session, group.\n- After selecting a property, **validate that the property value accurately reflects the intended criteria**.\n- **Find the suitable operator for type** (e.g., `contains`, `is set`).\n- If the operator requires a value, use the `read-data-schema` tool to find the property values.\n\nInfer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.\n\nSupported operators for the String type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- contains (icontains)\n- doesn't contain (not_icontains)\n- matches regex (regex)\n- doesn't match regex (not_regex)\n- is set\n- is not set\n\nSupported operators for the Numeric type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- greater than (gt)\n- less than (lt)\n- is set\n- is not set\n\nSupported operators for the DateTime type are:\n\n- equals (is_date_exact)\n- doesn't equal (is_not for existence check)\n- before (is_date_before)\n- after (is_date_after)\n- is set\n- is not set\n\nSupported operators for the Boolean type are:\n\n- equals\n- doesn't equal\n- is set\n- is not set\n\nAll operators take a single value except for `equals` and `doesn't equal` which can take one or more values (as an array).\n\n## Time period\n\nYou should not filter events by time using property filters. Instead, use the `dateRange` field. If the question doesn't mention time, the default is the last 7 days.\n\n# Parameters\n\n## issueId (optional)\n\nWhen provided, returns aggregated metrics for a single error tracking issue. When omitted, returns a paginated list of issues matching the filters.\n\n## status\n\nFilter by issue status. Available values: `active`, `resolved`, `suppressed`, `pending_release`, `archived`, `all`. Defaults to `active`.\n\n## orderBy\n\nField to sort results by: `occurrences`, `last_seen`, `first_seen`, `users`, `sessions`. Defaults to `occurrences`.\n\n## searchQuery\n\nFree-text search across exception type, message, and stack frames. Use this when the user is looking for a specific error by name or message content.\n\n## assignee\n\nFilter issues by assignee. The value is a user ID. Use this when the user asks to see errors assigned to a specific person.\n\n## filterGroup\n\nA flat list of property filters to narrow results. Each filter specifies a property key, operator, type (event/person/session/group), and value. See the \"Property filters\" section above for usage guidelines and supported operators.\n\n## volumeResolution\n\nControls the granularity of the volume chart data returned with each issue. Use `1` (default) for list views where you want a volume sparkline. Use `0` when you only need aggregate counts without volume data.\n\n## dateRange\n\nDate range to filter results. Defaults to the last 7 days (`-7d`).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps (e.g., `2024-01-15T00:00:00Z`) or relative formats: `-7d`, `-2w`, `-1m`, `-1h`, `-1mStart`, `-1yStart`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## limit / offset\n\nPagination controls. `limit` defaults to 50.\n\n# Examples\n\n## List all active errors sorted by occurrence count\n\n```json\n{}\n```\n\nAll defaults apply: `status: \"active\"`, `orderBy: \"occurrences\"`, `dateRange: { \"date_from\": \"-7d\" }`.\n\n## Search for a specific error\n\n```json\n{\n \"searchQuery\": \"TypeError: Cannot read property\",\n \"limit\": 10\n}\n```\n\n## Get details for a specific issue\n\n```json\n{\n \"issueId\": \"01234567-89ab-cdef-0123-456789abcdef\",\n \"volumeResolution\": 0\n}\n```\n\n## List resolved errors from the last 30 days\n\n```json\n{\n \"status\": \"resolved\",\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"orderBy\": \"last_seen\"\n}\n```\n\n## Find most recent errors\n\n```json\n{\n \"orderBy\": \"first_seen\",\n \"orderDirection\": \"DESC\",\n \"dateRange\": { \"date_from\": \"-24h\" }\n}\n```\n\n## Errors from Chrome users only\n\n```json\n{\n \"filterGroup\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Chrome\"] }]\n}\n```\n\n## Errors from US users in the last 30 days\n\n```json\n{\n \"filterGroup\": [{ \"key\": \"$geoip_country_code\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"US\"] }],\n \"dateRange\": { \"date_from\": \"-30d\" }\n}\n```\n\n# Session recordings\n\nEach error issue is linked to sessions via `$session_id` on the underlying `$exception` events. When a user asks \"what were they doing,\" \"can I see what happened,\" or wants visual context for an error, fetch the session recording.\n\nIf you have specific `$session_id` values from event data, use `query-session-recordings-list` with the `session_ids` parameter to fetch multiple recordings in a single call. Otherwise, use `query-session-recordings-list` with an event filter for `$exception` matching the error. If a specific person is involved, also filter by `person_uuid` to see all their sessions. If no person context is available, filter by `$exception` alone to find all sessions with that error. Use `date_from` to match the issue's time range — e.g., if the error was first seen 10 days ago, set `date_from` accordingly so recordings from that period are included.\n\n# Reminders\n\n- Ensure that any properties included are directly relevant to the context and objectives of the user's question. Avoid unnecessary or unrelated details.\n- Avoid overcomplicating the response with excessive property filters. Focus on the simplest solution.",
"category": "Error tracking",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 202504160378..347ba4d74e85 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -301,6 +301,70 @@
"readOnlyHint": false
}
},
+ "apm-attribute-values-list": {
+ "description": "List values for a specific span or resource attribute key. Use to discover what values exist for a given attribute before building filters.",
+ "category": "Tracing",
+ "feature": "tracing",
+ "summary": "List tracing attribute values",
+ "title": "List tracing attribute values",
+ "required_scopes": ["tracing:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "tracing"
+ },
+ "apm-attributes-list": {
+ "description": "List available span or resource attribute names. Use attribute_type \"span\" for span-level attributes or \"resource\" for resource-level attributes (e.g. k8s labels). Use this to discover available attribute keys before building filters.",
+ "category": "Tracing",
+ "feature": "tracing",
+ "summary": "List tracing span attributes",
+ "title": "List tracing span attributes",
+ "required_scopes": ["tracing:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "tracing"
+ },
+ "apm-services-list": {
+ "description": "List distinct service names that have emitted trace spans. Use to discover available services before filtering spans by service name.",
+ "category": "Tracing",
+ "feature": "tracing",
+ "summary": "List tracing service names",
+ "title": "List tracing service names",
+ "required_scopes": ["tracing:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "tracing"
+ },
+ "apm-trace-get": {
+ "description": "Fetch all spans for a specific trace by its hex trace ID. Returns the full span tree for the trace including parent-child relationships, timing, and status information. Use this to inspect a specific trace in detail after discovering it via the query tool.",
+ "category": "Tracing",
+ "feature": "tracing",
+ "summary": "Retrieve trace spans",
+ "title": "Retrieve trace spans",
+ "required_scopes": ["tracing:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "tracing"
+ },
"approval-policies-list": {
"description": "List all approval policies configured for this project. Shows which actions require approval, who can approve, and bypass rules.",
"category": "Platform Features",
@@ -3799,6 +3863,22 @@
"readOnlyHint": false
}
},
+ "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, and is_root_span.\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\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).\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 HTTP status codes (list of integers).\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\nFilter to root spans only. Defaults to true. Set to false to include all spans in the trace tree.\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 child spans to prefetch per trace (1-100). Useful to get a preview of trace structure without fetching the full trace.\n\n# Examples\n\n## List recent error spans\n\n```json\n{\n \"query\": {\n \"statusCodes\": [500, 503]\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",
+ "title": "Query tracing spans",
+ "required_scopes": ["tracing:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "tracing"
+ },
"query-error-tracking-issues": {
"description": "Query error tracking issues to find, filter, and inspect errors in the project. Returns aggregated metrics per issue including occurrence count, affected users, sessions, and volume data.\n\nUse 'read-data-schema' to discover available events, actions, and properties for filters.\n\nThis is a unified query tool — use it both to list issues and to get details on a specific issue:\n\n- **List issues**: omit `issueId` to get a filtered, sorted list of error tracking issues.\n- **Get issue details**: provide `issueId` to get aggregated metrics for a single issue.\n\nUse `error-tracking-issues-retrieve` to get the full issue model (description, assignee, external references) and `error-tracking-issues-partial-update` to change status or assignee.\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\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question. Avoid adding them if the question can be addressed without additional filtering and always use the minimum set of property filters needed.\n\nIMPORTANT: Do not check if a property is set unless the user explicitly asks for it.\n\nWhen using a property filter, you should:\n\n- **Prioritize properties directly related to the context or objective of the user's query.** Avoid using properties for identification like IDs. Instead, prioritize filtering based on general properties like `$browser`, `$os`, or `$geoip_country_code`.\n- **Ensure that you find both the property group and name.** Property groups should be one of the following: event, person, session, group.\n- After selecting a property, **validate that the property value accurately reflects the intended criteria**.\n- **Find the suitable operator for type** (e.g., `contains`, `is set`).\n- If the operator requires a value, use the `read-data-schema` tool to find the property values.\n\nInfer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.\n\nSupported operators for the String type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- contains (icontains)\n- doesn't contain (not_icontains)\n- matches regex (regex)\n- doesn't match regex (not_regex)\n- is set\n- is not set\n\nSupported operators for the Numeric type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- greater than (gt)\n- less than (lt)\n- is set\n- is not set\n\nSupported operators for the DateTime type are:\n\n- equals (is_date_exact)\n- doesn't equal (is_not for existence check)\n- before (is_date_before)\n- after (is_date_after)\n- is set\n- is not set\n\nSupported operators for the Boolean type are:\n\n- equals\n- doesn't equal\n- is set\n- is not set\n\nAll operators take a single value except for `equals` and `doesn't equal` which can take one or more values (as an array).\n\n## Time period\n\nYou should not filter events by time using property filters. Instead, use the `dateRange` field. If the question doesn't mention time, the default is the last 7 days.\n\n# Parameters\n\n## issueId (optional)\n\nWhen provided, returns aggregated metrics for a single error tracking issue. When omitted, returns a paginated list of issues matching the filters.\n\n## status\n\nFilter by issue status. Available values: `active`, `resolved`, `suppressed`, `pending_release`, `archived`, `all`. Defaults to `active`.\n\n## orderBy\n\nField to sort results by: `occurrences`, `last_seen`, `first_seen`, `users`, `sessions`. Defaults to `occurrences`.\n\n## searchQuery\n\nFree-text search across exception type, message, and stack frames. Use this when the user is looking for a specific error by name or message content.\n\n## assignee\n\nFilter issues by assignee. The value is a user ID. Use this when the user asks to see errors assigned to a specific person.\n\n## filterGroup\n\nA flat list of property filters to narrow results. Each filter specifies a property key, operator, type (event/person/session/group), and value. See the \"Property filters\" section above for usage guidelines and supported operators.\n\n## volumeResolution\n\nControls the granularity of the volume chart data returned with each issue. Use `1` (default) for list views where you want a volume sparkline. Use `0` when you only need aggregate counts without volume data.\n\n## dateRange\n\nDate range to filter results. Defaults to the last 7 days (`-7d`).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps (e.g., `2024-01-15T00:00:00Z`) or relative formats: `-7d`, `-2w`, `-1m`, `-1h`, `-1mStart`, `-1yStart`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## limit / offset\n\nPagination controls. `limit` defaults to 50.\n\n# Examples\n\n## List all active errors sorted by occurrence count\n\n```json\n{}\n```\n\nAll defaults apply: `status: \"active\"`, `orderBy: \"occurrences\"`, `dateRange: { \"date_from\": \"-7d\" }`.\n\n## Search for a specific error\n\n```json\n{\n \"searchQuery\": \"TypeError: Cannot read property\",\n \"limit\": 10\n}\n```\n\n## Get details for a specific issue\n\n```json\n{\n \"issueId\": \"01234567-89ab-cdef-0123-456789abcdef\",\n \"volumeResolution\": 0\n}\n```\n\n## List resolved errors from the last 30 days\n\n```json\n{\n \"status\": \"resolved\",\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"orderBy\": \"last_seen\"\n}\n```\n\n## Find most recent errors\n\n```json\n{\n \"orderBy\": \"first_seen\",\n \"orderDirection\": \"DESC\",\n \"dateRange\": { \"date_from\": \"-24h\" }\n}\n```\n\n## Errors from Chrome users only\n\n```json\n{\n \"filterGroup\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Chrome\"] }]\n}\n```\n\n## Errors from US users in the last 30 days\n\n```json\n{\n \"filterGroup\": [{ \"key\": \"$geoip_country_code\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"US\"] }],\n \"dateRange\": { \"date_from\": \"-30d\" }\n}\n```\n\n# Session recordings\n\nEach error issue is linked to sessions via `$session_id` on the underlying `$exception` events. When a user asks \"what were they doing,\" \"can I see what happened,\" or wants visual context for an error, fetch the session recording.\n\nIf you have specific `$session_id` values from event data, use `query-session-recordings-list` with the `session_ids` parameter to fetch multiple recordings in a single call. Otherwise, use `query-session-recordings-list` with an event filter for `$exception` matching the error. If a specific person is involved, also filter by `person_uuid` to see all their sessions. If no person context is available, filter by `$exception` alone to find all sessions with that error. Use `date_from` to match the issue's time range — e.g., if the error was first seen 10 days ago, set `date_from` accordingly so recordings from that period are included.\n\n# Reminders\n\n- Ensure that any properties included are directly relevant to the context and objectives of the user's question. Avoid unnecessary or unrelated details.\n- Avoid overcomplicating the response with excessive property filters. Focus on the simplest solution.",
"category": "Error tracking",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 560e4399cc97..3e6bd0dbfc41 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -38199,11 +38199,128 @@ export namespace Schemas {
refreshing: boolean;
}
+ /**
+ * * `span` - span
+ * `span_attribute` - span_attribute
+ * `span_resource_attribute` - span_resource_attribute
+ */
+ export type _SpanPropertyFilterTypeEnum = typeof _SpanPropertyFilterTypeEnum[keyof typeof _SpanPropertyFilterTypeEnum];
+
+
+ export const _SpanPropertyFilterTypeEnum = {
+ Span: 'span',
+ SpanAttribute: 'span_attribute',
+ SpanResourceAttribute: 'span_resource_attribute',
+ } as const;
+
+ /**
+ * * `exact` - exact
+ * `is_not` - is_not
+ * `icontains` - icontains
+ * `not_icontains` - not_icontains
+ * `regex` - regex
+ * `not_regex` - not_regex
+ * `gt` - gt
+ * `lt` - lt
+ * `is_set` - is_set
+ * `is_not_set` - is_not_set
+ */
+ export type _SpanPropertyFilterOperatorEnum = typeof _SpanPropertyFilterOperatorEnum[keyof typeof _SpanPropertyFilterOperatorEnum];
+
+
+ export const _SpanPropertyFilterOperatorEnum = {
+ Exact: 'exact',
+ IsNot: 'is_not',
+ Icontains: 'icontains',
+ NotIcontains: 'not_icontains',
+ Regex: 'regex',
+ NotRegex: 'not_regex',
+ Gt: 'gt',
+ Lt: 'lt',
+ IsSet: 'is_set',
+ IsNotSet: 'is_not_set',
+ } as const;
+
+ export interface _SpanPropertyFilter {
+ /** 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"). */
+ key: string;
+ /** "span" filters built-in span fields. "span_attribute" filters span-level attributes. "span_resource_attribute" filters resource-level attributes.
+
+ * `span` - span
+ * `span_attribute` - span_attribute
+ * `span_resource_attribute` - span_resource_attribute */
+ type: _SpanPropertyFilterTypeEnum;
+ /** Comparison operator.
+
+ * `exact` - exact
+ * `is_not` - is_not
+ * `icontains` - icontains
+ * `not_icontains` - not_icontains
+ * `regex` - regex
+ * `not_regex` - not_regex
+ * `gt` - gt
+ * `lt` - lt
+ * `is_set` - is_set
+ * `is_not_set` - is_not_set */
+ operator: _SpanPropertyFilterOperatorEnum;
+ /** Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators. */
+ value?: unknown | null;
+ }
+
export interface _SymbolSetDownloadResponse {
/** Presigned URL to download the source map file. Use immediately; expires after one hour. */
url: string;
}
+ export interface _TracingDateRange {
+ /**
+ * Start of the date range. Accepts ISO 8601 timestamps or relative formats: -1h, -6h, -1d, -7d, etc.
+ * @nullable
+ */
+ date_from?: string | null;
+ /**
+ * End of the date range. Same format as date_from. Omit or null for "now".
+ * @nullable
+ */
+ date_to?: string | null;
+ }
+
+ export interface _TracingQueryBody {
+ /** Date range for the query. Defaults to last hour. */
+ dateRange?: _TracingDateRange;
+ /** Filter by service names. */
+ serviceNames?: string[];
+ /** Filter by HTTP status codes. */
+ statusCodes?: number[];
+ /** Order results by timestamp. Defaults to latest.
+
+ * `latest` - latest
+ * `earliest` - earliest */
+ orderBy?: OrderByEnum;
+ /** Property filters for the query. */
+ filterGroup?: _SpanPropertyFilter[];
+ /** Filter to a specific trace ID (hex string). */
+ traceId?: string;
+ /** Max results (1-1000). Defaults to 100. */
+ limit?: number;
+ /** Pagination cursor from previous response. */
+ after?: string;
+ /** Filter to root spans only. Defaults to true. */
+ rootSpans?: boolean;
+ /** Number of child spans to prefetch per trace (1-100). */
+ prefetchSpans?: number;
+ }
+
+ export interface _TracingQueryRequest {
+ /** The tracing spans query to execute. */
+ query: _TracingQueryBody;
+ }
+
+ export interface _TracingTraceRequest {
+ /** Date range for the query. Defaults to last 24 hours. */
+ dateRange?: _TracingDateRange;
+ }
+
export type EnvironmentsAlertsListParams = {
/**
* Number of results to return per page.
@@ -41607,6 +41724,94 @@ export namespace Schemas {
search?: string;
};
+ export type TracingSpansAttributesRetrieveParams = {
+ /**
+ * Type of attributes: "span" for span attributes, "resource" for resource attributes.
+
+ * `span` - span
+ * `resource` - resource
+ * @minLength 1
+ */
+ attribute_type?: TracingSpansAttributesRetrieveAttributeType;
+ /**
+ * Max results (default: 100).
+ * @minimum 1
+ * @maximum 100
+ */
+ limit?: number;
+ /**
+ * Pagination offset (default: 0).
+ * @minimum 0
+ */
+ offset?: number;
+ /**
+ * Search filter for attribute names.
+ * @minLength 1
+ */
+ search?: string;
+ };
+
+ export type TracingSpansAttributesRetrieveAttributeType = typeof TracingSpansAttributesRetrieveAttributeType[keyof typeof TracingSpansAttributesRetrieveAttributeType];
+
+
+ export const TracingSpansAttributesRetrieveAttributeType = {
+ Span: 'span',
+ Resource: 'resource',
+ } as const;
+
+ export type TracingSpansServiceNamesRetrieveParams = {
+ /**
+ * JSON-encoded date range, e.g. '{"date_from": "-1h"}'.
+ * @minLength 1
+ */
+ dateRange?: string;
+ /**
+ * Search filter for service names.
+ * @minLength 1
+ */
+ search?: string;
+ };
+
+ export type TracingSpansValuesRetrieveParams = {
+ /**
+ * Type of attribute: "span" or "resource".
+
+ * `span` - span
+ * `resource` - resource
+ * @minLength 1
+ */
+ attribute_type?: TracingSpansValuesRetrieveAttributeType;
+ /**
+ * The attribute key to get values for.
+ * @minLength 1
+ */
+ key: string;
+ /**
+ * Max results (default: 100).
+ * @minimum 1
+ * @maximum 100
+ */
+ limit?: number;
+ /**
+ * Pagination offset (default: 0).
+ * @minimum 0
+ */
+ offset?: number;
+ /**
+ * Search filter for attribute values.
+ * @minLength 1
+ */
+ value?: string;
+ };
+
+ export type TracingSpansValuesRetrieveAttributeType = typeof TracingSpansValuesRetrieveAttributeType[keyof typeof TracingSpansValuesRetrieveAttributeType];
+
+
+ export const TracingSpansValuesRetrieveAttributeType = {
+ Span: 'span',
+ Resource: 'resource',
+ } as const;
+
export type UserInterviewsListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.ts
new file mode 100644
index 000000000000..97c51565265d
--- /dev/null
+++ b/services/mcp/src/generated/tracing/api.ts
@@ -0,0 +1,215 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * MCP service uses these Zod schemas for generated tool handlers.
+ * To regenerate: hogli build:openapi
+ *
+ * PostHog API - MCP 5 enabled ops
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+export const TracingSpansAttributesRetrieveParams = /* @__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 tracingSpansAttributesRetrieveQueryLimitMax = 100
+
+export const tracingSpansAttributesRetrieveQueryOffsetMin = 0
+
+export const TracingSpansAttributesRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ attribute_type: zod
+ .enum(['span', 'resource'])
+ .optional()
+ .describe(
+ 'Type of attributes: "span" for span attributes, "resource" for resource attributes.\n\n* `span` - span\n* `resource` - resource'
+ ),
+ limit: zod
+ .number()
+ .min(1)
+ .max(tracingSpansAttributesRetrieveQueryLimitMax)
+ .optional()
+ .describe('Max results (default: 100).'),
+ offset: zod
+ .number()
+ .min(tracingSpansAttributesRetrieveQueryOffsetMin)
+ .optional()
+ .describe('Pagination offset (default: 0).'),
+ search: zod.string().min(1).optional().describe('Search filter for attribute names.'),
+})
+
+export const TracingSpansQueryCreateParams = /* @__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 tracingSpansQueryCreateBodyQueryOneFilterGroupDefault = []
+export const tracingSpansQueryCreateBodyQueryOneLimitDefault = 100
+export const tracingSpansQueryCreateBodyQueryOneRootSpansDefault = true
+
+export const TracingSpansQueryCreateBody = /* @__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 query. 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.'),
+ orderBy: zod
+ .enum(['latest', 'earliest'])
+ .describe('* `latest` - latest\n* `earliest` - earliest')
+ .optional()
+ .describe(
+ 'Order results by timestamp. Defaults to latest.\n\n* `latest` - latest\n* `earliest` - earliest'
+ ),
+ 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()
+ .nullish()
+ .describe(
+ 'Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators.'
+ ),
+ })
+ )
+ .default(tracingSpansQueryCreateBodyQueryOneFilterGroupDefault)
+ .describe('Property filters for the query.'),
+ traceId: zod.string().optional().describe('Filter to a specific trace ID (hex string).'),
+ limit: zod
+ .number()
+ .default(tracingSpansQueryCreateBodyQueryOneLimitDefault)
+ .describe('Max results (1-1000). Defaults to 100.'),
+ after: zod.string().optional().describe('Pagination cursor from previous response.'),
+ rootSpans: zod
+ .boolean()
+ .default(tracingSpansQueryCreateBodyQueryOneRootSpansDefault)
+ .describe('Filter to root spans only. Defaults to true.'),
+ prefetchSpans: zod.number().optional().describe('Number of child spans to prefetch per trace (1-100).'),
+ })
+ .describe('The tracing spans query to execute.'),
+})
+
+export const TracingSpansServiceNamesRetrieveParams = /* @__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 TracingSpansServiceNamesRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ dateRange: zod.string().min(1).optional().describe('JSON-encoded date range, e.g. \'{"date_from": "-1h"}\'.'),
+ search: zod.string().min(1).optional().describe('Search filter for service names.'),
+})
+
+export const tracingSpansTraceCreatePathTraceIdRegExp = new RegExp('^[a-zA-Z0-9]+$')
+
+export const TracingSpansTraceCreateParams = /* @__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/."
+ ),
+ trace_id: zod.string().regex(tracingSpansTraceCreatePathTraceIdRegExp),
+})
+
+export const TracingSpansTraceCreateBody = /* @__PURE__ */ 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 query. Defaults to last 24 hours.'),
+})
+
+export const TracingSpansValuesRetrieveParams = /* @__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 tracingSpansValuesRetrieveQueryLimitMax = 100
+
+export const tracingSpansValuesRetrieveQueryOffsetMin = 0
+
+export const TracingSpansValuesRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ attribute_type: zod
+ .enum(['span', 'resource'])
+ .optional()
+ .describe('Type of attribute: "span" or "resource".\n\n* `span` - span\n* `resource` - resource'),
+ key: zod.string().min(1).describe('The attribute key to get values for.'),
+ limit: zod
+ .number()
+ .min(1)
+ .max(tracingSpansValuesRetrieveQueryLimitMax)
+ .optional()
+ .describe('Max results (default: 100).'),
+ offset: zod
+ .number()
+ .min(tracingSpansValuesRetrieveQueryOffsetMin)
+ .optional()
+ .describe('Pagination offset (default: 0).'),
+ value: zod.string().min(1).optional().describe('Search filter for attribute values.'),
+})
diff --git a/services/mcp/src/resources/ui-apps.generated.ts b/services/mcp/src/resources/ui-apps.generated.ts
index fd40905292ae..bbf798d5a9c0 100644
--- a/services/mcp/src/resources/ui-apps.generated.ts
+++ b/services/mcp/src/resources/ui-apps.generated.ts
@@ -22,6 +22,8 @@ export const SURVEY_RESOURCE_URI = 'ui://posthog/survey.html'
export const SURVEY_GLOBAL_STATS_RESOURCE_URI = 'ui://posthog/survey-global-stats.html'
export const SURVEY_LIST_RESOURCE_URI = 'ui://posthog/survey-list.html'
export const SURVEY_STATS_RESOURCE_URI = 'ui://posthog/survey-stats.html'
+export const TRACE_SPAN_RESOURCE_URI = 'ui://posthog/trace-span.html'
+export const TRACE_SPAN_LIST_RESOURCE_URI = 'ui://posthog/trace-span-list.html'
export const WORKFLOW_RESOURCE_URI = 'ui://posthog/workflow.html'
export const WORKFLOW_LIST_RESOURCE_URI = 'ui://posthog/workflow-list.html'
@@ -48,6 +50,8 @@ export type UiAppKey =
| 'survey-global-stats'
| 'survey-list'
| 'survey-stats'
+ | 'trace-span'
+ | 'trace-span-list'
| 'workflow'
| 'workflow-list'
@@ -74,6 +78,8 @@ export const URI_MAP: Record<UiAppKey, string> = {
'survey-global-stats': SURVEY_GLOBAL_STATS_RESOURCE_URI,
'survey-list': SURVEY_LIST_RESOURCE_URI,
'survey-stats': SURVEY_STATS_RESOURCE_URI,
+ 'trace-span': TRACE_SPAN_RESOURCE_URI,
+ 'trace-span-list': TRACE_SPAN_LIST_RESOURCE_URI,
workflow: WORKFLOW_RESOURCE_URI,
'workflow-list': WORKFLOW_LIST_RESOURCE_URI,
}
@@ -216,6 +222,18 @@ export const UI_APPS: Array<{
description: 'Survey Stats detail view',
appDir: 'generated/survey-stats',
},
+ {
+ name: 'PostHog Trace Span',
+ uri: TRACE_SPAN_RESOURCE_URI,
+ description: 'Trace Span detail view',
+ appDir: 'generated/trace-span',
+ },
+ {
+ name: 'PostHog Trace Span List',
+ uri: TRACE_SPAN_LIST_RESOURCE_URI,
+ description: 'Trace Span List view',
+ appDir: 'generated/trace-span-list',
+ },
{
name: 'PostHog Workflow',
uri: WORKFLOW_RESOURCE_URI,
diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.ts
index b6da08981d20..f8ea415e99fa 100644
--- a/services/mcp/src/tools/generated/index.ts
+++ b/services/mcp/src/tools/generated/index.ts
@@ -31,6 +31,7 @@ import { GENERATED_TOOLS as replay } from './replay'
import { GENERATED_TOOLS as sdk_doctor } from './sdk_doctor'
import { GENERATED_TOOLS as signals } from './signals'
import { GENERATED_TOOLS as surveys } from './surveys'
+import { GENERATED_TOOLS as tracing } from './tracing'
import { GENERATED_TOOLS as visual_review } from './visual_review'
import { GENERATED_TOOLS as web_analytics } from './web_analytics'
import { GENERATED_TOOLS as workflows } from './workflows'
@@ -66,6 +67,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =
...sdk_doctor,
...signals,
...surveys,
+ ...tracing,
...visual_review,
...web_analytics,
...workflows,
diff --git a/services/mcp/src/tools/generated/tracing.ts b/services/mcp/src/tools/generated/tracing.ts
new file mode 100644
index 000000000000..e8ad17f485bf
--- /dev/null
+++ b/services/mcp/src/tools/generated/tracing.ts
@@ -0,0 +1,133 @@
+// AUTO-GENERATED from products/tracing/mcp/tools.yaml + OpenAPI — do not edit
+import { z } from 'zod'
+
+import {
+ TracingSpansAttributesRetrieveQueryParams,
+ TracingSpansQueryCreateBody,
+ TracingSpansServiceNamesRetrieveQueryParams,
+ TracingSpansTraceCreateBody,
+ TracingSpansTraceCreateParams,
+ TracingSpansValuesRetrieveQueryParams,
+} from '@/generated/tracing/api'
+import { withUiApp } from '@/resources/ui-apps'
+import { pickResponseFields } from '@/tools/tool-utils'
+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+
+const ApmAttributeValuesListSchema = TracingSpansValuesRetrieveQueryParams
+
+const apmAttributeValuesList = (): ToolBase<typeof ApmAttributeValuesListSchema, unknown> => ({
+ name: 'apm-attribute-values-list',
+ schema: ApmAttributeValuesListSchema,
+ handler: async (context: Context, params: z.infer<typeof ApmAttributeValuesListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'GET',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/tracing/spans/values/`,
+ query: {
+ attribute_type: params.attribute_type,
+ key: params.key,
+ limit: params.limit,
+ offset: params.offset,
+ value: params.value,
+ },
+ })
+ const filtered = pickResponseFields(result, ['results']) as typeof result
+ return filtered
+ },
+})
+
+const ApmAttributesListSchema = TracingSpansAttributesRetrieveQueryParams
+
+const apmAttributesList = (): ToolBase<typeof ApmAttributesListSchema, unknown> => ({
+ name: 'apm-attributes-list',
+ schema: ApmAttributesListSchema,
+ handler: async (context: Context, params: z.infer<typeof ApmAttributesListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'GET',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/tracing/spans/attributes/`,
+ query: {
+ attribute_type: params.attribute_type,
+ limit: params.limit,
+ offset: params.offset,
+ search: params.search,
+ },
+ })
+ const filtered = pickResponseFields(result, ['results', 'count']) as typeof result
+ return filtered
+ },
+})
+
+const ApmServicesListSchema = TracingSpansServiceNamesRetrieveQueryParams
+
+const apmServicesList = (): ToolBase<typeof ApmServicesListSchema, unknown> => ({
+ name: 'apm-services-list',
+ schema: ApmServicesListSchema,
+ handler: async (context: Context, params: z.infer<typeof ApmServicesListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'GET',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/tracing/spans/service-names/`,
+ query: {
+ dateRange: params.dateRange,
+ search: params.search,
+ },
+ })
+ const filtered = pickResponseFields(result, ['results']) as typeof result
+ return filtered
+ },
+})
+
+const ApmTraceGetSchema = TracingSpansTraceCreateParams.omit({ project_id: true }).extend(
+ TracingSpansTraceCreateBody.shape
+)
+
+const apmTraceGet = (): ToolBase<typeof ApmTraceGetSchema, unknown> =>
+ withUiApp('trace-span-list', {
+ name: 'apm-trace-get',
+ schema: ApmTraceGetSchema,
+ handler: async (context: Context, params: z.infer<typeof ApmTraceGetSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.dateRange !== undefined) {
+ body['dateRange'] = params.dateRange
+ }
+ const result = await context.api.request<unknown>({
+ method: 'POST',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/tracing/spans/trace/${encodeURIComponent(String(params.trace_id))}/`,
+ body,
+ })
+ const filtered = pickResponseFields(result, ['results']) as typeof result
+ return filtered
+ },
+ })
+
+const QueryApmSpansSchema = TracingSpansQueryCreateBody
+
+const queryApmSpans = (): ToolBase<typeof QueryApmSpansSchema, unknown> =>
+ withUiApp('trace-span-list', {
+ name: 'query-apm-spans',
+ schema: QueryApmSpansSchema,
+ handler: async (context: Context, params: z.infer<typeof QueryApmSpansSchema>) => {
+ 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<unknown>({
+ method: 'POST',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/tracing/spans/query/`,
+ body,
+ })
+ const filtered = pickResponseFields(result, ['results']) as typeof result
+ return filtered
+ },
+ })
+
+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'apm-attribute-values-list': apmAttributeValuesList,
+ 'apm-attributes-list': apmAttributesList,
+ 'apm-services-list': apmServicesList,
+ 'apm-trace-get': apmTraceGet,
+ 'query-apm-spans': queryApmSpans,
+}
diff --git a/services/mcp/src/ui-apps/apps/generated/trace-span-list.tsx b/services/mcp/src/ui-apps/apps/generated/trace-span-list.tsx
new file mode 100644
index 000000000000..8dd18aa4b73b
--- /dev/null
+++ b/services/mcp/src/ui-apps/apps/generated/trace-span-list.tsx
@@ -0,0 +1,61 @@
+// AUTO-GENERATED by generate-ui-apps.ts — do not edit
+import '../../styles/tailwind.css'
+
+import type { App } from '@modelcontextprotocol/ext-apps'
+import { useCallback } from 'react'
+import { createRoot } from 'react-dom/client'
+
+import { type TraceSpanData, type TraceSpanListData, TraceSpanListView } from 'products/tracing/mcp/apps'
+
+import { AppWrapper } from '../../components/AppWrapper'
+
+function TraceSpanListApp(): JSX.Element {
+ return (
+ <AppWrapper<TraceSpanListData> appName="PostHog Trace Span List">
+ {({ data, app }) => <TraceSpanListContent data={data!} app={app} />}
+ </AppWrapper>
+ )
+}
+
+function TraceSpanListContent({ data, app }: { data: TraceSpanListData; app: App | null }): JSX.Element {
+ const fallbackToChat = useCallback(
+ (name: string) => {
+ app?.sendMessage({
+ role: 'user',
+ content: [{ type: 'text', text: `Show me the details for trace span "${name}"` }],
+ })
+ },
+ [app]
+ )
+
+ const handleClick = useCallback(
+ async (item: TraceSpanData): Promise<TraceSpanData | null> => {
+ if (!app) {
+ fallbackToChat(item.name)
+ return null
+ }
+ try {
+ const result = await app.callServerTool({
+ name: 'apm-trace-get',
+ arguments: { trace_id: item.trace_id },
+ })
+ if (result.isError || !result.structuredContent) {
+ fallbackToChat(item.name)
+ return null
+ }
+ return result.structuredContent as unknown as TraceSpanData
+ } catch {
+ fallbackToChat(item.name)
+ return null
+ }
+ },
+ [app, fallbackToChat]
+ )
+
+ return <TraceSpanListView data={data} onSpanClick={handleClick} />
+}
+
+const container = document.getElementById('root')
+if (container) {
+ createRoot(container).render(<TraceSpanListApp />)
+}
diff --git a/services/mcp/src/ui-apps/apps/generated/trace-span.tsx b/services/mcp/src/ui-apps/apps/generated/trace-span.tsx
new file mode 100644
index 000000000000..0e535f825430
--- /dev/null
+++ b/services/mcp/src/ui-apps/apps/generated/trace-span.tsx
@@ -0,0 +1,21 @@
+// AUTO-GENERATED by generate-ui-apps.ts — do not edit
+import '../../styles/tailwind.css'
+
+import { createRoot } from 'react-dom/client'
+
+import { type TraceSpanData, TraceSpanView } from 'products/tracing/mcp/apps'
+
+import { AppWrapper } from '../../components/AppWrapper'
+
+function TraceSpanApp(): JSX.Element {
+ return (
+ <AppWrapper<TraceSpanData> appName="PostHog Trace Span">
+ {({ data }) => <TraceSpanView data={data!} />}
+ </AppWrapper>
+ )
+}
+
+const container = document.getElementById('root')
+if (container) {
+ createRoot(container).render(<TraceSpanApp />)
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-attribute-values-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-attribute-values-list.json
new file mode 100644
index 000000000000..dab37453b3e7
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-attribute-values-list.json
@@ -0,0 +1,33 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "attribute_type": {
+ "description": "Type of attribute: \"span\" or \"resource\".\n\n* `span` - span\n* `resource` - resource",
+ "enum": ["span", "resource"],
+ "type": "string"
+ },
+ "key": {
+ "description": "The attribute key to get values for.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "limit": {
+ "description": "Max results (default: 100).",
+ "maximum": 100,
+ "minimum": 1,
+ "type": "number"
+ },
+ "offset": {
+ "description": "Pagination offset (default: 0).",
+ "minimum": 0,
+ "type": "number"
+ },
+ "value": {
+ "description": "Search filter for attribute values.",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["key"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-attributes-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-attributes-list.json
new file mode 100644
index 000000000000..067cb0ffad15
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-attributes-list.json
@@ -0,0 +1,27 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "attribute_type": {
+ "description": "Type of attributes: \"span\" for span attributes, \"resource\" for resource attributes.\n\n* `span` - span\n* `resource` - resource",
+ "enum": ["span", "resource"],
+ "type": "string"
+ },
+ "limit": {
+ "description": "Max results (default: 100).",
+ "maximum": 100,
+ "minimum": 1,
+ "type": "number"
+ },
+ "offset": {
+ "description": "Pagination offset (default: 0).",
+ "minimum": 0,
+ "type": "number"
+ },
+ "search": {
+ "description": "Search filter for attribute names.",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-services-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-services-list.json
new file mode 100644
index 000000000000..2520e54f4632
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-services-list.json
@@ -0,0 +1,16 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "dateRange": {
+ "description": "JSON-encoded date range, e.g. '{\"date_from\": \"-1h\"}'.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "search": {
+ "description": "Search filter for service names.",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-trace-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-trace-get.json
new file mode 100644
index 000000000000..1e44cd2bce7d
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-trace-get.json
@@ -0,0 +1,39 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "dateRange": {
+ "description": "Date range for the query. Defaults to last 24 hours.",
+ "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"
+ },
+ "trace_id": {
+ "pattern": "^[a-zA-Z0-9]+$",
+ "type": "string"
+ }
+ },
+ "required": ["trace_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-apm-spans.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-apm-spans.json
new file mode 100644
index 000000000000..63e2991a4b5f
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/query-apm-spans.json
@@ -0,0 +1,127 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "query": {
+ "description": "The tracing spans query to execute.",
+ "properties": {
+ "after": {
+ "description": "Pagination cursor from previous response.",
+ "type": "string"
+ },
+ "dateRange": {
+ "description": "Date range for the query. 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 query.",
+ "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": {
+ "anyOf": [
+ {},
+ {
+ "type": "null"
+ }
+ ],
+ "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"
+ },
+ "limit": {
+ "default": 100,
+ "description": "Max results (1-1000). Defaults to 100.",
+ "type": "number"
+ },
+ "orderBy": {
+ "description": "Order results by timestamp. Defaults to latest.\n\n* `latest` - latest\n* `earliest` - earliest",
+ "enum": ["latest", "earliest"],
+ "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": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "statusCodes": {
+ "description": "Filter by HTTP status codes.",
+ "items": {
+ "type": "number"
+ },
+ "type": "array"
+ },
+ "traceId": {
+ "description": "Filter to a specific trace ID (hex string).",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ }
+ },
+ "required": ["query"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 2e8b8607186f..0483b2a65ef5 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -639,11 +639,12 @@ describe('Tool Filtering - Feature Flags', () => {
expect.arrayContaining([
'logs-alerting',
'replay-video-based-summarization',
+ 'tracing',
'visual-review',
'mcp-feedback-tool',
])
)
- expect(flags).toHaveLength(4)
+ expect(flags).toHaveLength(5)
})
// Test the filtering logic with a direct unit test approach using
diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
index de65d5df1c76..11bbda4b1959 100644
--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts
+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
@@ -106,10 +106,9 @@ describe('Tool schema snapshots', () => {
it('snapshots runtime tool schemas as common + version deltas', async () => {
const shouldUpdateSnapshots = isSnapshotUpdateAll()
const root = path.resolve(__dirname, '__snapshots__', 'tool-schemas')
- // Enable the agent-feedback gating flag so its snapshot is captured. Other flag-gated
- // tools (logs-alerts, visual-review) remain excluded so this test stays scoped to the
- // tool surface that was previously snapshotted.
- const featureFlags = { 'mcp-feedback-tool': true }
+ // Enable flag-gated tools we snapshot here: agent-feedback, tracing (APM spans). Other
+ // flag-gated tools (logs-alerts, visual-review, etc.) stay off to keep the surface stable.
+ const featureFlags = { 'mcp-feedback-tool': true, tracing: true }
const v1Tools = [...(await getToolsFromContext(context, { version: 1, featureFlags }))].sort((a, b) =>
a.name.localeCompare(b.name)
)
diff --git a/services/mcp/tests/unit/ui-apps.test.ts b/services/mcp/tests/unit/ui-apps.test.ts
index 6dbfecbd2be1..2a984d9d1708 100644
--- a/services/mcp/tests/unit/ui-apps.test.ts
+++ b/services/mcp/tests/unit/ui-apps.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import { buildAppStubHtml } from '@/resources/ui-apps'
+import { UI_APPS } from '@/resources/ui-apps.generated'
describe('ui-apps', () => {
describe('buildAppStubHtml', () => {
@@ -101,7 +102,7 @@ describe('ui-apps', () => {
await registerUiAppResources(server as any, context as any)
- expect(server.registerResource).toHaveBeenCalledTimes(24)
+ expect(server.registerResource).toHaveBeenCalledTimes(UI_APPS.length)
})
it('registers apps with correct names and URIs', async () => {