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(mcp-analytics): list notification types in one table (#101712)

Lucas Faria1fe0484eed48
diff --git a/docs/published/docs/mcp-analytics/notifications.mdx b/docs/published/docs/mcp-analytics/notifications.mdx
index 90c586d05e17..7f495bc8bae2 100644
--- a/docs/published/docs/mcp-analytics/notifications.mdx
+++ b/docs/published/docs/mcp-analytics/notifications.mdx
@@ -10,6 +10,9 @@ Which one you want depends on the question.
Use a recurring report for anything you'd think about periodically, like what agents keep trying to do.
Use an instant alert for something you'd want to know about immediately, like one of your tools breaking.
+The **Notifications** tab lists every kind of notification in one table, with its cadence and whether it is on.
+Expand a row to see what it sends, and the destinations you have set up for it.
+
## Recurring reports
A recurring report is an AI-written summary of your MCP traffic, delivered on a schedule.
@@ -36,7 +39,7 @@ Because a report summarizes a window of time, it stays useful on a low-volume se
An instant alert reaches you as soon as something happens that you'd want to know about right away: **a failed tool call**, captured as `$mcp_tool_call` with `$mcp_is_error`.
-To create one, select **Notify me** under **Instant alerts**, then choose a channel.
+To create one, select **Set up** on the **A tool call failed** row, then choose a channel.
PostHog prefills the message with the tool, your server, the agent's client, and its intent.
You can customize it later from the alert's own page.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 8c495418af45..bd64a34280e4 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9348,6 +9348,22 @@ snapshots:
hash: v1.k794b7964.e1dfe15b20b22dec1f74881db821597e40d534cf0c9773fc032948311de642f7.iAS_FuPfykHZ7rjy90ExdGbsAT1eKhSIwVLvxUg1aGM
scenes-app-mcp-analytics-missing-capabilities-preview--example-reports--light:
hash: v1.k794b7964.428de360c05be96069166fcf43a1b02ae48d7dea500d8f9caf9371fbc7ab8bac.LfbPCIHegnJwRBMnkSmipZH3IutsBu1DYRFH3tQGNRU
+ scenes-app-mcp-analytics-notification-types-table--loading--dark:
+ hash: v1.k794b7964.ec6ef9403c11fe69423832f39c758eb8c35b82f213bf5592d5b90cece9590c13.E6jL-gC2B0yKgf-wsB_9LygDEQJMxMO-8oeH38IOByA
+ scenes-app-mcp-analytics-notification-types-table--loading--light:
+ hash: v1.k794b7964.d9d61ad56f4643d5b88c74cf5107ed8433c771c487a9d64e1c0623b63eca9326.EXHwe7QTB2eIevF4QJIQ98Z5jLV3oI0PrLMMRSxXlNg
+ scenes-app-mcp-analytics-notification-types-table--mixed-states--dark:
+ hash: v1.k794b7964.0b585dff0f92db3c32117ef5bc773927607dda8835e607593cc45d58bca5b2bf.YqFG-70G-8m_KaFe4hzyoYX25osVZ8uff2tpXVpy5lE
+ scenes-app-mcp-analytics-notification-types-table--mixed-states--light:
+ hash: v1.k794b7964.f068a594f18002730fb0dd498f9da2e8efb964125ef00a803a6a226479deb488.rp5wW53w7OYBS7lLe_0FpaVAobsJqskOVPJ6bY5Zej4
+ scenes-app-mcp-analytics-notification-types-table--narrow-scene--dark:
+ hash: v1.k794b7964.4097d670e35243ed026de6d0fca9020dcf7dc26d775de57b89dcbd9003e6d8e0.8_x5MTZ6_J8KXWAa1bu6LhWfZPvPvaSQr95vMFzGjZA
+ scenes-app-mcp-analytics-notification-types-table--narrow-scene--light:
+ hash: v1.k794b7964.d8eb396c3864dd84e84b61a14167f312ac789634063562ca2c480a48d3838104.YHQrunRg_ERBH3ck1txmuNeqopTOcG2LuGWZq9-lGLI
+ scenes-app-mcp-analytics-notification-types-table--nothing-set-up--dark:
+ hash: v1.k794b7964.b33c74ffb5531cf86afcd5fa718200c83a0863450ca85a5c94d026264f81dc4c.awlyXScQ759I0zP7I5rQA8PEIunmftZStWnJ90q-tpw
+ scenes-app-mcp-analytics-notification-types-table--nothing-set-up--light:
+ hash: v1.k794b7964.d0cb2086e12994284977aa2d895e1214c0261d2505022d9df4aef0d15c6562c6.fKwM2EVKz22cubQjamzL4YJN2CWRvtdpvYIifmijXtA
scenes-app-mcp-analytics-tool-quality-charts--in-progress-bucket--dark:
hash: v1.k794b7964.6dd3665d59b7590cdbba24e83fb952ffc45f74dc15e5811b5bfe004af314ead6.sGmDMl0-TraAucPmgpjftNcfxWrhDZXgFgxRNVUFp1Y
scenes-app-mcp-analytics-tool-quality-charts--in-progress-bucket--light:
diff --git a/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsx b/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsx
index 15d9ad877ecf..b2c2c5c47de8 100644
--- a/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsx
+++ b/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsx
@@ -1,286 +1,55 @@
-import { useActions, useValues } from 'kea'
-import { combineUrl, router } from 'kea-router'
-import { useEffect } from 'react'
+import { LemonBanner, Link } from '@posthog/lemon-ui'
-import { IconPlus, IconWarning } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonCard, LemonSkeleton, LemonSwitch, LemonTag, Link } from '@posthog/lemon-ui'
-
-import { ConfirmDeleteButton } from 'lib/components/ConfirmDeleteButton'
-import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
-import { OrganizationMembershipLevel } from 'lib/constants'
-import { HogFunctionIcon } from 'scenes/hog-functions/configuration/HogFunctionIcon'
-import { urlForHogFunction } from 'scenes/hog-functions/list/HogFunctionsList'
import { NewNotificationDialog } from 'scenes/hog-functions/list/NewNotificationDialog'
-import { newNotificationDialogLogic } from 'scenes/hog-functions/list/newNotificationDialogLogic'
-import { getNotificationDescription } from 'scenes/hog-functions/list/notificationDescription'
-import { NotificationSlackPreview } from 'scenes/hog-functions/sub-templates/NotificationSlackPreview'
-import {
- MCP_NOTIFICATION_BUTTON_LABELS,
- MCPMessageField,
- MCPNotificationSubTemplateId,
- mcpNotificationPreviewMessage,
-} from 'scenes/hog-functions/sub-templates/sub-templates'
import { urls } from 'scenes/urls'
-import { HogFunctionType } from '~/types'
-
-import {
- getMCPNotificationUseCase,
- mcpAnalyticsNotificationsLogic,
- MCPNotificationUseCase,
-} from './mcpAnalyticsNotificationsLogic'
-import { MCPNotificationExample, mcpNotificationExamplesLogic } from './mcpNotificationExamplesLogic'
+import { INSTANT_ALERT_USE_CASES, useInstantAlertRows } from './instantAlertRows'
import { AI_REPORT_LIST_LIMIT } from './mcpRecurringReportsLogic'
import { NotificationTypesTable } from './NotificationTypesTable'
import { useRecurringReportRows } from './recurringReportRows'
-interface MCPUseCaseConfig {
- useCase: MCPNotificationUseCase
- subTemplateId: MCPNotificationSubTemplateId
- icon: JSX.Element
- headline: string
- lead: string
- dialogTitle: string
- /** Shown until the project's own latest event loads; the copy always comes from the template. */
- sample: Record<MCPMessageField, string>
- /** Caption for a preview built from the project's own event. */
- realCaption: string
-}
-
-const USE_CASES: MCPUseCaseConfig[] = [
- {
- useCase: 'tool-error',
- subTemplateId: 'mcp-tool-error',
- icon: <IconWarning />,
- headline: 'A tool call failed',
- lead: 'Which tool broke, what the agent wanted, and a link to the detail.',
- dialogTitle: 'Notify me about failing tool calls',
- sample: {
- clientName: 'Claude Code',
- serverName: 'acme-mcp',
- intent: 'find out why signups dropped after Tuesday’s release',
- toolName: 'query-events',
- },
- realCaption: 'Your most recent',
- },
-]
-
-function NotificationRow({ notification }: { notification: HogFunctionType }): JSX.Element {
- const { notificationsLoading, pendingToggleIds } = useValues(mcpAnalyticsNotificationsLogic)
- const { toggleNotificationEnabled, deleteNotification } = useActions(mcpAnalyticsNotificationsLogic)
- const { searchParams } = useValues(router)
-
- const description = getNotificationDescription(notification)
-
- return (
- <div className="flex items-center gap-2 rounded border p-2">
- <HogFunctionIcon src={notification.icon_url} size="small" />
- <div className="min-w-0 flex-1">
- <Link
- to={urlForHogFunction(
- notification,
- // Carry the scene's shared params (date range) so returning doesn't reset them
- combineUrl(urls.mcpAnalyticsNotifications(), searchParams).url
- )}
- className="font-medium truncate"
- >
- {notification.name}
- </Link>
- {description ? <div className="text-xs text-muted truncate">{description}</div> : null}
- </div>
- <LemonSwitch
- checked={notification.enabled}
- onChange={() => toggleNotificationEnabled(notification.id, !notification.enabled)}
- loading={!!pendingToggleIds[notification.id]}
- // Refresh in flight: a mutation started now could be clobbered by the stale response
- disabled={notificationsLoading}
- aria-label={`Enable ${notification.name}`}
- />
- <ConfirmDeleteButton
- onDelete={() => deleteNotification(notification)}
- disabledReason={
- notificationsLoading
- ? 'Refreshing notifications…'
- : pendingToggleIds[notification.id]
- ? 'Waiting for the enable/disable update to finish…'
- : undefined
- }
- data-attr="mcp-analytics-notification-delete"
- />
- </div>
- )
-}
-
-interface UseCaseCardProps {
- config: MCPUseCaseConfig
- notifications: HogFunctionType[]
- onAdd: () => void
- addDisabledReason?: string
- /** The project's own latest event for this use case, once it has loaded. */
- example?: MCPNotificationExample
-}
+export function MCPAnalyticsNotifications(): JSX.Element {
+ const alerts = useInstantAlertRows()
+ const reports = useRecurringReportRows()
+ const rows = [...(alerts.failed ? [] : alerts.rows), ...(reports.failed ? [] : reports.rows)]
-function UseCaseCard({ config, notifications, onAdd, addDisabledReason, example }: UseCaseCardProps): JSX.Element {
return (
- <LemonCard hoverEffect={false} className="flex flex-col gap-2 p-3">
- <div className="flex items-start justify-between gap-2">
- <div className="flex min-w-0 items-start gap-1.5">
- <span className="mt-0.5 shrink-0 text-muted">{config.icon}</span>
- <div className="min-w-0">
- <h3 className="m-0 text-sm font-semibold">{config.headline}</h3>
- <p className="m-0 text-xs text-muted">{config.lead}</p>
- </div>
- </div>
- <LemonButton
- type={notifications.length > 0 ? 'secondary' : 'primary'}
- size="xsmall"
- icon={<IconPlus />}
- onClick={onAdd}
- disabledReason={addDisabledReason}
- data-attr={`mcp-analytics-add-notification-${config.useCase}`}
+ <div className="@container flex flex-col gap-3" data-attr="mcp-analytics-notifications">
+ {alerts.failed && (
+ <LemonBanner
+ type="error"
+ action={{ children: 'Try again', onClick: alerts.reload }}
+ data-attr="mcp-analytics-notifications-load-error"
>
- {notifications.length > 0 ? 'Add' : 'Notify me'}
- </LemonButton>
- </div>
-
- <NotificationSlackPreview
- message={mcpNotificationPreviewMessage(example ?? config.sample)}
- buttonLabel={MCP_NOTIFICATION_BUTTON_LABELS[config.subTemplateId]}
- caption={example ? config.realCaption : 'Example'}
- />
-
- {notifications.length > 0 && (
- <div className="flex flex-col gap-1">
- {notifications.map((notification) => (
- <NotificationRow key={notification.id} notification={notification} />
- ))}
- </div>
+ We couldn't load your MCP alerts. Please try again in a moment.
+ </LemonBanner>
)}
- </LemonCard>
- )
-}
-
-export function MCPAnalyticsNotifications(): JSX.Element {
- const { notifications, notificationsLoaded, notificationsFailed } = useValues(mcpAnalyticsNotificationsLogic)
- const { loadNotifications } = useActions(mcpAnalyticsNotificationsLogic)
- const { examples } = useValues(mcpNotificationExamplesLogic)
- const reports = useRecurringReportRows()
- const { loadExamples } = useActions(mcpNotificationExamplesLogic)
- const addDisabledReason = useRestrictedArea({
- scope: RestrictionScope.Project,
- minimumAccessLevel: OrganizationMembershipLevel.Admin,
- })
-
- useEffect(() => {
- loadNotifications()
- // The previews render sample copy straight away and upgrade to the project's own events when
- // this lands, so there's deliberately no loading state to wait on.
- loadExamples()
- }, [loadNotifications, loadExamples])
-
- const onCreated = (): void => {
- loadNotifications()
- }
-
- // One dialog logic per use case, called in a fixed order so the hook calls stay stable.
- const { openDialog: openToolErrorDialog } = useActions(
- newNotificationDialogLogic({ subTemplateId: 'mcp-tool-error', onCreated })
- )
- const openDialogFor: Record<MCPNotificationSubTemplateId, () => void> = {
- 'mcp-tool-error': openToolErrorDialog,
- }
-
- // Anything the filters matched but we can't classify still needs a home, so it can't be
- // silently dropped from the list.
- const unclassified = notifications.filter((notification) => !getMCPNotificationUseCase(notification))
-
- const instantAlerts = notificationsFailed ? (
- <LemonBanner
- type="error"
- action={{ children: 'Try again', onClick: () => loadNotifications() }}
- data-attr="mcp-analytics-notifications-load-error"
- >
- We couldn't load your MCP alerts. Please try again in a moment.
- </LemonBanner>
- ) : !notificationsLoaded ? (
- <div className="grid gap-2 md:grid-cols-2">
- {USE_CASES.map((config) => (
- <LemonCard key={config.useCase} hoverEffect={false} className="flex flex-col gap-2 p-3">
- <LemonSkeleton className="h-4 w-48 max-w-full" />
- <LemonSkeleton className="h-16 w-full" />
- </LemonCard>
- ))}
- </div>
- ) : (
- <>
- <div className="grid gap-2 md:grid-cols-2">
- {USE_CASES.map((config) => (
- <UseCaseCard
- key={config.useCase}
- config={config}
- notifications={notifications.filter(
- (notification) => getMCPNotificationUseCase(notification) === config.useCase
- )}
- onAdd={openDialogFor[config.subTemplateId]}
- addDisabledReason={addDisabledReason ?? undefined}
- example={examples[config.useCase]}
- />
- ))}
- </div>
-
- {unclassified.length > 0 && (
- <LemonCard hoverEffect={false} className="flex flex-col gap-1 p-3">
- <h3 className="m-0 text-sm font-semibold">Other MCP alerts</h3>
- {unclassified.map((notification) => (
- <NotificationRow key={notification.id} notification={notification} />
- ))}
- </LemonCard>
+ {reports.failed && (
+ <LemonBanner
+ type="error"
+ action={{ children: 'Try again', onClick: reports.reload }}
+ data-attr="mcp-analytics-recurring-reports-load-error"
+ >
+ We couldn't load your MCP reports. Please try again in a moment.
+ </LemonBanner>
)}
- </>
- )
- return (
- <div className="@container flex flex-col gap-6" data-attr="mcp-analytics-notifications">
- <section className="flex flex-col gap-2">
- <div className="flex flex-wrap items-center gap-1.5">
- <h2 className="m-0 text-base font-semibold">Recurring reports</h2>
- <LemonTag type="completion">Beta</LemonTag>
- </div>
- {reports.failed ? (
- <LemonBanner
- type="error"
- action={{ children: 'Try again', onClick: reports.reload }}
- data-attr="mcp-analytics-recurring-reports-load-error"
- >
- We couldn't load your MCP reports. Please try again in a moment.
- </LemonBanner>
- ) : (
- <NotificationTypesTable rows={reports.rows} />
- )}
- {/* Say so rather than quietly dropping the tail — an invisible report is the bug this
- whole section exists to fix. */}
- {reports.truncated && (
- <p className="m-0 text-xs text-muted">
- Showing the first {AI_REPORT_LIST_LIMIT} reports.{' '}
- <Link to={urls.subscriptions()}>See all subscriptions</Link> for the rest.
- </p>
- )}
- </section>
+ {rows.length > 0 && <NotificationTypesTable rows={rows} />}
- <section className="flex flex-col gap-2">
- <h2 className="m-0 text-base font-semibold">Instant alerts</h2>
- <p className="m-0 text-sm text-muted">
- One message per event, for the things you'd want to hear about the moment they happen. A busy server
- can send a lot of these.
+ {/* Say so rather than quietly dropping the tail — an invisible report is the bug this
+ whole section exists to fix. */}
+ {reports.truncated && (
+ <p className="m-0 text-xs text-muted">
+ Showing the first {AI_REPORT_LIST_LIMIT} reports.{' '}
+ <Link to={urls.subscriptions()}>See all subscriptions</Link> for the rest.
</p>
- {instantAlerts}
- </section>
+ )}
- {USE_CASES.map((config) => (
+ {INSTANT_ALERT_USE_CASES.map((config) => (
<NewNotificationDialog
key={config.subTemplateId}
subTemplateId={config.subTemplateId}
- onCreated={onCreated}
+ onCreated={alerts.reload}
title={config.dialogTitle}
/>
))}
diff --git a/products/mcp_analytics/frontend/notifications/NotificationTypesTable.stories.tsx b/products/mcp_analytics/frontend/notifications/NotificationTypesTable.stories.tsx
new file mode 100644
index 000000000000..fe1f26fb6c55
--- /dev/null
+++ b/products/mcp_analytics/frontend/notifications/NotificationTypesTable.stories.tsx
@@ -0,0 +1,126 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { IconCalendar, IconPlus, IconWarning } from '@posthog/icons'
+import { LemonButton, LemonTag } from '@posthog/lemon-ui'
+
+import { NotificationSlackPreview } from 'scenes/hog-functions/sub-templates/NotificationSlackPreview'
+
+import { NotificationTypeRow, NotificationTypesTable } from './NotificationTypesTable'
+import { MCP_RECURRING_REPORTS } from './recurringReportDefinitions'
+import { RecurringReportDetails } from './RecurringReportDetails'
+import { SavedNotificationRow } from './SavedNotificationRow'
+
+const meta: Meta = {
+ title: 'Scenes-App/MCP Analytics/Notification Types Table',
+ parameters: { layout: 'padded' },
+}
+export default meta
+
+type Story = StoryObj
+
+const noop = (): void => {}
+
+function savedRow(name: string, summary: string, enabled: boolean): JSX.Element {
+ return (
+ <SavedNotificationRow
+ key={name}
+ name={name}
+ to="#"
+ summary={summary}
+ enabled={enabled}
+ onToggle={noop}
+ toggleLoading={false}
+ onDelete={noop}
+ deleteDataAttr="story-delete"
+ />
+ )
+}
+
+const alertRow: NotificationTypeRow = {
+ key: 'alert-tool-error',
+ icon: <IconWarning />,
+ headline: 'A tool call failed',
+ lead: 'Which tool broke, what the agent wanted, and a link to the detail.',
+ cadence: 'instant',
+ saved: { total: 2, enabled: 1, truncated: false },
+ action: (
+ <LemonButton type="secondary" size="small" icon={<IconPlus />}>
+ Add
+ </LemonButton>
+ ),
+ preview: (
+ <NotificationSlackPreview
+ message="*query-events* failed on your MCP server *acme-mcp* (client: Claude Code). Agent intent: _find out why signups dropped after Tuesday's release_"
+ buttonLabel="View tool detail"
+ caption="Example"
+ />
+ ),
+ savedRows: [
+ savedRow('Failing tool calls to #mcp-alerts', 'Slack · #mcp-alerts', true),
+ savedRow('Failing tool calls to on-call email', 'Email · [email protected]', false),
+ ],
+}
+
+const reportRows: NotificationTypeRow[] = MCP_RECURRING_REPORTS.map((report) => ({
+ key: `report-${report.key}`,
+ icon: <IconCalendar />,
+ headline: report.headline,
+ lead: report.lead,
+ tag: (
+ <LemonTag type="completion" size="small">
+ Beta
+ </LemonTag>
+ ),
+ cadence: report.frequency,
+ saved: { total: 0, enabled: 0, truncated: false },
+ action: (
+ <LemonButton type="primary" size="small">
+ Set up
+ </LemonButton>
+ ),
+ preview: <RecurringReportDetails covers={report.covers} prompt={report.prompt} />,
+ savedRows: [],
+}))
+
+export const MixedStates: Story = {
+ render: () => <NotificationTypesTable rows={[alertRow, ...reportRows]} />,
+}
+
+export const NothingSetUp: Story = {
+ render: () => (
+ <NotificationTypesTable
+ rows={[
+ {
+ ...alertRow,
+ saved: { total: 0, enabled: 0, truncated: false },
+ savedRows: [],
+ action: (
+ <LemonButton type="primary" size="small">
+ Set up
+ </LemonButton>
+ ),
+ },
+ ...reportRows,
+ ]}
+ />
+ ),
+}
+
+export const Loading: Story = {
+ // The skeletons are the point of this story, so the runner must not wait for them to go away.
+ parameters: { testOptions: { waitForLoadersToDisappear: false } },
+ render: () => (
+ <NotificationTypesTable
+ rows={[alertRow, ...reportRows].map((row) => ({ ...row, saved: undefined, savedRows: [] }))}
+ />
+ ),
+}
+
+export const NarrowScene: Story = {
+ render: () => (
+ // An inline-size container needs a width of its own, or the story root collapses to nothing.
+ <div className="@container w-lg max-w-full">
+ <NotificationTypesTable rows={[alertRow, ...reportRows]} />
+ </div>
+ ),
+}
diff --git a/products/mcp_analytics/frontend/notifications/instantAlertRows.tsx b/products/mcp_analytics/frontend/notifications/instantAlertRows.tsx
new file mode 100644
index 000000000000..0900bbbdb378
--- /dev/null
+++ b/products/mcp_analytics/frontend/notifications/instantAlertRows.tsx
@@ -0,0 +1,184 @@
+import { useActions, useValues } from 'kea'
+import { combineUrl, router } from 'kea-router'
+import { useEffect } from 'react'
+
+import { IconPlus, IconWarning } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { OrganizationMembershipLevel } from 'lib/constants'
+import { HogFunctionIcon } from 'scenes/hog-functions/configuration/HogFunctionIcon'
+import { urlForHogFunction } from 'scenes/hog-functions/list/HogFunctionsList'
+import { newNotificationDialogLogic } from 'scenes/hog-functions/list/newNotificationDialogLogic'
+import { getNotificationDescription } from 'scenes/hog-functions/list/notificationDescription'
+import { NotificationSlackPreview } from 'scenes/hog-functions/sub-templates/NotificationSlackPreview'
+import {
+ MCP_NOTIFICATION_BUTTON_LABELS,
+ MCPMessageField,
+ MCPNotificationSubTemplateId,
+ mcpNotificationPreviewMessage,
+} from 'scenes/hog-functions/sub-templates/sub-templates'
+import { urls } from 'scenes/urls'
+
+import { HogFunctionType } from '~/types'
+
+import { mcpAnalyticsNotificationsLogic, MCPNotificationUseCase } from './mcpAnalyticsNotificationsLogic'
+import { mcpNotificationExamplesLogic } from './mcpNotificationExamplesLogic'
+import { countSaved, NotificationTypeRow } from './NotificationTypesTable'
+import { SavedNotificationRow } from './SavedNotificationRow'
+
+export interface InstantAlertUseCase {
+ useCase: MCPNotificationUseCase
+ subTemplateId: MCPNotificationSubTemplateId
+ icon: JSX.Element
+ headline: string
+ lead: string
+ dialogTitle: string
+ /** Shown until the project's own latest event loads; the copy always comes from the template. */
+ sample: Record<MCPMessageField, string>
+ /** Caption for a preview built from the project's own event. */
+ realCaption: string
+}
+
+export const INSTANT_ALERT_USE_CASES: InstantAlertUseCase[] = [
+ {
+ useCase: 'tool-error',
+ subTemplateId: 'mcp-tool-error',
+ icon: <IconWarning />,
+ headline: 'A tool call failed',
+ lead: 'Which tool broke, what the agent wanted, and a link to the detail.',
+ dialogTitle: 'Notify me about failing tool calls',
+ sample: {
+ clientName: 'Claude Code',
+ serverName: 'acme-mcp',
+ intent: 'find out why signups dropped after Tuesday’s release',
+ toolName: 'query-events',
+ },
+ realCaption: 'Your most recent',
+ },
+]
+
+function NotificationRow({ notification }: { notification: HogFunctionType }): JSX.Element {
+ const { notificationsLoading, pendingToggleIds } = useValues(mcpAnalyticsNotificationsLogic)
+ const { toggleNotificationEnabled, deleteNotification } = useActions(mcpAnalyticsNotificationsLogic)
+ const { searchParams } = useValues(router)
+
+ return (
+ <SavedNotificationRow
+ icon={<HogFunctionIcon src={notification.icon_url} size="small" />}
+ name={notification.name}
+ to={urlForHogFunction(
+ notification,
+ // Carry the scene's shared params (date range) so returning doesn't reset them
+ combineUrl(urls.mcpAnalyticsNotifications(), searchParams).url
+ )}
+ summary={getNotificationDescription(notification)}
+ enabled={notification.enabled}
+ onToggle={(enabled) => toggleNotificationEnabled(notification.id, enabled)}
+ toggleLoading={!!pendingToggleIds[notification.id]}
+ // Refresh in flight: a mutation started now could be clobbered by the stale response
+ toggleDisabled={notificationsLoading}
+ onDelete={() => deleteNotification(notification)}
+ deleteDisabledReason={
+ notificationsLoading
+ ? 'Refreshing notifications…'
+ : pendingToggleIds[notification.id]
+ ? 'Waiting for the enable/disable update to finish…'
+ : undefined
+ }
+ deleteDataAttr="mcp-analytics-notification-delete"
+ />
+ )
+}
+
+export interface InstantAlertRows {
+ rows: NotificationTypeRow[]
+ loaded: boolean
+ failed: boolean
+ reload: () => void
+}
+
+export function useInstantAlertRows(): InstantAlertRows {
+ const {
+ notificationsByUseCase,
+ unclassifiedNotifications,
+ notificationsLoaded,
+ notificationsFailed,
+ notificationsTruncated,
+ } = useValues(mcpAnalyticsNotificationsLogic)
+ const { loadNotifications } = useActions(mcpAnalyticsNotificationsLogic)
+ const { examples } = useValues(mcpNotificationExamplesLogic)
+ const { loadExamples } = useActions(mcpNotificationExamplesLogic)
+ const addDisabledReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: OrganizationMembershipLevel.Admin,
+ })
+
+ useEffect(() => {
+ loadNotifications()
+ // The previews render sample copy straight away and upgrade to the project's own events when
+ // this lands, so there's deliberately no loading state to wait on.
+ loadExamples()
+ }, [loadNotifications, loadExamples])
+
+ // One dialog logic per use case, called in a fixed order so the hook calls stay stable.
+ const { openDialog: openToolErrorDialog } = useActions(
+ newNotificationDialogLogic({ subTemplateId: 'mcp-tool-error', onCreated: loadNotifications })
+ )
+ const openDialogFor: Record<MCPNotificationSubTemplateId, () => void> = {
+ 'mcp-tool-error': openToolErrorDialog,
+ }
+
+ const rows: NotificationTypeRow[] = INSTANT_ALERT_USE_CASES.map((config) => {
+ const saved = notificationsByUseCase[config.useCase] ?? []
+ // A cut list may hide a match past the page limit, so it never gets a primary "Set up".
+ const mayExist = saved.length > 0 || notificationsTruncated
+ const example = examples[config.useCase]
+ return {
+ key: `alert-${config.useCase}`,
+ icon: config.icon,
+ headline: config.headline,
+ lead: config.lead,
+ cadence: 'instant',
+ saved: notificationsLoaded ? countSaved(saved, notificationsTruncated) : undefined,
+ action: (
+ <LemonButton
+ type={mayExist ? 'secondary' : 'primary'}
+ size="small"
+ icon={mayExist ? <IconPlus /> : undefined}
+ onClick={openDialogFor[config.subTemplateId]}
+ disabledReason={addDisabledReason ?? undefined}
+ data-attr={`mcp-analytics-add-notification-${config.useCase}`}
+ >
+ {mayExist ? 'Add' : 'Set up'}
+ </LemonButton>
+ ),
+ preview: (
+ <NotificationSlackPreview
+ message={mcpNotificationPreviewMessage(example ?? config.sample)}
+ buttonLabel={MCP_NOTIFICATION_BUTTON_LABELS[config.subTemplateId]}
+ caption={example ? config.realCaption : 'Example'}
+ />
+ ),
+ savedRows: saved.map((notification) => (
+ <NotificationRow key={notification.id} notification={notification} />
+ )),
+ }
+ })
+
+ const unclassified = unclassifiedNotifications
+ if (unclassified.length > 0) {
+ rows.push({
+ key: 'alert-other',
+ icon: <IconWarning />,
+ headline: 'Other MCP alerts',
+ lead: 'Alerts on MCP events that do not match a template above.',
+ saved: countSaved(unclassified, notificationsTruncated),
+ savedRows: unclassified.map((notification) => (
+ <NotificationRow key={notification.id} notification={notification} />
+ )),
+ })
+ }
+
+ return { rows, loaded: notificationsLoaded, failed: notificationsFailed, reload: loadNotifications }
+}
diff --git a/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.test.ts b/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.test.ts
index c56dfa0cb4f2..00b51a27ea2d 100644
--- a/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.test.ts
+++ b/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.test.ts
@@ -87,6 +87,19 @@ describe('mcpAnalyticsNotificationsLogic', () => {
expect(listSpy.mock.calls[0][0]).not.toHaveProperty('full')
})
+ it('groups notifications by use case and keeps unclassified ones', async () => {
+ const toolError = makeNotification('a')
+ const other = makeNotification('b', {
+ filters: { events: [{ id: '$mcp_missing_capability', type: 'events' }] },
+ })
+ listSpy.mockReset().mockResolvedValue({ count: 2, next: null, previous: null, results: [toolError, other] })
+
+ await expectLogic(logic, () => logic.actions.loadNotifications()).toFinishAllListeners()
+
+ expect(logic.values.notificationsByUseCase['tool-error']).toEqual([toolError])
+ expect(logic.values.unclassifiedNotifications).toEqual([other])
+ })
+
it('keeps the fetched rows and warns when the list is truncated', async () => {
const notifications = [makeNotification('a'), makeNotification('b')]
listSpy.mockReset().mockResolvedValue({
diff --git a/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.ts b/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.ts
index 7e8ee2916a8a..5b85fa44886b 100644
--- a/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.ts
+++ b/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'
+import { actions, afterMount, connect, kea, listeners, MakeLogicType, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
@@ -33,12 +33,14 @@ export interface mcpAnalyticsNotificationsLogicValues {
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.
@@ -103,9 +105,21 @@ export interface mcpAnalyticsNotificationsLogicActions {
}
}
+// 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
+ mcpAnalyticsNotificationsLogicActions,
+ Record<string, any>,
+ mcpAnalyticsNotificationsLogicMeta
>
export const mcpAnalyticsNotificationsLogic = kea<mcpAnalyticsNotificationsLogicType>([
@@ -231,6 +245,29 @@ export const mcpAnalyticsNotificationsLogic = kea<mcpAnalyticsNotificationsLogic
},
],
}),
+ 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.