: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 } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { AnyPropertyFilter } from '~/types'
import {
mcpAnalyticsSessionsGenerateIntent,
mcpAnalyticsSessionsList,
mcpAnalyticsSessionsToolCalls,
} from '../generated/api'
import type { MCPSessionApi, MCPSessionIntentApi, MCPToolCallApi } from '../generated/api.schemas'
import {
type MCPSharedQueryFilters,
mcpAnalyticsFiltersLogic,
parseUrlBoolean,
sharedFilterParams,
} from '../mcpAnalyticsFiltersLogic'
export interface MCPSessionsFilters {
// true: sessions with at least one errored call; false: sessions with none; null: both.
hasErrors: boolean | null
}
const DEFAULT_FILTERS: MCPSessionsFilters = {
hasErrors: null,
}
export interface MCPSessionsDateFilter {
dateFrom: string | null
dateTo: string | null
}
// Matches the dashboard default (mcpDashboardOverviewLogic) so both tabs show the
// same window out of the box and the shared date_from/date_to URL params line up.
const DEFAULT_DATE_FILTER: MCPSessionsDateFilter = { dateFrom: '-7d', dateTo: null }
// How many sessions to fetch per request. Each "Load more" appends the next page
export const SESSIONS_PAGE_SIZE = 50
// How many of a session's tool calls to fetch per request. Each "Load more" appends the
// next page; the button appears whenever a session has more calls than one page.
export const TOOL_CALLS_PAGE_SIZE = 100
// Must stay aligned with SESSION_SORT_FIELDS on the backend (logic.py).
export type MCPSessionSortColumn =
| 'session_id'
| 'session_start'
| 'session_end'
| 'duration_seconds'
| 'tool_call_count'
| 'mcp_client_name'
| 'distinct_id'
export interface MCPSessionSorting {
column: MCPSessionSortColumn
order: 1 | -1
}
const DEFAULT_SORTING: MCPSessionSorting = { column: 'session_start', order: -1 }
export type MCPSessionOrderBy = `${'' | '-'}${MCPSessionSortColumn}`
export function orderByParam(sorting: MCPSessionSorting | null): MCPSessionOrderBy | undefined {
return sorting ? `${sorting.order === -1 ? '-' : ''}${sorting.column}` : undefined
}
export interface SessionToolCalls {
sessionId: string | null
filters: MCPSharedQueryFilters | null
calls: MCPToolCallApi[]
hasNext: boolean
}
const EMPTY_TOOL_CALLS: SessionToolCalls = { sessionId: null, filters: null, calls: [], hasNext: false }
// Fetch one page of a session's tool calls, unwrapped into { calls, hasNext }. session_id comes from
// untrusted event properties, so encode it — path/query delimiters must not redirect the request to
// another same-origin endpoint. date_from bounds the scan by the session's start so sessions older
// than the backend's default lookback still return their calls.
async function fetchToolCallsPage(
projectId: string | number,
sessionId: string,
sessionStart: string | null | undefined,
offset: number,
sharedFilters: MCPSharedQueryFilters
): Promise<{ calls: MCPToolCallApi[]; hasNext: boolean }> {
const response = await mcpAnalyticsSessionsToolCalls(String(projectId), encodeURIComponent(sessionId), {
date_from: sessionStart || undefined,
limit: TOOL_CALLS_PAGE_SIZE,
offset,
...sharedFilterParams(sharedFilters),
})
return { calls: response.results ?? [], hasNext: response.has_next ?? false }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpSessionsLogicValues {
sharedQueryFilters: MCPSharedQueryFilters // mcpAnalyticsFiltersLogic
currentProjectId: number | string // teamLogic
dateFilter: MCPSessionsDateFilter
filters: MCPSessionsFilters
generatedIntent: MCPSessionIntentApi | null
generatedIntentLoading: boolean
generatingSessionId: string | null
hasActiveFilters: boolean
hasNext: boolean
intentOverrides: Record<string, string>
isSelectedSessionGenerating: boolean
selectedSession: MCPSessionApi | null
selectedSessionId: string | null
selectedSessionIntent: string
selectedSessionToolCalls: {
calls: MCPToolCallApi[]
error: boolean
hasNext: boolean
loading: boolean
loadingMore: boolean
}
sessions: MCPSessionApi[]
sessionsLoading: boolean
sorting: MCPSessionSorting | null
toolCalls: SessionToolCalls
toolCallsLoadFailed: boolean
toolCallsLoading: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpSessionsLogicActions {
hydrateFilters: (
filterTestAccountsOverride: boolean | null,
propertyFilters: AnyPropertyFilter[]
) => {
filterTestAccountsOverride: boolean | null
propertyFilters: AnyPropertyFilter[]
} // mcpAnalyticsFiltersLogic
setFilterTestAccounts: (filterTestAccounts: boolean | null) => {
filterTestAccounts: boolean | null
} // mcpAnalyticsFiltersLogic
setPropertyFilters: (properties: AnyPropertyFilter[]) => {
properties: AnyPropertyFilter[]
} // mcpAnalyticsFiltersLogic
generateIntent: (sessionId: string) => string
generateIntentFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
generateIntentSuccess: (
generatedIntent: MCPSessionIntentApi | null,
payload?: string
) => {
generatedIntent: MCPSessionIntentApi | null
payload?: string
}
loadMoreSessions: () => {
value: true
}
loadMoreSessionsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadMoreSessionsSuccess: (
sessions: MCPSessionApi[],
payload?: {
value: true
}
) => {
sessions: MCPSessionApi[]
payload?: {
value: true
}
}
loadMoreToolCalls: () => {
value: true
}
loadMoreToolCallsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadMoreToolCallsSuccess: (
toolCalls: SessionToolCalls,
payload?: {
value: true
}
) => {
toolCalls: SessionToolCalls
payload?: {
value: true
}
}
loadSessions: () => {
value: true
}
loadSessionsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadSessionsSuccess: (
sessions: MCPSessionApi[],
payload?: {
value: true
}
) => {
sessions: MCPSessionApi[]
payload?: {
value: true
}
}
loadToolCalls: (sessionId: string) => string
loadToolCallsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadToolCallsSuccess: (
toolCalls: SessionToolCalls,
payload?: string
) => {
toolCalls: SessionToolCalls
payload?: string
}
refreshSessions: () => {
value: true
}
selectSession: (sessionId: string | null) => {
sessionId: string | null
}
setDateFilter: (
dateFrom: string | null,
dateTo: string | null
) => {
dateFrom: string | null
dateTo: string | null
}
setFilters: (filters: Partial<MCPSessionsFilters>) => {
filters: Partial<MCPSessionsFilters>
}
setHasNext: (hasNext: boolean) => {
hasNext: boolean
}
setSorting: (sorting: MCPSessionSorting | null) => {
sorting: MCPSessionSorting | null
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpSessionsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
hasActiveFilters: (
filters: MCPSessionsFilters,
dateFilter: MCPSessionsDateFilter,
sharedQueryFilters: Required<
Pick<import('~/queries/schema').HogQLFilters, 'filterTestAccounts' | 'properties'>
>
) => boolean
selectedSession: (sessions: MCPSessionApi[], selectedSessionId: string | null) => MCPSessionApi | null
selectedSessionIntent: (
selectedSession: MCPSessionApi | null,
intentOverrides: Record<string, string>,
selectedSessionId: string | null
) => string
isSelectedSessionGenerating: (
generatedIntentLoading: boolean,
generatingSessionId: string | null,
selectedSessionId: string | null
) => boolean
selectedSessionToolCalls: (
toolCalls: SessionToolCalls,
selectedSessionId: string | null,
toolCallsLoading: boolean,
sharedQueryFilters: Required<
Pick<import('~/queries/schema').HogQLFilters, 'filterTestAccounts' | 'properties'>
>,
toolCallsLoadFailed: boolean
) => {
calls: MCPToolCallApi[]
error: boolean
hasNext: boolean
loading: boolean
loadingMore: boolean
}
}
}
export type mcpSessionsLogicType = MakeLogicType<
mcpSessionsLogicValues,
mcpSessionsLogicActions,
Record<string, any>,
mcpSessionsLogicMeta
>
export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
path(['products', 'mcp_analytics', 'frontend', 'sessions', 'mcpSessionsLogic']),
connect(() => ({
values: [teamLogic, ['currentProjectId'], mcpAnalyticsFiltersLogic, ['queryFilters as sharedQueryFilters']],
actions: [mcpAnalyticsFiltersLogic, ['hydrateFilters', 'setFilterTestAccounts', 'setPropertyFilters']],
})),
actions({
// Declared explicitly so kea-typegen emits a no-arg signature for the loader
// actions below — without this, the `(_, breakpoint)` loader signature forces
// every call site to pass a placeholder argument.
loadSessions: true,
loadMoreSessions: true,
loadMoreToolCalls: true,
refreshSessions: true,
setFilters: (filters: Partial<MCPSessionsFilters>) => ({ filters }),
setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
setSorting: (sorting: MCPSessionSorting | null) => ({ sorting }),
setHasNext: (hasNext: boolean) => ({ hasNext }),
selectSession: (sessionId: string | null) => ({ sessionId }),
}),
loaders(({ values, actions, cache }) => ({
sessions: [
[] as MCPSessionApi[],
{
loadSessions: async (_, breakpoint) => {
cache.sessionsGeneration = (cache.sessionsGeneration ?? 0) + 1
if (!values.currentProjectId) {
return []
}
const response = await mcpAnalyticsSessionsList(String(values.currentProjectId), {
has_errors: values.filters.hasErrors ?? undefined,
order_by: orderByParam(values.sorting),
date_from: values.dateFilter.dateFrom || undefined,
date_to: values.dateFilter.dateTo || undefined,
limit: SESSIONS_PAGE_SIZE,
offset: 0,
...sharedFilterParams(values.sharedQueryFilters),
})
// A newer reset load supersedes this one. Publishing a superseded page would
// put stale session rows on screen, and loadSessionsSuccess reads session_start
// off them to bound the selected session's detail scan.
breakpoint()
actions.setHasNext(response.has_next ?? false)
return [...(response.results ?? [])]
},
// Load more: append the next page at offset = current length.
loadMoreSessions: async () => {
if (!values.currentProjectId) {
return values.sessions
}
// Keep a query snapshot because a reset can finish before this page.
// Discard the old page instead of merging it into the new list.
const baseSessions = values.sessions
const generation = cache.sessionsGeneration ?? 0
const filters = values.filters
const orderBy = orderByParam(values.sorting)
const dateFrom = values.dateFilter.dateFrom
const dateTo = values.dateFilter.dateTo
const sharedFilters = values.sharedQueryFilters
const response = await mcpAnalyticsSessionsList(String(values.currentProjectId), {
has_errors: filters.hasErrors ?? undefined,
order_by: orderBy,
date_from: dateFrom || undefined,
date_to: dateTo || undefined,
limit: SESSIONS_PAGE_SIZE,
offset: baseSessions.length,
...sharedFilterParams(sharedFilters),
})
if (
generation !== cache.sessionsGeneration ||
filters !== values.filters ||
orderBy !== orderByParam(values.sorting) ||
dateFrom !== values.dateFilter.dateFrom ||
dateTo !== values.dateFilter.dateTo ||
sharedFilters !== values.sharedQueryFilters
) {
return values.sessions
}
actions.setHasNext(response.has_next ?? false)
return [...baseSessions, ...(response.results ?? [])]
},
},
],
toolCalls: [
EMPTY_TOOL_CALLS,
{
// First page for a session. Replaces the value, tagged with the session it's for.
loadToolCalls: async (sessionId: string, breakpoint) => {
cache.toolCallsGeneration = (cache.toolCallsGeneration ?? 0) + 1
if (!values.currentProjectId || !sessionId) {
return EMPTY_TOOL_CALLS
}
const filters = values.sharedQueryFilters
const page = await fetchToolCallsPage(
values.currentProjectId,
sessionId,
values.selectedSession?.session_start,
0,
filters
).catch((error) => {
breakpoint()
throw error
})
breakpoint()
return { sessionId, filters, ...page }
},
// Load more: append the next page at offset = current length.
loadMoreToolCalls: async () => {
const { sessionId, filters, calls } = values.toolCalls
const generation = cache.toolCallsGeneration ?? 0
if (!values.currentProjectId || !sessionId) {
return values.toolCalls
}
const page = await fetchToolCallsPage(
values.currentProjectId,
sessionId,
values.selectedSession?.session_start,
calls.length,
filters ?? values.sharedQueryFilters
)
// If the user switched sessions or changed the shared filters while this page
// was loading, drop it: appending one set's calls onto another's would show the
// wrong data. The backend orders by (timestamp, event_id), so pages that do
// belong together don't overlap and need no dedupe.
if (
generation !== cache.toolCallsGeneration ||
sessionId !== values.selectedSessionId ||
filters !== values.sharedQueryFilters
) {
return values.toolCalls
}
return { sessionId, filters, calls: [...calls, ...page.calls], hasNext: page.hasNext }
},
},
],
generatedIntent: [
null as MCPSessionIntentApi | null,
{
generateIntent: async (sessionId: string) => {
if (!values.currentProjectId || !sessionId) {
return null
}
// session_id comes from untrusted event properties — encode it so path/query
// delimiters can't redirect this POST to another same-origin endpoint. Bound the
// intent scan by the session's start so older sessions resolve, mirroring
// loadToolCalls. The shared filters never move session_start, so this bound
// still covers the whole session, which is what the persisted summary describes.
return await mcpAnalyticsSessionsGenerateIntent(
String(values.currentProjectId),
encodeURIComponent(sessionId),
{ date_from: values.selectedSession?.session_start || undefined }
)
},
},
],
})),
reducers({
toolCallsLoadFailed: [
false,
{
loadToolCalls: () => false,
loadToolCallsFailure: () => true,
},
],
filters: [
DEFAULT_FILTERS,
{
setFilters: (state, { filters }) => ({ ...state, ...filters }),
},
],
dateFilter: [
DEFAULT_DATE_FILTER,
{
setDateFilter: (_, { dateFrom, dateTo }): MCPSessionsDateFilter => ({ dateFrom, dateTo }),
},
],
selectedSessionId: [
null as string | null,
{
selectSession: (_, { sessionId }) => sessionId,
},
],
sorting: [
DEFAULT_SORTING as MCPSessionSorting | null,
{
setSorting: (_, { sorting }) => sorting,
},
],
hasNext: [
false,
{
setHasNext: (_, { hasNext }) => hasNext,
// Hide "Load more" the moment a reset starts so it isn't shown (disabled,
// spinning) during the reset; setHasNext restores it when the page resolves.
loadSessions: () => false,
},
],
intentOverrides: [
{} as Record<string, string>,
{
generateIntentSuccess: (state, { generatedIntent }) =>
generatedIntent?.intent
? { ...state, [generatedIntent.session_id]: generatedIntent.intent }
: state,
},
],
generatingSessionId: [
null as string | null,
{
generateIntent: (_, sessionId) => sessionId,
generateIntentSuccess: () => null,
generateIntentFailure: () => null,
},
],
}),
selectors({
hasActiveFilters: [
(s) => [s.filters, s.dateFilter, s.sharedQueryFilters],
(
filters: MCPSessionsFilters,
dateFilter: MCPSessionsDateFilter,
sharedQueryFilters: MCPSharedQueryFilters
): boolean =>
filters.hasErrors !== null ||
dateFilter.dateFrom !== DEFAULT_DATE_FILTER.dateFrom ||
dateFilter.dateTo !== DEFAULT_DATE_FILTER.dateTo ||
sharedQueryFilters.properties.length > 0 ||
sharedQueryFilters.filterTestAccounts,
],
selectedSession: [
(s) => [s.sessions, s.selectedSessionId],
(sessions: MCPSessionApi[], selectedSessionId: string | null): MCPSessionApi | null => {
if (!selectedSessionId) {
return null
}
return sessions.find((session) => session.session_id === selectedSessionId) ?? null
},
],
selectedSessionIntent: [
(s) => [s.selectedSession, s.intentOverrides, s.selectedSessionId],
(
selectedSession: MCPSessionApi | null,
intentOverrides: Record<string, string>,
selectedSessionId: string | null
): string => {
if (selectedSessionId && intentOverrides[selectedSessionId]) {
return intentOverrides[selectedSessionId]
}
return selectedSession?.intent ?? ''
},
],
// True only while a generation for the *currently selected* session is running, so a
// generation kicked off for another session never shows a spinner on this one.
isSelectedSessionGenerating: [
(s) => [s.generatedIntentLoading, s.generatingSessionId, s.selectedSessionId],
(
generatedIntentLoading: boolean,
generatingSessionId: string | null,
selectedSessionId: string | null
): boolean => generatedIntentLoading && generatingSessionId === selectedSessionId,
],
// Everything the detail panel needs about the selected session's calls, derived from the
// loaded value (tagged with its session) so a previous session's calls never render under
// the new session's header. A plain comparison — no shared loader flag a concurrent load
// more could flip.
selectedSessionToolCalls: [
(s) => [s.toolCalls, s.selectedSessionId, s.toolCallsLoading, s.sharedQueryFilters, s.toolCallsLoadFailed],
(
toolCalls: SessionToolCalls,
selectedSessionId: string | null,
toolCallsLoading: boolean,
sharedQueryFilters: MCPSharedQueryFilters,
toolCallsLoadFailed: boolean
): {
calls: MCPToolCallApi[]
hasNext: boolean
loading: boolean
loadingMore: boolean
error: boolean
} => {
const isCurrent = toolCalls.sessionId === selectedSessionId && toolCalls.filters === sharedQueryFilters
return {
calls: isCurrent ? toolCalls.calls : [],
hasNext: isCurrent && toolCalls.hasNext,
// First page still loading: the loaded value isn't for the selected session yet.
loading: selectedSessionId !== null && !isCurrent && !toolCallsLoadFailed,
error: selectedSessionId !== null && toolCallsLoadFailed,
// A "Load more" append is in flight for the session already on screen.
loadingMore: isCurrent && toolCallsLoading,
}
},
],
}),
listeners(({ actions, values }) => {
const reloadForSharedFilters = (): void => {
actions.loadSessions()
if (values.selectedSessionId) {
actions.loadToolCalls(values.selectedSessionId)
}
}
return {
setFilters: () => {
actions.loadSessions()
},
setDateFilter: () => {
actions.loadSessions()
},
setSorting: () => {
actions.loadSessions()
},
hydrateFilters: reloadForSharedFilters,
setFilterTestAccounts: reloadForSharedFilters,
setPropertyFilters: reloadForSharedFilters,
refreshSessions: reloadForSharedFilters,
selectSession: ({ sessionId }) => {
if (sessionId) {
actions.loadToolCalls(sessionId)
}
},
generateIntentFailure: () => {
lemonToast.error('Could not generate the session intent. Please try again.')
},
loadSessionsSuccess: ({ sessions }) => {
if (sessions.length === 0) {
if (values.selectedSessionId) {
actions.selectSession(null)
}
return
}
const stillVisible = values.selectedSessionId
? sessions.some((s) => s.session_id === values.selectedSessionId)
: false
if (!stillVisible) {
actions.selectSession(sessions[0].session_id)
}
},
}
}),
// The date range follows users across MCP analytics tabs. The error filter applies only to Sessions.
actionToUrl(({ values }) => {
const syncUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => {
const { currentLocation } = router.values
const searchParams = { ...currentLocation.searchParams }
const params: Record<string, string | null> = {
date_from: values.dateFilter.dateFrom,
date_to: values.dateFilter.dateTo,
search: null,
has_errors: values.filters.hasErrors === null ? null : String(values.filters.hasErrors),
}
for (const [key, value] of Object.entries(params)) {
if (value) {
searchParams[key] = value
} else {
delete searchParams[key]
}
}
return [currentLocation.pathname, searchParams, currentLocation.hashParams, { replace: true }]
}
return {
setDateFilter: syncUrl,
setFilters: syncUrl,
}
}),
urlToAction(({ actions, values, cache }) => ({
[urls.mcpAnalyticsSessions()]: (_, 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
const hasErrors = parseUrlBoolean(searchParams.has_errors)
const filtersChanged = hasErrors !== values.filters.hasErrors
// setFilters / setDateFilter each reload via their listener; only load directly when
// neither changed and we haven't loaded yet.
if (filtersChanged) {
actions.setFilters({ hasErrors })
}
if (dateChanged) {
actions.setDateFilter(dateFrom, dateTo)
} else if (!filtersChanged && !cache.hasLoaded) {
actions.loadSessions()
}
cache.hasLoaded = true
},
})),
afterMount(({ actions, cache }) => {
// urlToAction owns the initial load when the Sessions URL carries route parameters. This
// is the fallback for a param-less mount (and off-route mounts in tests, where urlToAction
// never fires). The cache.hasLoaded guard keeps a deep-linked load from firing twice.
const { searchParams } = router.values
const hasUrlParams =
typeof searchParams.date_from === 'string' ||
typeof searchParams.date_to === 'string' ||
searchParams.has_errors !== undefined
if (!hasUrlParams && !cache.hasLoaded) {
cache.hasLoaded = true
actions.loadSessions()
}
}),
])