: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,
afterMount,
connect,
kea,
listeners,
path,
reducers,
selectors,
sharedListeners,
} from 'kea'
import type { BreakPointFunction } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
import posthog from 'lib/posthog-typed'
import { teamLogic } from 'scenes/teamLogic'
import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
import {
DataTableNode,
HogQLFilters,
MCPHarnessBreakdownItem,
MCPModelBreakdownItem,
NodeKind,
} from '~/queries/schema/schema-general'
import type { HogFunctionType } from '~/types'
import {
DEFAULT_MCP_ACTIVITY_QUERY,
MCP_ACTIVITY_DATA_COLLECTION_ID,
withFailedCallsOnly,
withSharedFilters,
} from '../components/toolCallFeedQuery'
import { mcpAnalyticsSessionsActivityOverview } from '../generated/api'
import type { MCPActivityOverviewApi } from '../generated/api.schemas'
import { type MCPSharedQueryFilters, mcpAnalyticsFiltersLogic, sharedFilterParams } from '../mcpAnalyticsFiltersLogic'
import { mcpAnalyticsOnboardingLogic } from '../mcpAnalyticsOnboardingLogic'
import type { MCPOnboardingSignals } from '../mcpAnalyticsOnboardingLogic'
import type { HarnessRow, ModelRow } from '../mcpDashboardOverviewLogic'
import { mcpAnalyticsNotificationsLogic } from '../notifications/mcpAnalyticsNotificationsLogic'
import { mcpRecurringReportsLogic } from '../notifications/mcpRecurringReportsLogic'
import { type WeeklyReportOffer, weeklyReportOfferLabel } from '../notifications/weeklyReportOffer'
import { ActivitySummary, buildActivitySummary } from './activitySummary'
import { EarlyStats, NextStep, NextStepInteraction, NextStepKey, buildNextSteps } from './nextSteps'
export type { EarlyStats, NextStep } from './nextSteps'
export type NotificationsLoad = 'pending' | 'loaded' | 'failed'
export interface EarlyToolRow {
tool: string
calls: number
errors: number
}
const EMPTY_STATS: EarlyStats = {
totalCalls: 0,
distinctTools: 0,
distinctSessions: 0,
distinctClients: 0,
callsWithIntent: 0,
errorCalls: 0,
missingCapabilityReports: 0,
}
// The feed's default range, unfiltered like the feed and the overview endpoint, so every number on
// the tab describes the same calls. The dashboard applies its own test-account filter.
export const ACTIVITY_FILTERS: HogQLFilters = { dateRange: { date_from: '-30d' } }
// Refresh cadence for the early view. Slower than the onboarding signal poll: the
// overview aggregates 30 days of property-reading queries server-side, and "within
// a minute" is live enough.
const REFRESH_INTERVAL_MS = 60000
// A tab left open with nobody looking still polls, so each refresh that sees no user input
// doubles the wait, up to this cap. Any input goes back to one minute.
const MAX_REFRESH_INTERVAL_MS = 30 * REFRESH_INTERVAL_MS
const USER_INPUT_EVENTS = ['pointermove', 'pointerdown', 'keydown', 'wheel'] as const
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpEarlyDataLogicValues {
sharedQueryFilters: MCPSharedQueryFilters // mcpAnalyticsFiltersLogic
notifications: HogFunctionType[] // mcpAnalyticsNotificationsLogic
signals: MCPOnboardingSignals | null // mcpAnalyticsOnboardingLogic
weeklyReportOffer: WeeklyReportOffer // mcpRecurringReportsLogic
currentProjectId: number | string // teamLogic
activityQuery: DataTableNode
harnessRows: HarnessRow[]
harnessRowsLoading: boolean
hasFailureNotification: boolean | null
hasModelData: boolean
inputSinceRefresh: boolean
modelRows: ModelRow[]
modelRowsLoading: boolean
nextSteps: NextStep[] | null
notificationsLoad: NotificationsLoad
overview: MCPActivityOverviewApi | null
overviewLoading: boolean
refreshDelayMs: number
refreshesWithoutInput: number
stats: EarlyStats
summary: ActivitySummary
topTools: EarlyToolRow[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpEarlyDataLogicActions {
reloadActivityQuery: () => {} // dataNodeCollectionLogic
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
loadNotifications: () => any // mcpAnalyticsNotificationsLogic
loadNotificationsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
} // mcpAnalyticsNotificationsLogic
loadNotificationsSuccess: (
notifications: HogFunctionType[],
payload?: any
) => {
notifications: HogFunctionType[]
payload?: any
} // mcpAnalyticsNotificationsLogic
loadSignals: (_?: void | undefined) => void // mcpAnalyticsOnboardingLogic
createWeeklyReportReconciled: () => {
value: true
} // mcpRecurringReportsLogic
loadReports: () => any // mcpRecurringReportsLogic
loadReportsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
} // mcpRecurringReportsLogic
loadReportsSuccess: (
reports: import('products/subscriptions/frontend/generated/api.schemas').SubscriptionApi[],
payload?: any
) => {
payload?: any
reports: import('products/subscriptions/frontend/generated/api.schemas').SubscriptionApi[]
} // mcpRecurringReportsLogic
loadHarnessRows: (_: void) => void
loadHarnessRowsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadHarnessRowsSuccess: (
harnessRows: HarnessRow[],
payload?: void
) => {
harnessRows: HarnessRow[]
payload?: void
}
loadModelRows: (_: void) => void
loadModelRowsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadModelRowsSuccess: (
modelRows: ModelRow[],
payload?: void
) => {
modelRows: ModelRow[]
payload?: void
}
loadOverview: (_: void) => void
loadOverviewFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadOverviewSuccess: (
overview: MCPActivityOverviewApi | null,
payload?: void
) => {
overview: MCPActivityOverviewApi | null
payload?: void
}
nextStepClicked: (
stepKey: NextStepKey,
interaction: NextStepInteraction
) => {
interaction: NextStepInteraction
stepKey: NextStepKey
}
noteUserInput: () => {
value: true
}
refreshAll: () => {
value: true
}
refreshFilteredActivity: () => {
value: true
}
refreshOnSchedule: (hadInput: boolean) => {
hadInput: boolean
}
resetRefreshBackoff: () => {
value: true
}
scheduleRefresh: () => {
value: true
}
setActivityQuery: (query: DataTableNode) => {
query: DataTableNode
}
showFailedCallsOnly: () => {
value: true
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpEarlyDataLogicMeta {
sharedListeners: {
captureNextStepsShown: (
payload: any,
breakpoint: BreakPointFunction,
action: {
type: string
payload: any
},
previousState: any
) => void | Promise<void>
}
__keaTypeGenInternalSelectorTypes: {
stats: (overview: MCPActivityOverviewApi | null) => EarlyStats
topTools: (overview: MCPActivityOverviewApi | null) => EarlyToolRow[]
summary: (signals: MCPOnboardingSignals | null, stats: EarlyStats, topTools: EarlyToolRow[]) => ActivitySummary
hasFailureNotification: (
notificationsLoad: NotificationsLoad,
notifications: HogFunctionType[]
) => boolean | null
nextSteps: (
overview: MCPActivityOverviewApi | null,
stats: EarlyStats,
notificationsLoad: NotificationsLoad,
hasFailureNotification: boolean | null,
weeklyReportOffer: WeeklyReportOffer
) => NextStep[] | null
hasModelData: (modelRows: ModelRow[]) => boolean
refreshDelayMs: (refreshesWithoutInput: number) => number
}
}
export type mcpEarlyDataLogicType = MakeLogicType<
mcpEarlyDataLogicValues,
mcpEarlyDataLogicActions,
Record<string, any>,
mcpEarlyDataLogicMeta
>
export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([
path(['products', 'mcp_analytics', 'frontend', 'earlyData', 'mcpEarlyDataLogic']),
connect(() => ({
values: [
mcpAnalyticsOnboardingLogic,
['signals'],
teamLogic,
['currentProjectId'],
mcpAnalyticsFiltersLogic,
['queryFilters as sharedQueryFilters'],
mcpAnalyticsNotificationsLogic,
['notifications'],
mcpRecurringReportsLogic,
['weeklyReportOffer'],
],
actions: [
// Refresh the lifetime signal with the overview so first-call copy can
// advance even after the onboarding signal poll stops.
mcpAnalyticsOnboardingLogic,
['loadSignals'],
mcpAnalyticsFiltersLogic,
['hydrateFilters', 'setFilterTestAccounts', 'setPropertyFilters'],
mcpAnalyticsNotificationsLogic,
['loadNotifications', 'loadNotificationsSuccess', 'loadNotificationsFailure'],
mcpRecurringReportsLogic,
['loadReports', 'loadReportsSuccess', 'loadReportsFailure', 'createWeeklyReportReconciled'],
dataNodeCollectionLogic({ key: MCP_ACTIVITY_DATA_COLLECTION_ID }),
['reloadAll as reloadActivityQuery'],
],
})),
actions({
noteUserInput: true,
refreshAll: true,
refreshFilteredActivity: true,
refreshOnSchedule: (hadInput: boolean) => ({ hadInput }),
resetRefreshBackoff: true,
scheduleRefresh: true,
setActivityQuery: (query: DataTableNode) => ({ query }),
showFailedCallsOnly: true,
nextStepClicked: (stepKey: NextStepKey, interaction: NextStepInteraction) => ({ stepKey, interaction }),
}),
reducers({
activityQuery: [DEFAULT_MCP_ACTIVITY_QUERY, { setActivityQuery: (_, { query }) => query }],
// The list defaults to empty before its first load, which would read as "no alert set up".
// A failed load also releases the card, so it never waits forever on a list that will not arrive,
// but leaves the alert question unanswered rather than reading the empty default as "no alert".
notificationsLoad: [
'pending' as NotificationsLoad,
{ loadNotificationsSuccess: () => 'loaded', loadNotificationsFailure: () => 'failed' },
],
inputSinceRefresh: [false, { noteUserInput: () => true, refreshOnSchedule: () => false }],
refreshesWithoutInput: [
0,
{
refreshOnSchedule: (count, { hadInput }) => (hadInput ? 0 : count + 1),
resetRefreshBackoff: () => 0,
},
],
}),
loaders(({ values }) => ({
overview: {
__default: null as MCPActivityOverviewApi | null,
loadOverview: async (_: void, breakpoint): Promise<MCPActivityOverviewApi | null> => {
if (!values.currentProjectId) {
return null
}
const response = await mcpAnalyticsSessionsActivityOverview(
String(values.currentProjectId),
sharedFilterParams(values.sharedQueryFilters)
)
breakpoint()
return response
},
},
harnessRows: [
[] as HarnessRow[],
{
loadHarnessRows: async (_: void, breakpoint): Promise<HarnessRow[]> => {
const response = (await api.query({
kind: NodeKind.MCPHarnessBreakdownQuery,
...ACTIVITY_FILTERS,
...values.sharedQueryFilters,
})) as { results?: MCPHarnessBreakdownItem[] }
breakpoint()
return (response?.results ?? []).map((r) => ({
category: r.harness,
total_calls: r.total_calls,
errors: r.errors,
error_rate_pct: r.error_rate_pct,
sessions: r.sessions,
}))
},
},
],
modelRows: [
[] as ModelRow[],
{
loadModelRows: async (_: void, breakpoint): Promise<ModelRow[]> => {
const response = (await api.query({
kind: NodeKind.MCPModelBreakdownQuery,
...ACTIVITY_FILTERS,
...values.sharedQueryFilters,
})) as { results?: MCPModelBreakdownItem[] }
breakpoint()
return response?.results ?? []
},
},
],
})),
selectors({
stats: [
(s) => [s.overview],
(overview: MCPActivityOverviewApi | null): EarlyStats =>
overview
? {
totalCalls: overview.stats.total_calls,
distinctTools: overview.stats.distinct_tools,
distinctSessions: overview.stats.distinct_sessions,
distinctClients: overview.stats.distinct_clients,
callsWithIntent: overview.stats.calls_with_intent,
errorCalls: overview.stats.error_calls,
missingCapabilityReports: overview.stats.missing_capability_reports,
}
: EMPTY_STATS,
],
topTools: [
(s) => [s.overview],
(overview: MCPActivityOverviewApi | null): EarlyToolRow[] =>
(overview?.top_tools ?? []).map((row) => ({ tool: row.tool, calls: row.calls, errors: row.errors })),
],
summary: [
(s) => [s.signals, s.stats, s.topTools],
(signals: MCPOnboardingSignals | null, stats: EarlyStats, topTools: EarlyToolRow[]): ActivitySummary =>
buildActivitySummary({
lifetimeCalls: signals?.toolCallsTotal ?? null,
totalCalls: stats.totalCalls,
distinctClients: stats.distinctClients,
errorCalls: stats.errorCalls,
topTool: stats.totalCalls > 10 ? (topTools[0]?.tool ?? null) : null,
}),
],
// A paused alert notifies nobody, so only enabled ones count as "set up".
hasFailureNotification: [
(s) => [s.notificationsLoad, s.notifications],
(notificationsLoad: NotificationsLoad, notifications: HogFunctionType[]): boolean | null =>
notificationsLoad === 'loaded' ? notifications.some((notification) => notification.enabled) : null,
],
// Null until the overview, the notification list and the report offer all resolve, so steps never reorder under the reader.
nextSteps: [
(s) => [s.overview, s.stats, s.notificationsLoad, s.hasFailureNotification, s.weeklyReportOffer],
(
overview: MCPActivityOverviewApi | null,
stats: EarlyStats,
notificationsLoad: NotificationsLoad,
hasFailureNotification: boolean | null,
weeklyReportOffer: WeeklyReportOffer
): NextStep[] | null =>
overview && notificationsLoad !== 'pending' && weeklyReportOffer.state !== 'loading'
? buildNextSteps({ stats, hasFailureNotification, weeklyReport: weeklyReportOffer })
: null,
],
hasModelData: [
(s) => [s.modelRows],
(modelRows: ModelRow[]): boolean => modelRows.some((row) => row.total_calls > 0),
],
refreshDelayMs: [
(s) => [s.refreshesWithoutInput],
(refreshesWithoutInput: number): number =>
Math.min(REFRESH_INTERVAL_MS * 2 ** refreshesWithoutInput, MAX_REFRESH_INTERVAL_MS),
],
}),
sharedListeners(({ cache, values }) => ({
// Bound to each action that resolves an input of `nextSteps` (reacting-to-changes.md prefers
// sharedListeners to kea-subscriptions). Compares step keys: the 60s refresh rebuilds the same steps.
captureNextStepsShown: () => {
const stepKeys = (values.nextSteps ?? []).map((step) => step.key)
const shown = stepKeys.join()
if (shown === cache.shownStepKeys) {
return
}
// An empty card is remembered too, so steps coming back after none are shown again.
cache.shownStepKeys = shown
if (stepKeys.length > 0) {
posthog.captureRaw('mcp analytics next steps shown', {
step_keys: stepKeys,
weekly_report: weeklyReportOfferLabel(values.weeklyReportOffer),
total_calls: values.stats.totalCalls,
error_calls: values.stats.errorCalls,
})
}
},
})),
listeners(({ actions, values, cache, sharedListeners }) => ({
loadOverviewSuccess: sharedListeners.captureNextStepsShown,
loadNotificationsSuccess: sharedListeners.captureNextStepsShown,
loadNotificationsFailure: sharedListeners.captureNextStepsShown,
loadReportsSuccess: sharedListeners.captureNextStepsShown,
loadReportsFailure: sharedListeners.captureNextStepsShown,
createWeeklyReportReconciled: sharedListeners.captureNextStepsShown,
nextStepClicked: ({ stepKey, interaction }) => {
posthog.captureRaw('mcp analytics next step clicked', {
step_key: stepKey,
interaction,
position: values.nextSteps?.findIndex((step) => step.key === stepKey) ?? -1,
weekly_report: weeklyReportOfferLabel(values.weeklyReportOffer),
})
},
scheduleRefresh: () => {
cache.disposables.add(() => {
const id = window.setTimeout(
() => actions.refreshOnSchedule(values.inputSinceRefresh),
values.refreshDelayMs
)
return () => clearTimeout(id)
}, 'refresh')
},
refreshOnSchedule: () => {
actions.refreshAll()
actions.scheduleRefresh()
},
noteUserInput: () => {
if (values.refreshesWithoutInput > 0) {
actions.resetRefreshBackoff()
}
},
resetRefreshBackoff: () => actions.scheduleRefresh(),
refreshAll: () => {
actions.loadSignals()
actions.loadNotifications()
actions.refreshFilteredActivity()
},
refreshFilteredActivity: () => {
actions.setActivityQuery(withSharedFilters(values.activityQuery, values.sharedQueryFilters))
actions.loadOverview()
actions.loadHarnessRows()
actions.loadModelRows()
actions.reloadActivityQuery()
},
hydrateFilters: () => actions.refreshFilteredActivity(),
setFilterTestAccounts: () => actions.refreshFilteredActivity(),
setPropertyFilters: () => actions.refreshFilteredActivity(),
showFailedCallsOnly: () => {
actions.setActivityQuery(withFailedCallsOnly(values.activityQuery))
},
})),
afterMount(({ actions, values, cache }) => {
actions.setActivityQuery(
withSharedFilters(DEFAULT_MCP_ACTIVITY_QUERY, mcpAnalyticsFiltersLogic.values.queryFilters)
)
actions.loadOverview()
actions.loadNotifications()
actions.loadReports()
actions.loadHarnessRows()
actions.loadModelRows()
actions.scheduleRefresh()
cache.disposables.add(() => {
const onUserInput = (): void => {
if (!values.inputSinceRefresh) {
actions.noteUserInput()
}
}
USER_INPUT_EVENTS.forEach((event) => window.addEventListener(event, onUserInput, { passive: true }))
return () => USER_INPUT_EVENTS.forEach((event) => window.removeEventListener(event, onUserInput))
}, 'userInput')
}),
])