: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 { actions, afterMount, connect, kea, listeners, MakeLogicType, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import posthog from 'lib/posthog-typed'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { getFiltersFromSubTemplateId } from 'scenes/hog-functions/list/LinkedHogFunctions'
import { projectLogic } from 'scenes/projectLogic'
import { CyclotronJobFiltersType, HogFunctionSubTemplateIdType, HogFunctionType } from '~/types'
const MCP_NOTIFICATION_LIST_LIMIT = 500
const MCP_NOTIFICATION_SUB_TEMPLATE_IDS: HogFunctionSubTemplateIdType[] = ['mcp-tool-error']
function getMCPNotificationFilterGroups(): CyclotronJobFiltersType[] {
return MCP_NOTIFICATION_SUB_TEMPLATE_IDS.map((id) => getFiltersFromSubTemplateId(id)).filter(
(filters): filters is CyclotronJobFiltersType => !!filters
)
}
export type MCPNotificationUseCase = 'tool-error'
export function getMCPNotificationUseCase(fn: Pick<HogFunctionType, 'filters'>): MCPNotificationUseCase | null {
const events = fn.filters?.events ?? []
return events.some((event) => event.id === '$mcp_tool_call') ? 'tool-error' : null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpAnalyticsNotificationsLogicValues {
currentProjectId: number | null // projectLogic
notificationCount: number
notificationCountLoading: boolean
notifications: HogFunctionType[]
notificationsByUseCase: Partial<Record<MCPNotificationUseCase, HogFunctionType[]>>
notificationsFailed: boolean
notificationsLoaded: boolean
notificationsLoading: boolean
notificationsTruncated: boolean
pendingDeleteIds: Record<string, true>
pendingToggleIds: Record<string, true>
unclassifiedNotifications: HogFunctionType[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpAnalyticsNotificationsLogicActions {
deleteNotification: (notification: HogFunctionType) => {
notification: HogFunctionType
}
deleteNotificationSettled: (notificationId: string) => {
notificationId: string
}
deleteNotificationStarted: (notificationId: string) => {
notificationId: string
}
loadNotificationCount: () => any
loadNotificationCountFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadNotificationCountSuccess: (
notificationCount: number,
payload?: any
) => {
notificationCount: number
payload?: any
}
loadNotifications: () => any
loadNotificationsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadNotificationsSuccess: (
notifications: HogFunctionType[],
payload?: any
) => {
notifications: HogFunctionType[]
payload?: any
}
setNotifications: (notifications: HogFunctionType[]) => {
notifications: HogFunctionType[]
}
setNotificationsTruncated: (notificationsTruncated: boolean) => {
notificationsTruncated: boolean
}
toggleNotificationEnabled: (
notificationId: string,
enabled: boolean
) => {
enabled: boolean
notificationId: string
}
toggleNotificationEnabledSettled: (notificationId: string) => {
notificationId: string
}
toggleNotificationEnabledStarted: (notificationId: string) => {
notificationId: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpAnalyticsNotificationsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
notificationsByUseCase: (
notifications: HogFunctionType[]
) => Partial<Record<MCPNotificationUseCase, HogFunctionType[]>>
unclassifiedNotifications: (notifications: HogFunctionType[]) => HogFunctionType[]
}
}
export type mcpAnalyticsNotificationsLogicType = MakeLogicType<
mcpAnalyticsNotificationsLogicValues,
mcpAnalyticsNotificationsLogicActions,
Record<string, any>,
mcpAnalyticsNotificationsLogicMeta
>
export const mcpAnalyticsNotificationsLogic = kea<mcpAnalyticsNotificationsLogicType>([
path(['products', 'mcp_analytics', 'frontend', 'notifications', 'mcpAnalyticsNotificationsLogic']),
connect(() => ({
values: [projectLogic, ['currentProjectId']],
})),
actions({
toggleNotificationEnabled: (notificationId: string, enabled: boolean) => ({ notificationId, enabled }),
toggleNotificationEnabledStarted: (notificationId: string) => ({ notificationId }),
toggleNotificationEnabledSettled: (notificationId: string) => ({ notificationId }),
deleteNotification: (notification: HogFunctionType) => ({ notification }),
deleteNotificationStarted: (notificationId: string) => ({ notificationId }),
deleteNotificationSettled: (notificationId: string) => ({ notificationId }),
setNotificationsTruncated: (notificationsTruncated: boolean) => ({ notificationsTruncated }),
// Local (optimistic) writes go through this rather than the loader's success action, which
// would also clear `notificationsLoading` and hide a reload that is still in flight.
setNotifications: (notifications: HogFunctionType[]) => ({ notifications }),
}),
loaders(({ actions, values }) => ({
notificationCount: [
0,
{
loadNotificationCount: async (): Promise<number> => {
const response = await api.hogFunctions.list({
filter_groups: getMCPNotificationFilterGroups(),
types: ['destination'],
limit: 1,
})
return response.count
},
},
],
notifications: [
[] as HogFunctionType[],
{
loadNotifications: async (): Promise<HogFunctionType[]> => {
const response = await api.hogFunctions.list({
filter_groups: getMCPNotificationFilterGroups(),
types: ['destination'],
full: true,
limit: MCP_NOTIFICATION_LIST_LIMIT,
})
const notificationsTruncated = !!response.next
actions.setNotificationsTruncated(notificationsTruncated)
if (notificationsTruncated) {
lemonToast.warning(
`Showing the first ${MCP_NOTIFICATION_LIST_LIMIT} notifications — manage the rest from the data pipelines page.`
)
}
// A reload can race in-flight mutations: a GET that read the DB before a
// toggle/delete landed would otherwise revert the toggle or resurrect the
// deleted row. Keep the local value for rows with a pending mutation.
return response.results
.filter((notification) => !notification.deleted && !values.pendingDeleteIds[notification.id])
.map((notification) => {
if (!values.pendingToggleIds[notification.id]) {
return notification
}
const local = values.notifications.find((item) => item.id === notification.id)
return local ? { ...notification, enabled: local.enabled } : notification
})
},
},
],
})),
reducers({
notifications: {
setNotifications: (_: HogFunctionType[], { notifications }: { notifications: HogFunctionType[] }) =>
notifications,
},
notificationsTruncated: [
false,
{
setNotificationsTruncated: (_, { notificationsTruncated }) => notificationsTruncated,
},
],
pendingToggleIds: [
{} as Record<string, true>,
{
toggleNotificationEnabledStarted: (state, { notificationId }) => ({
...state,
[notificationId]: true,
}),
toggleNotificationEnabledSettled: (state, { notificationId }) => {
const nextState = { ...state }
delete nextState[notificationId]
return nextState
},
},
],
pendingDeleteIds: [
{} as Record<string, true>,
{
deleteNotificationStarted: (state, { notificationId }) => ({
...state,
[notificationId]: true,
}),
deleteNotificationSettled: (state, { notificationId }) => {
const nextState = { ...state }
delete nextState[notificationId]
return nextState
},
},
],
notificationsFailed: [
false,
{
loadNotifications: () => false,
loadNotificationsSuccess: () => false,
loadNotificationsFailure: () => true,
},
],
// The list loads lazily when the tab mounts; without this flag the tab's first
// render (before the load kicks off) would flash the empty state.
notificationsLoaded: [
false,
{
loadNotificationsSuccess: () => true,
loadNotificationsFailure: () => true,
},
],
}),
selectors({
notificationsByUseCase: [
(s) => [s.notifications],
(notifications: HogFunctionType[]): Partial<Record<MCPNotificationUseCase, HogFunctionType[]>> =>
notifications.reduce<Partial<Record<MCPNotificationUseCase, HogFunctionType[]>>>(
(grouped, notification) => {
const useCase = getMCPNotificationUseCase(notification)
if (useCase) {
;(grouped[useCase] ??= []).push(notification)
}
return grouped
},
{}
),
],
// Anything the filters matched but we can't classify still needs a home, so it can't be
// silently dropped from the list.
unclassifiedNotifications: [
(s) => [s.notifications],
(notifications: HogFunctionType[]): HogFunctionType[] =>
notifications.filter((notification) => !getMCPNotificationUseCase(notification)),
],
}),
listeners(({ actions, values }) => {
// Preserve the server total while the list is capped. Optimistic deletes can leave it
// slightly stale until the next count reload, which is more accurate than replacing it with 500.
const syncCountFromList = (notifications: HogFunctionType[]): void => {
if (values.notificationsTruncated) {
return
}
actions.loadNotificationCountSuccess(notifications.length)
}
return {
// If a reload was already in flight when a mutation settled, that GET read pre-mutation
// state and its pending-id tombstone is now cleared — reload once more so the stale
// response can't revert a confirmed toggle or resurrect a confirmed delete.
toggleNotificationEnabledSettled: () => {
if (values.notificationsLoading) {
actions.loadNotifications()
}
},
deleteNotificationSettled: () => {
if (values.notificationsLoading) {
actions.loadNotifications()
}
},
loadNotificationsSuccess: ({ notifications }) => syncCountFromList(notifications),
setNotifications: ({ notifications }) => syncCountFromList(notifications),
toggleNotificationEnabled: async ({ notificationId, enabled }) => {
if (values.pendingToggleIds[notificationId]) {
return
}
const target = values.notifications.find((notification) => notification.id === notificationId)
if (!target) {
return
}
actions.toggleNotificationEnabledStarted(notificationId)
const previousEnabled = target.enabled
const applyEnabled = (next: boolean): void => {
actions.setNotifications(
values.notifications.map((notification) =>
notification.id === notificationId ? { ...notification, enabled: next } : notification
)
)
}
applyEnabled(enabled)
try {
const updatedNotification = await api.hogFunctions.update(notificationId, { enabled })
actions.setNotifications(
values.notifications.map((notification) =>
notification.id === notificationId ? updatedNotification : notification
)
)
} catch (error) {
applyEnabled(previousEnabled)
lemonToast.error('Failed to update notification')
posthog.captureException(error, {
action: 'toggle-mcp-analytics-notification',
notification: notificationId,
})
} finally {
actions.toggleNotificationEnabledSettled(notificationId)
}
},
deleteNotification: async ({ notification }) => {
actions.deleteNotificationStarted(notification.id)
actions.setNotifications(values.notifications.filter((item) => item.id !== notification.id))
let callbackFired = false
await deleteWithUndo({
endpoint: `projects/${values.currentProjectId}/hog_functions`,
object: { id: notification.id, name: notification.name },
callback: (undo) => {
callbackFired = true
// Settle before reloading so the undone row isn't filtered back out
actions.deleteNotificationSettled(notification.id)
if (undo) {
actions.loadNotifications()
}
},
})
if (!callbackFired) {
actions.deleteNotificationSettled(notification.id)
actions.loadNotifications()
}
},
}
}),
afterMount(({ actions }) => {
actions.loadNotificationCount()
}),
])