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): integrate tracing scenes with PostHog AI (#94122)

Jon McCallume181cb92c4bc
diff --git a/products/tracing/frontend/TracingAgentIntegration.tsx b/products/tracing/frontend/TracingAgentIntegration.tsx
new file mode 100644
index 000000000000..b99398dd851d
--- /dev/null
+++ b/products/tracing/frontend/TracingAgentIntegration.tsx
@@ -0,0 +1,70 @@
+import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
+import { useSceneAgentPanel } from 'scenes/max/useSceneAgentPanel'
+
+import { useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'
+
+import {
+ TRACING_AGENT_HEADLINES,
+ apmSpansQueryToViewerFilters,
+ apmTraceGetToTraceId,
+ buildTracingAgentContext,
+} from './tracingAgentContext'
+import { TRACING_SCENE_VIEWER_ID, tracingFiltersLogic } from './tracingFiltersLogic'
+import { tracingViewerLogic } from './tracingViewerLogic'
+
+/**
+ * Scene-level PostHog AI integration for the tracing viewer. Attaches the exploring-apm-traces
+ * skill, the tracing MCP tool catalog, and the live viewer state as agent context, mirrors a
+ * query-apm-spans call back onto the open viewer, and opens the trace an apm-trace-get call
+ * fetched in the drawer. Resolves the viewer instance from the enclosing BindLogic. Renders nothing.
+ */
+export function TracingAgentIntegration(): null {
+ const { filters } = useValues(tracingFiltersLogic)
+ const { setFilters } = useActions(tracingFiltersLogic)
+ const { selectedTraceId, selectedSpanId } = useValues(tracingViewerLogic)
+ const { openTrace } = useActions(tracingViewerLogic)
+
+ // Debounced so per-keystroke filter edits don't re-serialize the viewer state on every change.
+ const debouncedFilters = useDebouncedValue(filters, 500)
+ const contextItems = useMemo(
+ () =>
+ buildTracingAgentContext(
+ debouncedFilters,
+ selectedTraceId ? { traceId: selectedTraceId, spanId: selectedSpanId } : null
+ ),
+ [debouncedFilters, selectedTraceId, selectedSpanId]
+ )
+
+ useSceneAgentPanel({
+ sceneKey: 'tracing',
+ contextItems,
+ headlines: TRACING_AGENT_HEADLINES,
+ })
+
+ useMcpToolApplyBack({
+ tools: ['query-apm-spans'],
+ targetKey: `tracing-viewer:${TRACING_SCENE_VIEWER_ID}`,
+ onApply: (_event, { innerInput }) => {
+ if (!innerInput) {
+ return
+ }
+ setFilters(apmSpansQueryToViewerFilters(innerInput))
+ },
+ })
+
+ useMcpToolApplyBack({
+ tools: ['apm-trace-get'],
+ targetKey: `tracing-viewer-trace:${TRACING_SCENE_VIEWER_ID}`,
+ onApply: (_event, { innerInput }) => {
+ const traceId = innerInput ? apmTraceGetToTraceId(innerInput) : null
+ if (traceId) {
+ openTrace(traceId)
+ }
+ },
+ })
+
+ return null
+}
diff --git a/products/tracing/frontend/TracingOperationScene.tsx b/products/tracing/frontend/TracingOperationScene.tsx
index bf1c0ab9c9e0..d07593ec876e 100644
--- a/products/tracing/frontend/TracingOperationScene.tsx
+++ b/products/tracing/frontend/TracingOperationScene.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
import { IconChevronLeft, IconChevronRight } from '@posthog/icons'
import { LemonButton, LemonSegmentedButton, LemonTag, Link, SpinnerOverlay } from '@posthog/lemon-ui'
@@ -6,6 +7,7 @@ import { LemonButton, LemonSegmentedButton, LemonTag, Link, SpinnerOverlay } fro
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { TZLabel } from 'lib/components/TZLabel'
import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { useSceneAgentPanel } from 'scenes/max/useSceneAgentPanel'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -19,6 +21,7 @@ import { formatBucketLabel } from './durationBuckets'
import { OperationHistogram } from './OperationHistogram'
import { errorRate, formatErrorRate } from './OperationsTable'
import { formatDuration, TraceWaterfallView } from './TraceWaterfallView'
+import { TRACING_AGENT_HEADLINES, buildTracingOperationAgentContext } from './tracingAgentContext'
import { TracingLatencyHeatmap } from './TracingLatencyHeatmap'
import {
type OperationChartType,
@@ -90,6 +93,17 @@ export function TracingOperationScene(): JSX.Element {
const { setDateRange, setDurationSelection, setSampleIndex, selectSpan, setChartType, applyHeatmapBrush } =
useActions(tracingOperationSceneLogic)
+ const agentContextItems = useMemo(
+ () => buildTracingOperationAgentContext(serviceName, spanName, dateRange),
+ [serviceName, spanName, dateRange]
+ )
+ useSceneAgentPanel({
+ sceneKey: 'tracing-operation',
+ contextItems: agentContextItems,
+ headlines: TRACING_AGENT_HEADLINES,
+ active: !!spanName && !!serviceName,
+ })
+
if (!spanName || !serviceName) {
return (
<SceneContent>
diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsx
index c94aaa780af0..3a59021df711 100644
--- a/products/tracing/frontend/TracingScene.tsx
+++ b/products/tracing/frontend/TracingScene.tsx
@@ -26,6 +26,7 @@ import { tracingEmptyState } from './emptyState/tracingEmptyState'
import { OperationsTable } from './OperationsTable'
import { TraceCompareFlame } from './TraceCompareFlame'
import { TraceCompareTable } from './TraceCompareTable'
+import { TracingAgentIntegration } from './TracingAgentIntegration'
import { tracingConfigLogic } from './tracingConfigLogic'
import { tracingDataLogic } from './tracingDataLogic'
import { TracingDisplayBar } from './TracingDisplayBar'
@@ -60,6 +61,7 @@ export default function TracingScene(): JSX.Element {
<BindLogic logic={tracingFiltersLogic} props={{ id: TRACING_SCENE_VIEWER_ID }}>
<BindLogic logic={tracingDataLogic} props={{ id: TRACING_SCENE_VIEWER_ID }}>
<BindLogic logic={tracingViewerLogic} props={{ id: TRACING_SCENE_VIEWER_ID }}>
+ <TracingAgentIntegration />
<TracingSceneContents />
</BindLogic>
</BindLogic>
diff --git a/products/tracing/frontend/tracingAgentContext.test.ts b/products/tracing/frontend/tracingAgentContext.test.ts
new file mode 100644
index 000000000000..5574f6979eb2
--- /dev/null
+++ b/products/tracing/frontend/tracingAgentContext.test.ts
@@ -0,0 +1,114 @@
+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
+
+import { apmSpansQueryToViewerFilters, apmTraceGetToTraceId } from './tracingAgentContext'
+import { DEFAULT_DATE_RANGE } from './tracingFiltersLogic'
+
+describe('tracingAgentContext', () => {
+ const innerValues = (filterGroup: UniversalFiltersGroup): any[] =>
+ (filterGroup.values[0] as UniversalFiltersGroup).values
+
+ describe('apmSpansQueryToViewerFilters', () => {
+ it('unwraps the query object and mirrors date range, services, sort and view mode', () => {
+ const result = apmSpansQueryToViewerFilters({
+ query: {
+ dateRange: { date_from: '-6h' },
+ serviceNames: ['api-gateway'],
+ orderBy: 'duration',
+ orderDirection: 'ASC',
+ flatSpans: true,
+ },
+ })
+
+ expect(result).toMatchObject({
+ dateRange: { date_from: '-6h' },
+ serviceNames: ['api-gateway'],
+ orderBy: 'duration',
+ orderDirection: 'ASC',
+ viewMode: 'spans',
+ })
+ })
+
+ it('resets omitted fields to the viewer defaults', () => {
+ const result = apmSpansQueryToViewerFilters({ query: {} })
+
+ expect(result).toEqual({
+ dateRange: DEFAULT_DATE_RANGE,
+ serviceNames: [],
+ filterGroup: {
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.And, values: [] }],
+ },
+ orderBy: 'timestamp',
+ orderDirection: 'DESC',
+ viewMode: 'traces',
+ })
+ })
+
+ it('accepts a raw input that is not wrapped in a query object', () => {
+ const result = apmSpansQueryToViewerFilters({ dateRange: { date_from: '-1d' } })
+
+ expect(result.dateRange).toEqual({ date_from: '-1d' })
+ })
+
+ it('defaults type and operator on raw agent filters that omit them', () => {
+ const result = apmSpansQueryToViewerFilters({
+ query: { filterGroup: [{ key: 'http.method', value: 'POST' }] },
+ })
+
+ expect(innerValues(result.filterGroup!)).toEqual([
+ {
+ key: 'http.method',
+ value: 'POST',
+ type: PropertyFilterType.SpanAttribute,
+ operator: PropertyOperator.Exact,
+ },
+ ])
+ })
+
+ it('preserves an explicit type and operator on a raw filter', () => {
+ const result = apmSpansQueryToViewerFilters({
+ query: { filterGroup: [{ key: 'duration', value: '1000000000', type: 'span', operator: 'gt' }] },
+ })
+
+ expect(innerValues(result.filterGroup!)[0]).toMatchObject({ key: 'duration', type: 'span', operator: 'gt' })
+ })
+
+ it.each([
+ ['statusCodes', { statusCodes: [2, '1'] }, { key: 'status_code', value: ['2', '1'] }],
+ ['traceId', { traceId: 'abc123' }, { key: 'trace_id', value: ['abc123'] }],
+ ])('folds %s into the filter group as a span column filter', (_name, query, expected) => {
+ const result = apmSpansQueryToViewerFilters({ query })
+
+ expect(innerValues(result.filterGroup!)).toEqual([
+ { type: PropertyFilterType.Span, operator: PropertyOperator.Exact, ...expected },
+ ])
+ })
+
+ // rootSpans has no viewer facet: the span list never sends it and the backend reads an
+ // omitted value as false, so the mode the mirror picks stays a flatSpans question.
+ it.each([
+ ['rootSpans is false', { rootSpans: false }, 'traces'],
+ ['rootSpans is true', { rootSpans: true }, 'traces'],
+ ['flatSpans comes along with rootSpans', { rootSpans: true, flatSpans: true }, 'spans'],
+ ])('leaves the view mode to flatSpans when %s', (_name, query, expected) => {
+ expect(apmSpansQueryToViewerFilters({ query }).viewMode).toBe(expected)
+ })
+
+ it('ignores an orderBy the viewer cannot sort by', () => {
+ const result = apmSpansQueryToViewerFilters({ query: { orderBy: 'latest' } })
+
+ expect(result.orderBy).toBe('timestamp')
+ })
+ })
+
+ describe('apmTraceGetToTraceId', () => {
+ it.each([
+ ['a 32-char hex id', '0123456789abcdef0123456789ABCDEF', '0123456789abcdef0123456789ABCDEF'],
+ ['a short id', 'abc123', null],
+ ['a non-hex id', 'g123456789abcdef0123456789abcdef', null],
+ ['a missing id', undefined, null],
+ ])('returns %s as %p', (_name, traceId, expected) => {
+ expect(apmTraceGetToTraceId({ trace_id: traceId })).toBe(expected)
+ })
+ })
+})
diff --git a/products/tracing/frontend/tracingAgentContext.ts b/products/tracing/frontend/tracingAgentContext.ts
new file mode 100644
index 000000000000..d591066c4878
--- /dev/null
+++ b/products/tracing/frontend/tracingAgentContext.ts
@@ -0,0 +1,226 @@
+import { DateRange } from '~/queries/schema/schema-general'
+import {
+ FilterLogicalOperator,
+ PropertyFilterType,
+ PropertyOperator,
+ UniversalFiltersGroup,
+ UniversalFiltersGroupValue,
+} from '~/types'
+
+import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'
+
+import {
+ DEFAULT_DATE_RANGE,
+ DEFAULT_ORDER_BY,
+ DEFAULT_ORDER_DIRECTION,
+ DEFAULT_VIEW_MODE,
+ TracingFilters,
+ TracingOrderBy,
+ TracingOrderDirection,
+} from './tracingFiltersLogic'
+
+// Each visible chip and the hidden payload items it stands for share a dismiss group, so closing
+// the chip actually detaches the payload instead of only hiding the chip.
+const SKILL_DISMISS_GROUP = 'tracing-scene-skill'
+const VIEWER_STATE_DISMISS_GROUP = 'tracing-scene-viewer-state'
+const OPERATION_DISMISS_GROUP = 'tracing-operation-scene'
+
+const EXPLORING_APM_TRACES_SKILL = 'exploring-apm-traces'
+
+// All static strings below are our own build-time constants, which is what makes them safe to attach
+// as trusted `instructions` items. The skill body and tool schemas are not embedded: product skills
+// are installed in the agent's sandbox, and the exec MCP tool already exposes the tracing commands,
+// so naming them is enough to skip discovery.
+const PREAMBLE_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ dismissGroup: SKILL_DISMISS_GROUP,
+ value:
+ 'The user has the PostHog tracing (APM, OpenTelemetry spans) viewer open. Load the ' +
+ `${EXPLORING_APM_TRACES_SKILL} skill before your first tool call; it covers the span fields and ` +
+ 'attributes you filter on. Act through the tracing MCP tools (the exec `apm-*` commands plus ' +
+ 'query-apm-spans: query-apm-spans, apm-trace-get, apm-spans-aggregate, apm-spans-count, ' +
+ 'apm-attribute-breakdown, apm-attributes-list, apm-services-list, and the rest). Do not search for ' +
+ 'tools; use the exec `info <tool>` command when you need a full input schema.',
+}
+
+const SKILL_CHIP_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'skill',
+ key: EXPLORING_APM_TRACES_SKILL,
+ label: 'Exploring traces skill',
+ dismissGroup: SKILL_DISMISS_GROUP,
+}
+
+// Static: it names the fields the live state carries, so no user-entered filter value or trace id
+// reaches trusted context. The viewer-state item's value changes with the filters, so it always
+// re-sends.
+const APPLY_BACK_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ dismissGroup: VIEWER_STATE_DISMISS_GROUP,
+ value:
+ 'The tracing_viewer_state item is the current filter state of the open tracing viewer (date range, ' +
+ 'service names, filter group, view mode, sort) and, when a trace drawer is open, its open_trace field ' +
+ 'names the trace and span the user is looking at. When you call query-apm-spans, the query filters ' +
+ '(serviceNames, statusCodes, traceId, filterGroup, dateRange, orderBy, orderDirection, flatSpans) are also ' +
+ 'applied to the open viewer, so the user sees matching spans both in this chat and on screen. When you ' +
+ 'call apm-trace-get, that trace opens in the viewer drawer. Read tracing_viewer_state before asking the ' +
+ 'user what they are filtering on.',
+}
+
+export const TRACING_AGENT_HEADLINES: string[] = [
+ 'How can I help you investigate these traces?',
+ 'What are you trying to find in the traces?',
+]
+
+export interface TracingOpenTrace {
+ traceId: string
+ spanId: string | null
+}
+
+// The viewer state the agent cannot fetch: what the user is filtering on and which trace they have
+// open. Small by construction (a date range, service names, a filter group, and two ids), so it
+// rides along whole with no budgeting. It is an untrusted item, so user-typed filter values stay
+// intact. Dragged comparison windows are ephemeral absolute-ms positions, so only mode and preset
+// are sent.
+function serializeViewerState(filters: TracingFilters, openTrace: TracingOpenTrace | null): string {
+ return JSON.stringify({
+ dateRange: filters.dateRange,
+ serviceNames: filters.serviceNames,
+ filterGroup: filters.filterGroup,
+ viewMode: filters.viewMode,
+ orderBy: filters.orderBy,
+ orderDirection: filters.orderDirection,
+ comparison: filters.comparison ? { mode: filters.comparison.mode, preset: filters.comparison.preset } : null,
+ open_trace: openTrace ? { trace_id: openTrace.traceId, span_id: openTrace.spanId } : null,
+ })
+}
+
+/**
+ * Context for the tracing scene: a pointer to the exploring-apm-traces skill and the tracing MCP
+ * tools, the instruction that tool calls reflect onto the open page, and the live viewer state so
+ * the agent can read what the user is filtering on without a fetch.
+ */
+export function buildTracingAgentContext(
+ filters: TracingFilters,
+ openTrace: TracingOpenTrace | null
+): AttachedContextItem[] {
+ return [
+ PREAMBLE_CONTEXT_ITEM,
+ SKILL_CHIP_CONTEXT_ITEM,
+ APPLY_BACK_CONTEXT_ITEM,
+ {
+ type: 'tracing_viewer_state',
+ hidden: true,
+ dismissGroup: VIEWER_STATE_DISMISS_GROUP,
+ value: serializeViewerState(filters, openTrace),
+ },
+ ]
+}
+
+const OPERATION_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ dismissGroup: OPERATION_DISMISS_GROUP,
+ value:
+ 'The user has a single tracing operation open. The tracing_operation item names the service_name, the ' +
+ 'span name and the date range on screen. Requests about "this operation" mean spans with that name in ' +
+ 'that service: scope query-apm-spans and the aggregate tools with serviceNames and a span-type name ' +
+ 'filter, and use apm-spans-duration-histogram or apm-spans-latency-heatmap for its latency distribution.',
+}
+
+/**
+ * Context for the single-operation scene: the same skill and tool pointer, plus an untrusted
+ * pointer to the operation on screen so "this operation" resolves without the user restating it.
+ */
+export function buildTracingOperationAgentContext(
+ serviceName: string,
+ spanName: string,
+ dateRange: DateRange
+): AttachedContextItem[] {
+ return [
+ PREAMBLE_CONTEXT_ITEM,
+ SKILL_CHIP_CONTEXT_ITEM,
+ OPERATION_CONTEXT_ITEM,
+ {
+ type: 'tracing_operation',
+ hidden: true,
+ dismissGroup: OPERATION_DISMISS_GROUP,
+ value: JSON.stringify({ service_name: serviceName, name: spanName, dateRange }),
+ },
+ ]
+}
+
+function asStringArray(value: unknown): string[] {
+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []
+}
+
+function spanFilter(key: string, value: string[]): UniversalFiltersGroupValue {
+ return { type: PropertyFilterType.Span, key, operator: PropertyOperator.Exact, value } as UniversalFiltersGroupValue
+}
+
+/**
+ * Map query-apm-spans tool input onto the viewer's filter fields, mirroring what the tool queried
+ * onto the open page. The args are the raw agent-sent JSON (never zod-validated), so every field
+ * is coerced and defaulted. statusCodes and traceId have no viewer facet of their own, so they
+ * fold into the filter group as span-column filters, the same way the facet rail writes them. An
+ * omitted field resets to the viewer default so the page shows the query's results exactly, with
+ * the same complete-query semantics the tool ran with.
+ *
+ * rootSpans has no viewer facet to mirror: the span list never sends it, and the backend reads an
+ * omitted value as false, so only flatSpans picks the view mode.
+ */
+export function apmSpansQueryToViewerFilters(input: Record<string, unknown>): Partial<TracingFilters> {
+ // All query-apm-spans params are nested inside `query`; fall back to the raw input defensively.
+ const query = (input.query && typeof input.query === 'object' ? input.query : input) as Record<string, unknown>
+
+ const flatValues: UniversalFiltersGroupValue[] = (Array.isArray(query.filterGroup) ? query.filterGroup : []).map(
+ (filter) => {
+ const f = filter as Record<string, unknown>
+ return {
+ ...f,
+ type: (f.type as PropertyFilterType) || PropertyFilterType.SpanAttribute,
+ operator: (f.operator as PropertyOperator) || PropertyOperator.Exact,
+ } as UniversalFiltersGroupValue
+ }
+ )
+
+ const statusCodes = (Array.isArray(query.statusCodes) ? query.statusCodes : [])
+ .filter((code): code is number | string => typeof code === 'number' || typeof code === 'string')
+ .map(String)
+ if (statusCodes.length > 0) {
+ flatValues.push(spanFilter('status_code', statusCodes))
+ }
+ if (typeof query.traceId === 'string' && query.traceId) {
+ flatValues.push(spanFilter('trace_id', [query.traceId]))
+ }
+
+ const filterGroup: UniversalFiltersGroup = {
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.And, values: flatValues }],
+ }
+
+ const orderBy: TracingOrderBy =
+ query.orderBy === 'timestamp' || query.orderBy === 'duration' ? query.orderBy : DEFAULT_ORDER_BY
+ const orderDirection: TracingOrderDirection =
+ query.orderDirection === 'ASC' || query.orderDirection === 'DESC'
+ ? query.orderDirection
+ : DEFAULT_ORDER_DIRECTION
+
+ return {
+ dateRange: (query.dateRange as DateRange) ?? DEFAULT_DATE_RANGE,
+ serviceNames: asStringArray(query.serviceNames),
+ filterGroup,
+ orderBy,
+ orderDirection,
+ viewMode: query.flatSpans === true ? 'spans' : DEFAULT_VIEW_MODE,
+ }
+}
+
+const HEX_TRACE_ID = /^[0-9a-f]{32}$/i
+
+/** The trace id an apm-trace-get call fetched, or null when the raw agent input carries none. */
+export function apmTraceGetToTraceId(input: Record<string, unknown>): string | null {
+ const traceId = input.trace_id
+ return typeof traceId === 'string' && HEX_TRACE_ID.test(traceId) ? traceId : null
+}