:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { urlToAction } from 'kea-router'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { dateFilterToText, dateStringToDayJs } from 'lib/utils/dateFilters'
import {
buildBucketKeys,
lastBucketIsInProgress,
normalizeBucket,
parseIntervalParam,
resolveInterval,
} from 'lib/utils/timeBuckets'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import {
DateRange,
MCPHarnessBreakdownItem,
MCPToolDailyStatItem,
MCPToolDescriptionItem,
MCPToolFailureItem,
MCPToolFailureOccurrenceItem,
MCPToolNeighborItem,
MCPToolSampleIntentItem,
MCPToolStatsItem,
MCPToolTopUserItem,
NodeKind,
} from '~/queries/schema/schema-general'
import { IntervalType } from '~/types'
import { type MCPSharedQueryFilters, mcpAnalyticsFiltersLogic } from './mcpAnalyticsFiltersLogic'
export interface ToolSummary {
calls: number
errors: number
p50_ms: number | null
p95_ms: number | null
users: number
conversations: number
total_calls: number
total_conversations: number
}
export interface DescriptionRevision {
description: string
last_seen: string
}
export interface IntentCoverage {
with_intent: number
total: number
}
export interface DailyToolStat {
day: string
calls: number
errors: number
p50: number
p95: number
users: number
sessions: number
}
export interface DailyChartData {
labels: string[]
calls: number[]
errors: number[]
p50: number[]
p95: number[]
users: number[]
sessions: number[]
}
const EMPTY_CHART_DATA: DailyChartData = {
labels: [],
calls: [],
errors: [],
p50: [],
p95: [],
users: [],
sessions: [],
}
export type ResultRows = unknown[][]
// Project the per-bucket rows onto the full set of interval buckets spanning the selected window
// (ClickHouse only returns buckets with data). `bucketKeys` covers the whole window at the active
// interval so the sparklines and trend charts match the chosen range — and always have enough points
// to draw a line — even when the tool has data on only a bucket or two. Counts fill with 0; latency
// fills with NaN so the chart skips the point instead of dipping to 0. Rows match by normalized
// bucket key, so day, hour, and minute intervals all line up. No rows at all keeps the empty state.
export function buildDailyChartData(rows: DailyToolStat[], bucketKeys: string[]): DailyChartData {
if (rows.length === 0) {
return EMPTY_CHART_DATA
}
const byBucket = new Map(rows.map((r) => [normalizeBucket(r.day), r]))
const at = bucketKeys.map((k) => byBucket.get(k))
return {
labels: bucketKeys,
calls: at.map((r) => r?.calls ?? 0),
errors: at.map((r) => r?.errors ?? 0),
p50: at.map((r) => (r ? r.p50 : NaN)),
p95: at.map((r) => (r ? r.p95 : NaN)),
users: at.map((r) => r?.users ?? 0),
sessions: at.map((r) => r?.sessions ?? 0),
}
}
export interface MCPAnalyticsToolDetailLogicProps {
toolName: string
}
export interface DateFilter {
dateFrom: string | null
dateTo: string | null
}
// The window carries over from the Tool quality tab via date_from / date_to search params
// (see mcpAnalyticsToolQualityLogic). Without them — e.g. opening a tool page directly — we
// default to the last 30 days.
const DEFAULT_DATE_FILTER: DateFilter = { dateFrom: '-30d', dateTo: null }
// Tools most often called immediately before/after this one within the same conversation.
async function neighborRows(
toolName: string,
direction: 'before' | 'after',
dateRange: DateRange,
sharedQueryFilters: MCPSharedQueryFilters
): Promise<ResultRows> {
const response = (await api.query({
kind: NodeKind.MCPToolNeighborsQuery,
toolName,
neighborDirection: direction,
dateRange,
...sharedQueryFilters,
})) as { results?: MCPToolNeighborItem[] }
return (response?.results ?? []).map((r) => [r.neighbor_tool, r.co_occurrences])
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpAnalyticsToolDetailLogicValues {
sharedQueryFilters: MCPSharedQueryFilters // mcpAnalyticsFiltersLogic
byHarnessRows: ResultRows
byHarnessRowsLoading: boolean
dailyChartData: DailyChartData
dailyStats: DailyToolStat[]
dailyStatsLoading: boolean
dateFilter: DateFilter
dateRange: DateRange
dateRangeLabel: string
descriptions: DescriptionRevision[]
descriptionsLoading: boolean
failureBuckets: MCPToolFailureItem[]
failureBucketsLoading: boolean
failureOccurrences: MCPToolFailureOccurrenceItem[]
failureOccurrencesLoading: boolean
incompleteTail: boolean
intentCoverage: IntentCoverage | null
intentCoverageLoading: boolean
interval: IntervalType
neighborsAfterRows: ResultRows
neighborsAfterRowsLoading: boolean
neighborsBeforeRows: ResultRows
neighborsBeforeRowsLoading: boolean
pinnedInterval: IntervalType | null
sampleIntentRows: ResultRows
sampleIntentRowsLoading: boolean
selectedFailure: MCPToolFailureItem | null
summary: ToolSummary | null
summaryLoading: boolean
toolName: string
topUserRows: ResultRows
topUserRowsLoading: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpAnalyticsToolDetailLogicActions {
hydrateFilters: (
filterTestAccountsOverride: boolean | null,
propertyFilters: import('~/types').AnyPropertyFilter[]
) => {
filterTestAccountsOverride: boolean | null
propertyFilters: import('~/types').AnyPropertyFilter[]
} // mcpAnalyticsFiltersLogic
setFilterTestAccounts: (filterTestAccounts: boolean | null) => {
filterTestAccounts: boolean | null
} // mcpAnalyticsFiltersLogic
setPropertyFilters: (properties: import('~/types').AnyPropertyFilter[]) => {
properties: import('~/types').AnyPropertyFilter[]
} // mcpAnalyticsFiltersLogic
loadAllSections: () => {
value: true
}
loadByHarnessRows: (_: void) => void
loadByHarnessRowsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadByHarnessRowsSuccess: (
byHarnessRows: ResultRows,
payload?: void
) => {
byHarnessRows: ResultRows
payload?: void
}
loadDailyStats: (_: void) => void
loadDailyStatsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadDailyStatsSuccess: (
dailyStats: DailyToolStat[],
payload?: void
) => {
dailyStats: DailyToolStat[]
payload?: void
}
loadDescriptions: (_: void) => void
loadDescriptionsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadDescriptionsSuccess: (
descriptions: DescriptionRevision[],
payload?: void
) => {
descriptions: DescriptionRevision[]
payload?: void
}
loadFailureBuckets: (_: void) => void
loadFailureBucketsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadFailureBucketsSuccess: (
failureBuckets: MCPToolFailureItem[],
payload?: void
) => {
failureBuckets: MCPToolFailureItem[]
payload?: void
}
loadFailureOccurrences: (bucket: MCPToolFailureItem) => MCPToolFailureItem
loadFailureOccurrencesFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadFailureOccurrencesSuccess: (
failureOccurrences: MCPToolFailureOccurrenceItem[],
payload?: MCPToolFailureItem
) => {
failureOccurrences: MCPToolFailureOccurrenceItem[]
payload?: MCPToolFailureItem
}
loadIntentCoverage: (_: void) => void
loadIntentCoverageFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadIntentCoverageSuccess: (
intentCoverage: IntentCoverage | null,
payload?: void
) => {
intentCoverage: IntentCoverage | null
payload?: void
}
loadNeighborsAfterRows: (_: void) => void
loadNeighborsAfterRowsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadNeighborsAfterRowsSuccess: (
neighborsAfterRows: ResultRows,
payload?: void
) => {
neighborsAfterRows: ResultRows
payload?: void
}
loadNeighborsBeforeRows: (_: void) => void
loadNeighborsBeforeRowsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadNeighborsBeforeRowsSuccess: (
neighborsBeforeRows: ResultRows,
payload?: void
) => {
neighborsBeforeRows: ResultRows
payload?: void
}
loadSampleIntentRows: (_: void) => void
loadSampleIntentRowsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadSampleIntentRowsSuccess: (
sampleIntentRows: ResultRows,
payload?: void
) => {
sampleIntentRows: ResultRows
payload?: void
}
loadSummary: (_: void) => void
loadSummaryFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadSummarySuccess: (
summary: ToolSummary | null,
payload?: void
) => {
summary: ToolSummary | null
payload?: void
}
loadTopUserRows: (_: void) => void
loadTopUserRowsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadTopUserRowsSuccess: (
topUserRows: ResultRows,
payload?: void
) => {
topUserRows: ResultRows
payload?: void
}
selectFailure: (bucket: MCPToolFailureItem | null) => {
bucket: MCPToolFailureItem | null
}
setDateFilter: (
dateFrom: string | null,
dateTo: string | null
) => {
dateFrom: string | null
dateTo: string | null
}
setPinnedInterval: (interval: IntervalType | null) => {
interval: IntervalType | null
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpAnalyticsToolDetailLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
toolName: (arg: any) => string
dailyChartData: (
dailyStats: DailyToolStat[],
dateFilter: DateFilter,
interval: IntervalType,
timezone: string
) => DailyChartData
incompleteTail: (dailyChartData: DailyChartData, interval: IntervalType, timezone: string) => boolean
interval: (dateFilter: DateFilter, pinnedInterval: IntervalType | null, timezone: string) => IntervalType
dateRange: (dateFilter: DateFilter, timezone: string) => DateRange
dateRangeLabel: (dateFilter: DateFilter) => string
}
}
export type mcpAnalyticsToolDetailLogicType = MakeLogicType<
mcpAnalyticsToolDetailLogicValues,
mcpAnalyticsToolDetailLogicActions,
MCPAnalyticsToolDetailLogicProps,
mcpAnalyticsToolDetailLogicMeta
>
export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>([
path(['products', 'mcp_analytics', 'frontend', 'mcpAnalyticsToolDetailLogic']),
key((props: MCPAnalyticsToolDetailLogicProps) => props.toolName),
props({} as MCPAnalyticsToolDetailLogicProps),
connect(() => ({
values: [mcpAnalyticsFiltersLogic, ['queryFilters as sharedQueryFilters']],
actions: [mcpAnalyticsFiltersLogic, ['hydrateFilters', 'setFilterTestAccounts', 'setPropertyFilters']],
})),
actions({
setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
setPinnedInterval: (interval: IntervalType | null) => ({ interval }),
loadAllSections: true,
selectFailure: (bucket: MCPToolFailureItem | null) => ({ bucket }),
}),
reducers({
dateFilter: [
DEFAULT_DATE_FILTER,
{
setDateFilter: (_, { dateFrom, dateTo }): DateFilter => ({ dateFrom, dateTo }),
},
],
// Grouping picked on the Tool quality tab and carried here in the URL; null follows the
// auto-choice for the window. This page has no picker of its own.
pinnedInterval: [
null as IntervalType | null,
{
setPinnedInterval: (_, { interval }): IntervalType | null => interval,
},
],
}),
loaders(({ props, values }) => ({
summary: [
null as ToolSummary | null,
{
loadSummary: async (_: void, breakpoint): Promise<ToolSummary | null> => {
const response = (await api.query({
kind: NodeKind.MCPToolStatsQuery,
toolName: props.toolName,
dateRange: values.dateRange,
...values.sharedQueryFilters,
})) as { results?: MCPToolStatsItem[] }
breakpoint()
const row = response?.results?.[0]
if (!row) {
return null
}
return {
calls: row.calls,
errors: row.errors,
p50_ms: row.p50_ms,
p95_ms: row.p95_ms,
users: row.users,
conversations: row.conversations,
total_calls: row.total_calls,
total_conversations: row.total_conversations,
}
},
},
],
descriptions: [
[] as DescriptionRevision[],
{
loadDescriptions: async (_: void, breakpoint): Promise<DescriptionRevision[]> => {
const response = (await api.query({
kind: NodeKind.MCPToolDescriptionsQuery,
toolName: props.toolName,
dateRange: values.dateRange,
...values.sharedQueryFilters,
})) as { results?: MCPToolDescriptionItem[] }
breakpoint()
return (response?.results ?? []).map((r) => ({
description: r.description,
last_seen: r.last_seen,
}))
},
},
],
intentCoverage: [
null as IntentCoverage | null,
{
// Reads the same MCPToolStatsQuery as `summary`; the coverage denominator is the call count.
loadIntentCoverage: async (_: void, breakpoint): Promise<IntentCoverage | null> => {
const response = (await api.query({
kind: NodeKind.MCPToolStatsQuery,
toolName: props.toolName,
dateRange: values.dateRange,
...values.sharedQueryFilters,
})) as { results?: MCPToolStatsItem[] }
breakpoint()
const row = response?.results?.[0]
if (!row) {
return null
}
return { with_intent: row.with_intent, total: row.calls }
},
},
],
dailyStats: [
[] as DailyToolStat[],
{
// Guarded with breakpoint: dailyChartData builds its bucket keys from the *live* interval,
// so a superseded response fetched at a different interval (e.g. day → hour on a fast
// back/forward) would otherwise land and collapse a day's rows into one hourly bucket.
loadDailyStats: async (_: void, breakpoint): Promise<DailyToolStat[]> => {
const response = (await api.query({
kind: NodeKind.MCPToolDailyStatsQuery,
toolName: props.toolName,
dateRange: values.dateRange,
interval: values.interval,
...values.sharedQueryFilters,
})) as { results?: MCPToolDailyStatItem[] }
breakpoint()
return (response?.results ?? []).map((r) => ({
day: r.day,
calls: r.calls,
errors: r.errors,
p50: r.p50,
p95: r.p95,
users: r.users,
sessions: r.sessions,
}))
},
},
],
failureBuckets: [
[] as MCPToolFailureItem[],
{
loadFailureBuckets: async (_: void, breakpoint): Promise<MCPToolFailureItem[]> => {
const response = (await api.query({
kind: NodeKind.MCPToolFailuresQuery,
toolName: props.toolName,
dateRange: values.dateRange,
...values.sharedQueryFilters,
})) as { results?: MCPToolFailureItem[] }
breakpoint()
return response?.results ?? []
},
},
],
failureOccurrences: [
[] as MCPToolFailureOccurrenceItem[],
{
loadFailureOccurrences: async (
bucket: MCPToolFailureItem,
breakpoint
): Promise<MCPToolFailureOccurrenceItem[]> => {
const response = (await api.query({
kind: NodeKind.MCPToolFailureOccurrencesQuery,
toolName: props.toolName,
// Raw bucket parts, not the composed label — the backend normalizes them the
// same way it grouped the failures table, so the bucket round-trips exactly.
errorType: bucket.error_type,
errorStatus: bucket.error_status || undefined,
dateRange: values.dateRange,
...values.sharedQueryFilters,
})) as { results?: MCPToolFailureOccurrenceItem[] }
// Bail if a newer bucket was selected while this request was in flight,
// so a slow earlier bucket can't overwrite the latest one.
breakpoint()
if (values.selectedFailure !== bucket) {
return []
}
return response?.results ?? []
},
},
],
sampleIntentRows: [
[] as ResultRows,
{
loadSampleIntentRows: async (_: void, breakpoint): Promise<ResultRows> => {
const response = (await api.query({
kind: NodeKind.MCPToolSampleIntentsQuery,
toolName: props.toolName,
dateRange: values.dateRange,
...values.sharedQueryFilters,
})) as { results?: MCPToolSampleIntentItem[] }
breakpoint()
return (response?.results ?? []).map((r) => [r.timestamp, r.intent, r.intent_source, r.harness])
},
},
],
neighborsBeforeRows: [
[] as ResultRows,
{
loadNeighborsBeforeRows: async (_: void, breakpoint): Promise<ResultRows> => {
const rows = await neighborRows(
props.toolName,
'before',
values.dateRange,
values.sharedQueryFilters
)
breakpoint()
return rows
},
},
],
neighborsAfterRows: [
[] as ResultRows,
{
loadNeighborsAfterRows: async (_: void, breakpoint): Promise<ResultRows> => {
const rows = await neighborRows(
props.toolName,
'after',
values.dateRange,
values.sharedQueryFilters
)
breakpoint()
return rows
},
},
],
byHarnessRows: [
[] as ResultRows,
{
// Server-resolved harness labels via the same runner as the dashboard (scoped to this
// tool's new-SDK calls by toolName), so the pill matches the dashboard's bucketing exactly.
loadByHarnessRows: async (_: void, breakpoint): Promise<ResultRows> => {
const response = (await api.query({
kind: NodeKind.MCPHarnessBreakdownQuery,
toolName: props.toolName,
dateRange: values.dateRange,
...values.sharedQueryFilters,
})) as { results?: MCPHarnessBreakdownItem[] }
breakpoint()
return (response?.results ?? []).map((r) => [
r.harness,
r.total_calls,
r.errors,
r.error_rate_pct,
r.sessions,
r.harness_sessions ?? null,
])
},
},
],
topUserRows: [
[] as ResultRows,
{
// The person tuple is rebuilt into the [distinct_id, _, properties] shape renderPersonCell expects.
loadTopUserRows: async (_: void, breakpoint): Promise<ResultRows> => {
const response = (await api.query({
kind: NodeKind.MCPToolTopUsersQuery,
toolName: props.toolName,
dateRange: values.dateRange,
...values.sharedQueryFilters,
})) as { results?: MCPToolTopUserItem[] }
breakpoint()
return (response?.results ?? []).map((r) => [
[r.distinct_id, '', r.person_properties],
r.calls,
r.errors,
r.error_rate_pct,
r.harnesses,
r.last_seen,
])
},
},
],
})),
reducers({
selectedFailure: [
null as MCPToolFailureItem | null,
{
selectFailure: (_, { bucket }) => bucket,
},
],
// Reset on every (de)selection so a newly opened bucket shows the loading skeleton
// instead of the previous bucket's rows.
failureOccurrences: {
selectFailure: () => [],
},
}),
listeners(({ actions }) => ({
selectFailure: ({ bucket }) => {
if (bucket) {
actions.loadFailureOccurrences(bucket)
}
},
})),
selectors({
toolName: [() => [(_, props) => props.toolName], (toolName: string) => toolName],
dailyChartData: [
(s) => [s.dailyStats, s.dateFilter, s.interval, teamLogic.selectors.timezone],
(
dailyStats: DailyToolStat[],
dateFilter: DateFilter,
interval: IntervalType,
timezone: string
): DailyChartData => {
const bucketKeys = buildBucketKeys(dateFilter.dateFrom, dateFilter.dateTo, timezone, interval)
return buildDailyChartData(dailyStats, bucketKeys)
},
],
// The trend charts and sparklines dash the final segment when it is the current, still-
// collecting interval, so a partial period doesn't read as a fall in calls or a latency win.
incompleteTail: [
(s) => [s.dailyChartData, s.interval, teamLogic.selectors.timezone],
(dailyChartData: DailyChartData, interval: IntervalType, timezone: string): boolean =>
lastBucketIsInProgress(dailyChartData.labels, timezone, interval),
],
// Grouping interval for the daily series, matching the query's dateTrunc: the interval pinned on
// the Tool quality tab, else the auto-choice so a sub-day window buckets by hour/minute instead
// of collapsing to one day point.
interval: [
(s) => [s.dateFilter, s.pinnedInterval, teamLogic.selectors.timezone],
(dateFilter: DateFilter, pinnedInterval: IntervalType | null, timezone: string): IntervalType =>
resolveInterval(dateFilter.dateFrom, dateFilter.dateTo, timezone, pinnedInterval),
],
// Resolve the `dateFilter` state (camelCase, nullable, may be relative like '-30d') into the
// absolute snake_case `DateRange` the query API takes. Done once so every section queries the
// exact same window — a relative '-Nd' would re-resolve per section and drift after midnight.
dateRange: [
(s) => [s.dateFilter, teamLogic.selectors.timezone],
(dateFilter: DateFilter, timezone: string): DateRange => {
const to = dateStringToDayJs(dateFilter.dateTo, timezone) ?? dayjs().tz(timezone)
const from =
dateStringToDayJs(dateFilter.dateFrom, timezone) ?? dayjs().tz(timezone).subtract(30, 'day')
return { date_from: from.toISOString(), date_to: to.toISOString() }
},
],
dateRangeLabel: [
(s) => [s.dateFilter],
(dateFilter: DateFilter): string =>
dateFilterToText(dateFilter.dateFrom, dateFilter.dateTo, 'the selected range') ?? 'the selected range',
],
}),
listeners(({ actions }) => ({
// The window and pinned interval reload through the urlToAction handler below instead of a
// listener on setDateFilter; the shared filters have no URL round-trip of their own here, so
// they reload directly the same way that handler reloads on a date change.
setFilterTestAccounts: () => {
actions.selectFailure(null)
actions.loadAllSections()
},
setPropertyFilters: () => {
actions.selectFailure(null)
actions.loadAllSections()
},
hydrateFilters: () => {
actions.selectFailure(null)
actions.loadAllSections()
},
loadAllSections: () => {
actions.loadSummary()
actions.loadDescriptions()
actions.loadIntentCoverage()
actions.loadDailyStats()
actions.loadFailureBuckets()
actions.loadSampleIntentRows()
actions.loadNeighborsBeforeRows()
actions.loadNeighborsAfterRows()
actions.loadByHarnessRows()
actions.loadTopUserRows()
},
})),
// The window and grouping ride along in the URL from the Tool quality tab. Reading them here
// (rather than once in afterMount) keeps the page in sync when only date_from / date_to / interval
// change for the same tool — e.g. browser back/forward — since the logic is keyed by toolName and
// wouldn't remount.
urlToAction(({ actions, values, cache }) => ({
[`${urls.mcpAnalyticsToolQuality()}/:toolName`]: (_, searchParams) => {
const dateFrom =
typeof searchParams.date_from === 'string' ? searchParams.date_from : DEFAULT_DATE_FILTER.dateFrom
const dateTo = typeof searchParams.date_to === 'string' ? searchParams.date_to : null
const dateChanged = dateFrom !== values.dateFilter.dateFrom || dateTo !== values.dateFilter.dateTo
if (dateChanged) {
actions.setDateFilter(dateFrom, dateTo)
}
const interval = parseIntervalParam(searchParams.interval)
const intervalChanged = interval !== values.pinnedInterval
if (intervalChanged) {
actions.setPinnedInterval(interval)
}
if (dateChanged || !cache.hasLoaded) {
actions.loadAllSections()
} else if (intervalChanged) {
// Only the trend series buckets by interval; every other section is a single-window
// aggregate that a grouping change cannot move.
actions.loadDailyStats()
}
cache.hasLoaded = true
},
})),
])