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): first-party notification destinations for MCP events (#69140)

Lucas Faria9420e0ee3918
diff --git a/docs/published/docs/mcp-analytics/notifications.mdx b/docs/published/docs/mcp-analytics/notifications.mdx
new file mode 100644
index 000000000000..cf0ff252bf02
--- /dev/null
+++ b/docs/published/docs/mcp-analytics/notifications.mdx
@@ -0,0 +1,54 @@
+---
+title: MCP analytics notifications
+sidebar: Docs
+showTitle: true
+---
+
+MCP analytics can reach you in Slack, Microsoft Teams, Discord, email, or any webhook, in two ways: a recurring written summary, or an instant alert on a single event.
+
+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.
+
+## Recurring reports
+
+A recurring report is an AI-written summary of your MCP traffic, delivered on a schedule.
+Two are ready to set up from the **Notifications** tab:
+
+- **What agents are trying to do** (weekly) groups and ranks agent goals in their own words, and shows which of them keep ending in failure.
+- **How your tools held up** (weekly) covers calls per tool, error rate, the most common error types, and p95 latency.
+
+To set one up:
+
+1. Open **MCP analytics** and select the **Notifications** tab.
+2. Under **Recurring reports**, select **Set up** on the report you want.
+3. Choose where it should go and how often, then create it.
+
+The report's question is already written for you, and you can edit it before saving.
+
+Recurring reports are built on PostHog's AI subscriptions, which are in early access.
+If you don't see a **Set up** button, turn on **AI subscriptions** in your [feature previews](https://app.posthog.com/settings/user-feature-previews) first.
+Your organization also needs to approve AI data processing in its settings.
+
+Because a report summarizes a window of time, it stays useful on a low-volume server and can't flood a channel.
+
+## Instant alerts
+
+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.
+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.
+
+The alert is deduplicated per failing tool: if one tool fails a hundred times in a row you get one message, not a hundred, and each additional tool that starts failing still gets its own.
+A tool that is still broken reappears after 30 minutes.
+You can change this under **Trigger options** on the alert's page, including turning deduplication off.
+
+## Manage alerts and reports
+
+Instant alerts are standard CDP destinations, so you can also manage them from the data pipelines page.
+To use another destination type, create it manually with the same MCP events and filters.
+Recurring reports appear alongside your other subscriptions, where you can edit, pause, or delete them.
+
+Slack requires the PostHog Slack integration.
+Microsoft Teams, Discord, and webhook destinations only need a webhook URL.
diff --git a/frontend/src/scenes/surveys/components/ConfirmDeleteButton.tsx b/frontend/src/lib/components/ConfirmDeleteButton.tsx
similarity index 87%
rename from frontend/src/scenes/surveys/components/ConfirmDeleteButton.tsx
rename to frontend/src/lib/components/ConfirmDeleteButton.tsx
index bacccadf484b..946cccc04215 100644
--- a/frontend/src/scenes/surveys/components/ConfirmDeleteButton.tsx
+++ b/frontend/src/lib/components/ConfirmDeleteButton.tsx
@@ -11,6 +11,7 @@ interface ConfirmDeleteButtonProps {
onDelete: () => void
idleLabel?: string
confirmLabel?: string
+ disabledReason?: string
'data-attr'?: string
}
@@ -18,6 +19,7 @@ export function ConfirmDeleteButton({
onDelete,
idleLabel = 'Delete',
confirmLabel = 'Confirm?',
+ disabledReason,
'data-attr': dataAttr,
}: ConfirmDeleteButtonProps): JSX.Element {
const [armed, setArmed] = useState(false)
@@ -57,7 +59,14 @@ export function ConfirmDeleteButton({
/>
)}
</AnimatePresence>
- <LemonButton size="small" icon={<IconTrash />} status="danger" data-attr={dataAttr} onClick={handleClick}>
+ <LemonButton
+ size="small"
+ icon={<IconTrash />}
+ status="danger"
+ disabledReason={disabledReason}
+ data-attr={dataAttr}
+ onClick={handleClick}
+ >
{armed ? confirmLabel : idleLabel}
</LemonButton>
<span aria-live="polite" aria-atomic="true" className="sr-only">
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 75bf918c7c4e..bde2904598f8 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -177,6 +177,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/mcp-analytics/tool-quality': ['MCPAnalytics', 'mcpAnalyticsToolQuality'],
'/mcp-analytics/tool-quality/:toolName': ['MCPAnalyticsToolDetail', 'mcpAnalyticsTool'],
'/mcp-analytics/intent-clustering': ['MCPAnalytics', 'mcpAnalyticsIntentClustering'],
+ '/mcp-analytics/notifications': ['MCPAnalytics', 'mcpAnalyticsNotifications'],
'/metrics': ['Metrics', 'metrics'],
'/tasks': ['TaskTracker', 'taskTracker'],
'/tasks/:taskId': ['TaskTracker', 'taskDetail'],
@@ -1198,6 +1199,7 @@ export const productUrls = {
mcpAnalyticsToolQuality: (): string => '/mcp-analytics/tool-quality',
mcpAnalyticsTool: (toolName: string): string => `/mcp-analytics/tool-quality/${encodeURIComponent(toolName)}`,
mcpAnalyticsIntentClustering: (): string => '/mcp-analytics/intent-clustering',
+ mcpAnalyticsNotifications: (): string => '/mcp-analytics/notifications',
metrics: (): string => '/metrics',
notebooks: (): string => '/notebooks',
notebook: (shortId: string): string => `/notebooks/${shortId}`,
diff --git a/frontend/src/scenes/hog-functions/list/newNotificationDialogLogic.test.ts b/frontend/src/scenes/hog-functions/list/newNotificationDialogLogic.test.ts
new file mode 100644
index 000000000000..a7f0f57d429a
--- /dev/null
+++ b/frontend/src/scenes/hog-functions/list/newNotificationDialogLogic.test.ts
@@ -0,0 +1,64 @@
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { newNotificationDialogLogic } from './newNotificationDialogLogic'
+
+describe('newNotificationDialogLogic', () => {
+ let logic: ReturnType<typeof newNotificationDialogLogic.build>
+ let createSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team/integrations': { count: 0, results: [] },
+ },
+ })
+ initKeaTests()
+ jest.spyOn(api.hogFunctions, 'getTemplate').mockResolvedValue({
+ id: 'template-slack',
+ code: 'print(1)',
+ inputs_schema: [],
+ icon_url: null,
+ } as any)
+ createSpy = jest.spyOn(api.hogFunctions, 'create').mockResolvedValue({ id: 'created' } as any)
+
+ logic = newNotificationDialogLogic({ subTemplateId: 'mcp-tool-error', onCreated: () => {} })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.restoreAllMocks()
+ })
+
+ // A broken MCP tool fails on every call and agents retry in loops, so this destination is only
+ // safe to ship deduped. The sub-template declares masking; if creation stops forwarding it the
+ // alert silently goes back to one message per event, which is what makes it floodable.
+ it('creates the MCP failure alert deduped per failing tool', async () => {
+ // Slack rather than a webhook destination: the webhook validator calls URL.canParse, which
+ // jsdom doesn't implement, so it throws before the form can submit.
+ logic.actions.setNotificationFormValues({
+ destination: 'slack',
+ slackIntegrationId: 1,
+ slackChannel: 'C123|alerts',
+ })
+
+ await expectLogic(logic, () => logic.actions.submitNotificationForm()).toFinishAllListeners()
+
+ expect(createSpy).toHaveBeenCalledTimes(1)
+ const masking = createSpy.mock.calls[0][0].masking
+ expect(masking).toMatchObject({ ttl: 30 * 60 })
+ // Keyed on the effective tool, so each distinct broken tool still gets through.
+ expect(masking.hash).toContain('$mcp_tool_name')
+ expect(masking.hash).toContain('$mcp_exec_tool_call_name')
+ // The filters only require $mcp_is_error, so an event can arrive with neither tool-name
+ // property. HogMaskerService skips masking when the hash evaluates falsy, so the expression
+ // has to yield a constant for those rather than an empty string.
+ expect(masking.hash).toContain("!= ''")
+ expect(masking.hash).toContain('unknown-tool')
+ })
+})
diff --git a/frontend/src/scenes/hog-functions/list/newNotificationDialogLogic.ts b/frontend/src/scenes/hog-functions/list/newNotificationDialogLogic.ts
index 5deab8f80397..bac2d521d3b2 100644
--- a/frontend/src/scenes/hog-functions/list/newNotificationDialogLogic.ts
+++ b/frontend/src/scenes/hog-functions/list/newNotificationDialogLogic.ts
@@ -219,6 +219,9 @@ export const newNotificationDialogLogic = kea<newNotificationDialogLogicType>([
inputs_schema: template.inputs_schema,
inputs,
filters: props.filtersOverride ?? commonProps.filters,
+ // Without this a sub-template's masking is dropped on creation and the
+ // destination fires on every matching event, however the template declared it.
+ masking: subTemplate?.masking ?? commonProps.masking ?? null,
hog: template.code,
icon_url: template.icon_url,
enabled: true,
diff --git a/frontend/src/scenes/hog-functions/list/notificationDescription.test.ts b/frontend/src/scenes/hog-functions/list/notificationDescription.test.ts
new file mode 100644
index 000000000000..42e039e35c1c
--- /dev/null
+++ b/frontend/src/scenes/hog-functions/list/notificationDescription.test.ts
@@ -0,0 +1,15 @@
+import { getNotificationDescription } from './notificationDescription'
+
+describe('getNotificationDescription', () => {
+ test.each([
+ [{ url: { value: 'https://hooks.example.com/path' } }, 'hooks.example.com'],
+ [{ url: { value: 'not a valid URL' } }, 'not a valid URL'],
+ [{ webhookUrl: { value: 'https://discord.com/api/webhooks/123/token' } }, 'discord.com'],
+ [{ webhookUrl: { value: 'not a valid webhook URL' } }, 'not a valid webhook URL'],
+ [{ channel: { value: '#alerts' } }, '#alerts'],
+ [{ email: { value: '[email protected]' } }, '[email protected]'],
+ [undefined, null],
+ ])('returns the destination description for inputs %#', (inputs, expected) => {
+ expect(getNotificationDescription({ inputs })).toBe(expected)
+ })
+})
diff --git a/frontend/src/scenes/hog-functions/list/notificationDescription.ts b/frontend/src/scenes/hog-functions/list/notificationDescription.ts
new file mode 100644
index 000000000000..6c4c2bcfcee7
--- /dev/null
+++ b/frontend/src/scenes/hog-functions/list/notificationDescription.ts
@@ -0,0 +1,23 @@
+import { HogFunctionType } from '~/types'
+
+export function getNotificationDescription(fn: Pick<HogFunctionType, 'inputs'>): string | null {
+ const inputs = fn.inputs
+ if (!inputs) {
+ return null
+ }
+ const destinationUrl = inputs.url?.value || inputs.webhookUrl?.value
+ if (destinationUrl) {
+ try {
+ return new URL(String(destinationUrl)).hostname
+ } catch {
+ return String(destinationUrl)
+ }
+ }
+ if (inputs.channel?.value) {
+ return String(inputs.channel.value)
+ }
+ if (inputs.email?.value) {
+ return String(inputs.email.value)
+ }
+ return null
+}
diff --git a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts
index 5492d6f3e833..60ee90e20692 100644
--- a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts
+++ b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts
@@ -1,6 +1,7 @@
import { FEATURE_FLAGS, INSIGHT_ALERT_FIRING_SUB_TEMPLATE_ID } from 'lib/constants'
import {
+ CyclotronJobFilterEvents,
HogFunctionConfigurationContextId,
HogFunctionSubTemplateIdType,
HogFunctionSubTemplateType,
@@ -19,6 +20,47 @@ import {
export const errorTrackingIssueLinkHogTemplate = (medium: string): string =>
`{project.url}/error_tracking/fingerprint/{replaceAll(replaceAll(encodeURLComponent(event.properties.fingerprint), '(', '%28'), ')', '%29')}?timestamp={event.properties.exception_timestamp}&utm_source=alert&utm_campaign=error_tracking_alert&utm_medium=${medium}`
+// In single-exec mode $mcp_tool_name is always the 'exec' dispatcher; the inner tool the agent
+// actually invoked rides on $mcp_exec_tool_call_name, so fall back the same way the backend does.
+const MCP_EFFECTIVE_TOOL_EXPR =
+ 'event.properties.$mcp_exec_tool_call_name ? event.properties.$mcp_exec_tool_call_name : event.properties.$mcp_tool_name'
+
+// How long one failing tool stays deduped. Long enough to collapse a retry loop, short enough that
+// a breakage that is still happening reappears in the channel.
+const MCP_ALERT_MASKING_TTL_SECONDS = 30 * 60
+
+// The masking key, which must never evaluate to an empty value: HogMaskerService skips masking
+// outright when the hash expression is falsy, so an event carrying neither tool-name property (the
+// filters only require $mcp_is_error, so anyone with the project token can send one) would
+// otherwise escape deduplication entirely. Nameless events all collapse into one bucket instead.
+const MCP_ALERT_MASKING_HASH =
+ `{concat(${MCP_EFFECTIVE_TOOL_EXPR}) != '' ` + `? concat(${MCP_EFFECTIVE_TOOL_EXPR}) : 'unknown-tool'}`
+
+// Every MCP failure notification triggers on an errored $mcp_tool_call. SDK versions stamp
+// $mcp_is_error as a boolean, the string 'true', or 1, so all three encodings are matched (CDP
+// compiles a multi-value Exact to IN, which the realtime bytecode rewrites to type-coercing
+// comparisons). Passing `errorType` narrows to one of the semantic buckets the SDK sets on
+// $mcp_error_type — see products/mcp_analytics/backend/hogql_queries/tool_tables.py for the list.
+function mcpFailedToolCallEvent(errorType?: string): CyclotronJobFilterEvents {
+ const properties: CyclotronJobFilterEvents['properties'] = [
+ {
+ key: '$mcp_is_error',
+ type: PropertyFilterType.Event,
+ value: ['true', true, 1],
+ operator: PropertyOperator.Exact,
+ },
+ ]
+ if (errorType) {
+ properties.push({
+ key: '$mcp_error_type',
+ type: PropertyFilterType.Event,
+ value: [errorType],
+ operator: PropertyOperator.Exact,
+ })
+ }
+ return { id: '$mcp_tool_call', type: 'events', properties }
+}
+
export const HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES: Record<
HogFunctionSubTemplateIdType,
Pick<HogFunctionSubTemplateType, 'sub_template_id' | 'type' | 'context_id'> &
@@ -47,6 +89,17 @@ export const HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES: Record<
context_id: 'standard',
filters: { events: [{ id: '$feature_enrollment_update', type: 'events' }] },
},
+ 'mcp-tool-error': {
+ sub_template_id: 'mcp-tool-error',
+ type: 'destination',
+ context_id: 'standard',
+ filters: { events: [mcpFailedToolCallEvent()] },
+ // Deduped per failing tool, not per call. A broken tool fails on every invocation and
+ // agents retry in loops, so an undeduped alert would post a message per event — enough to
+ // bury a channel, and amplifiable by anyone holding the (public) project token. One message
+ // per tool per interval still surfaces each distinct breakage.
+ masking: { hash: MCP_ALERT_MASKING_HASH, ttl: MCP_ALERT_MASKING_TTL_SECONDS, threshold: null },
+ },
'activity-log': {
sub_template_id: 'activity-log',
type: 'internal_destination',
@@ -274,7 +327,203 @@ function buildHealthAlertSubTemplates(
]
}
+// All $mcp_* text is producer-controlled and unbounded, so every interpolation is escaped
+// for the target chat format and truncated (post-escape, so entity expansion can't blow
+// past provider message limits: Slack 3000/section, Discord 2000/message).
+//
+// Discord worst case: message (template text + 3 fields x 200 + intent 600, all post-escape,
+// ~1260) + link (base ~80 + encoded tool name up to 480) = ~1820 < 2000.
+const MCP_INTENT_MAX_LENGTH = 600
+const MCP_FIELD_MAX_LENGTH = 200
+// The tool name is never shortened for the link. Truncating changes the tool's identity — the
+// detail page exact-matches the full event property, so a shortened link resolves to nothing —
+// and cutting mid-character can leave a lone surrogate, which makes encodeURLComponent throw
+// and drops the notification entirely. A name whose encoded form exceeds this budget links to
+// the tool list instead: less specific, still correct.
+const MCP_URL_ENCODED_TOOL_BUDGET = 480
+
+type ChatEscaper = (expression: string, maxLength?: number) => string
+
+/**
+ * Bounds a producer-controlled value before escaping it, so the escape never scans more than it
+ * can keep. Escaping only ever grows a string, so N output characters can come from at most N
+ * input characters — cutting the input at the same limit leaves the bounded result identical while
+ * keeping the work off a multi-megabyte property. The trailing bound still has to be applied after
+ * escaping, since expansion can push a short input past the limit.
+ */
+function boundedExpr(expression: string, maxLength: number): string {
+ return `substring(concat(${expression}), 1, ${maxLength})`
+}
+
+function slackEscapeExpr(expression: string, maxLength: number = MCP_FIELD_MAX_LENGTH): string {
+ // concat, not toString: concat(null) renders '' (matching bare {} interpolation), toString(null) prints 'null'
+ const bounded = boundedExpr(expression, maxLength)
+ return `substring(replaceAll(replaceAll(replaceAll(${bounded}, '&', '&amp;'), '<', '&lt;'), '>', '&gt;'), 1, ${maxLength})`
+}
+
+function markdownEscapeExpr(expression: string, maxLength: number = MCP_FIELD_MAX_LENGTH): string {
+ // Breaking the `](` adjacency is enough to neutralize masked links [text](url) in
+ // Discord and Teams; Discord mass mentions are already suppressed by the destination
+ // template's allowed_mentions, and Teams mentions can't be triggered from text.
+ return `substring(replaceAll(${boundedExpr(expression, maxLength)}, '](', '] ('), 1, ${maxLength})`
+}
+
+/** The producer-controlled values a notification message interpolates. */
+export type MCPMessageField = 'clientName' | 'serverName' | 'intent' | 'toolName'
+type MCPFieldRenderer = (field: MCPMessageField) => string
+
+// Renders each field as an escaped, length-bounded Hog interpolation.
+function hogFieldRenderer(escape: ChatEscaper): MCPFieldRenderer {
+ return (field) => {
+ switch (field) {
+ case 'clientName':
+ return `{${escape('event.properties.$mcp_client_name')}}`
+ case 'serverName':
+ return `{${escape('event.properties.$mcp_server_name')}}`
+ case 'intent':
+ return `{${escape('event.properties.$mcp_intent', MCP_INTENT_MAX_LENGTH)}}`
+ case 'toolName':
+ return `{${escape(MCP_EFFECTIVE_TOOL_EXPR)}}`
+ }
+ }
+}
+
+// The message copy lives here once; the Hog templates and the in-app preview differ only in how
+// fields are rendered, so the preview can never drift from what actually gets delivered.
+function mcpToolFailureMessage(field: MCPFieldRenderer, bold: string): string {
+ return (
+ `${bold}${field('toolName')}${bold} failed on your MCP server ` +
+ `${bold}${field('serverName')}${bold} ` +
+ `(client: ${field('clientName')}). ` +
+ `Agent intent: _${field('intent')}_`
+ )
+}
+
+export type MCPNotificationSubTemplateId = 'mcp-tool-error'
+
+export const MCP_NOTIFICATION_BUTTON_LABELS: Record<MCPNotificationSubTemplateId, string> = {
+ 'mcp-tool-error': 'View tool detail',
+}
+
+/**
+ * The caps the delivered message applies to each interpolated field. Exported so a preview built
+ * from real event values cuts them exactly where the chat provider will, instead of showing more
+ * than actually gets sent.
+ */
+export const MCP_MESSAGE_FIELD_LIMITS: Record<MCPMessageField, number> = {
+ clientName: MCP_FIELD_MAX_LENGTH,
+ serverName: MCP_FIELD_MAX_LENGTH,
+ toolName: MCP_FIELD_MAX_LENGTH,
+ intent: MCP_INTENT_MAX_LENGTH,
+}
+
+/**
+ * The Slack message a notification will post, rendered with sample values in place of the Hog
+ * expressions — for previewing the real copy before wiring a destination up.
+ */
+export function mcpNotificationPreviewMessage(values: Record<MCPMessageField, string>): string {
+ const field: MCPFieldRenderer = (name) => values[name]
+ return mcpToolFailureMessage(field, '*')
+}
+
+const MCP_TOOL_ERROR_SLACK_MESSAGE = mcpToolFailureMessage(hogFieldRenderer(slackEscapeExpr), '*')
+const MCP_TOOL_ERROR_MARKDOWN_MESSAGE = mcpToolFailureMessage(hogFieldRenderer(markdownEscapeExpr), '**')
+
+const MCP_ENCODED_EFFECTIVE_TOOL_EXPR = `encodeURLComponent(concat(${MCP_EFFECTIVE_TOOL_EXPR}))`
+// Deep-links to the failing tool, falling back to the tool list when the encoded name would
+// blow the Discord budget (see MCP_URL_ENCODED_TOOL_BUDGET). project.url stays a plain
+// substitution so only the path suffix is conditional.
+const MCP_TOOL_ERROR_LINK =
+ `{project.url}/mcp-analytics/tool-quality` +
+ `{length(${MCP_ENCODED_EFFECTIVE_TOOL_EXPR}) <= ${MCP_URL_ENCODED_TOOL_BUDGET}` +
+ ` ? concat('/', ${MCP_ENCODED_EFFECTIVE_TOOL_EXPR}) : ''}`
+
+interface MCPNotificationVariantsOptions {
+ subTemplateId: HogFunctionSubTemplateIdType
+ nameSuffix: string
+ description: string
+ webhookDescription: string
+ slackMessage: string
+ slackFallbackText: string
+ markdownMessage: string
+ slackButton: { url: string; label: string }
+}
+
+function mcpNotificationVariants({
+ subTemplateId,
+ nameSuffix,
+ description,
+ webhookDescription,
+ slackMessage,
+ slackFallbackText,
+ markdownMessage,
+ slackButton,
+}: MCPNotificationVariantsOptions): HogFunctionSubTemplateType[] {
+ const commonProperties = HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES[subTemplateId]
+
+ return [
+ {
+ ...commonProperties,
+ template_id: 'template-slack',
+ name: `Post to Slack ${nameSuffix}`,
+ description,
+ inputs: {
+ blocks: {
+ value: [
+ { type: 'section', text: { type: 'mrkdwn', text: slackMessage } },
+ {
+ type: 'actions',
+ elements: [
+ {
+ url: slackButton.url,
+ text: { text: slackButton.label, type: 'plain_text' },
+ type: 'button',
+ },
+ ],
+ },
+ ],
+ },
+ text: { value: slackFallbackText },
+ },
+ },
+ {
+ ...commonProperties,
+ template_id: 'template-microsoft-teams',
+ name: `Post to Microsoft Teams ${nameSuffix}`,
+ description,
+ inputs: {
+ text: { value: markdownMessage },
+ },
+ },
+ {
+ ...commonProperties,
+ template_id: 'template-discord',
+ name: `Post to Discord ${nameSuffix}`,
+ description,
+ inputs: {
+ content: { value: markdownMessage },
+ },
+ },
+ {
+ ...commonProperties,
+ template_id: 'template-webhook',
+ name: `HTTP Webhook ${nameSuffix}`,
+ description: webhookDescription,
+ },
+ ]
+}
+
export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, HogFunctionSubTemplateType[]> = {
+ 'mcp-tool-error': mcpNotificationVariants({
+ subTemplateId: 'mcp-tool-error',
+ nameSuffix: 'when an MCP tool call fails',
+ description: 'Know the moment agents hit an error on one of your tools',
+ webhookDescription: 'Send failing tool calls to your own endpoint',
+ slackMessage: MCP_TOOL_ERROR_SLACK_MESSAGE,
+ slackFallbackText: 'An MCP tool call failed',
+ markdownMessage: `${MCP_TOOL_ERROR_MARKDOWN_MESSAGE}\n\n${MCP_TOOL_ERROR_LINK}`,
+ slackButton: { url: MCP_TOOL_ERROR_LINK, label: MCP_NOTIFICATION_BUTTON_LABELS['mcp-tool-error'] },
+ }),
'survey-response': [
{
...HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES['survey-response'],
diff --git a/frontend/src/scenes/surveys/components/SurveyNotifications.tsx b/frontend/src/scenes/surveys/components/SurveyNotifications.tsx
index 4b0cfd856252..24f7d7df2c0c 100644
--- a/frontend/src/scenes/surveys/components/SurveyNotifications.tsx
+++ b/frontend/src/scenes/surveys/components/SurveyNotifications.tsx
@@ -3,43 +3,21 @@ import { useActions, useValues } from 'kea'
import { IconCopy, IconPlus } from '@posthog/icons'
import { LemonButton, LemonMenu, LemonSkeleton, LemonSwitch } from '@posthog/lemon-ui'
+import { ConfirmDeleteButton } from 'lib/components/ConfirmDeleteButton'
import { MailHog } from 'lib/components/hedgehogs'
import { LemonMenuItems } from 'lib/lemon-ui/LemonMenu/LemonMenu'
import { HogFunctionIcon } from 'scenes/hog-functions/configuration/HogFunctionIcon'
-import { ConfirmDeleteButton } from 'scenes/surveys/components/ConfirmDeleteButton'
+import { getNotificationDescription } from 'scenes/hog-functions/list/notificationDescription'
import { NEW_SURVEY } from 'scenes/surveys/constants'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
import { surveyNotificationModalLogic } from 'scenes/surveys/surveyNotificationModalLogic'
-import { HogFunctionType } from '~/types'
-
interface SurveyNotificationsProps {
surveyId: string
description?: string
buttonFullWidth?: boolean
}
-function getNotificationDescription(fn: HogFunctionType): string | null {
- const inputs = fn.inputs
- if (!inputs) {
- return null
- }
- if (inputs.url?.value) {
- try {
- return new URL(String(inputs.url.value)).hostname
- } catch {
- return String(inputs.url.value)
- }
- }
- if (inputs.channel?.value) {
- return String(inputs.channel.value)
- }
- if (inputs.email?.value) {
- return String(inputs.email.value)
- }
- return null
-}
-
export function SurveyNotifications({
surveyId,
description,
diff --git a/frontend/src/scenes/surveys/components/SurveyNotificationsList.tsx b/frontend/src/scenes/surveys/components/SurveyNotificationsList.tsx
index d26798e29e4e..6be4f9f7dc10 100644
--- a/frontend/src/scenes/surveys/components/SurveyNotificationsList.tsx
+++ b/frontend/src/scenes/surveys/components/SurveyNotificationsList.tsx
@@ -4,38 +4,16 @@ import { router } from 'kea-router'
import { IconPlus } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonDropdown, LemonInput, LemonSkeleton, LemonSwitch } from '@posthog/lemon-ui'
+import { ConfirmDeleteButton } from 'lib/components/ConfirmDeleteButton'
import { MailHog } from 'lib/components/hedgehogs'
import { HogFunctionIcon } from 'scenes/hog-functions/configuration/HogFunctionIcon'
-import { ConfirmDeleteButton } from 'scenes/surveys/components/ConfirmDeleteButton'
+import { getNotificationDescription } from 'scenes/hog-functions/list/notificationDescription'
import {
getSurveyIdsFromNotificationFilters,
surveyNotificationsListLogic,
} from 'scenes/surveys/surveyNotificationsListLogic'
import { urls } from 'scenes/urls'
-import { HogFunctionType } from '~/types'
-
-function getNotificationDescription(fn: HogFunctionType): string | null {
- const inputs = fn.inputs
- if (!inputs) {
- return null
- }
- if (inputs.url?.value) {
- try {
- return new URL(String(inputs.url.value)).hostname
- } catch {
- return String(inputs.url.value)
- }
- }
- if (inputs.channel?.value) {
- return String(inputs.channel.value)
- }
- if (inputs.email?.value) {
- return String(inputs.email.value)
- }
- return null
-}
-
function surveyNotificationsUrl(surveyId: string, params: Record<string, string> = {}): string {
const search = new URLSearchParams({ tab: 'notifications', ...params }).toString()
return `${urls.survey(surveyId)}?${search}`
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index e5a3ef510089..52599453a963 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -7225,6 +7225,7 @@ export type HogFunctionConfigurationContextId =
export type HogFunctionSubTemplateIdType =
| 'early-access-feature-enrollment'
| 'survey-response'
+ | 'mcp-tool-error'
| 'activity-log'
| 'feature-flag-change'
| 'error-tracking-issue-created'
diff --git a/posthog/cdp/test/test_filters.py b/posthog/cdp/test/test_filters.py
index 30dc39f7b116..bf88c68efe0c 100644
--- a/posthog/cdp/test/test_filters.py
+++ b/posthog/cdp/test/test_filters.py
@@ -228,6 +228,45 @@ class TestHogFunctionFilters(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest
assert execute_bytecode(bytecode, {"properties": {"$survey_response_1": 6}}).result is True
assert execute_bytecode(bytecode, {"properties": {"$survey_response_1": 7}}).result is False
+ @parameterized.expand(
+ [
+ (True, True),
+ ("true", True),
+ (1, True),
+ (False, False),
+ ("false", False),
+ (0, False),
+ ]
+ )
+ def test_multi_value_exact_filter_matches_mcp_error_encodings(
+ self, property_value: bool | str | int, expected: bool
+ ) -> None:
+ filters = {
+ "events": [
+ {
+ "id": "$mcp_tool_call",
+ "type": "events",
+ "properties": [
+ {
+ "key": "$mcp_is_error",
+ "value": ["true", True, 1],
+ "operator": "exact",
+ "type": "event",
+ }
+ ],
+ }
+ ]
+ }
+ bytecode = compile_filters_bytecode(filters, self.team)["bytecode"]
+
+ assert (
+ execute_bytecode(
+ bytecode,
+ {"event": "$mcp_tool_call", "properties": {"$mcp_is_error": property_value}},
+ ).result
+ is expected
+ )
+
def test_filters_full(self):
bytecode = self.filters_to_bytecode(filters=self.filters)
assert bytecode == [
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsScene.tsx b/products/mcp_analytics/frontend/MCPAnalyticsScene.tsx
index c6a3be70b180..6c97d122fbbf 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsScene.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsScene.tsx
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import { router, combineUrl } from 'kea-router'
import { IconSparkles } from '@posthog/icons'
-import { LemonButton, LemonTab, LemonTabs } from '@posthog/lemon-ui'
+import { LemonButton, LemonTab, LemonTabs, LemonTag } from '@posthog/lemon-ui'
import { urls } from 'scenes/urls'
@@ -22,6 +22,8 @@ import { mcpAnalyticsOnboardingLogic } from './mcpAnalyticsOnboardingLogic'
import { MCPAnalyticsTab, TAB_AI_PROMPTS, TAB_DESCRIPTIONS, mcpAnalyticsSceneLogic } from './mcpAnalyticsSceneLogic'
import { MCPAnalyticsSceneMenuBar } from './MCPAnalyticsSceneMenuBar'
import { MCPAnalyticsToolQuality } from './MCPAnalyticsToolQuality'
+import { MCPAnalyticsNotifications } from './notifications/MCPAnalyticsNotifications'
+import { mcpAnalyticsNotificationsLogic } from './notifications/mcpAnalyticsNotificationsLogic'
import { MCPSessionsPlaylist } from './sessions/MCPSessionsPlaylist'
export const scene: SceneExport = {
@@ -45,6 +47,7 @@ function MCPAnalyticsSceneContent(): JSX.Element {
const { searchParams } = useValues(router)
const { activeTab } = useValues(mcpAnalyticsSceneLogic)
const { onboardingState, dashboardStage } = useValues(mcpAnalyticsOnboardingLogic)
+ const { notificationCount } = useValues(mcpAnalyticsNotificationsLogic)
// search is Sessions-only — drop it when leaving the tab; the date range stays shared.
const { search: _search, ...sharedParams } = searchParams
@@ -90,6 +93,22 @@ function MCPAnalyticsSceneContent(): JSX.Element {
link: combineUrl(urls.mcpAnalyticsIntentClustering(), sharedParams).url,
'data-attr': 'mcp-analytics-intent-clustering-tab',
},
+ {
+ key: 'notifications',
+ label: (
+ <span className="flex items-center gap-1.5">
+ Notifications
+ {notificationCount > 0 && (
+ <LemonTag type="completion" size="small">
+ {notificationCount}
+ </LemonTag>
+ )}
+ </span>
+ ),
+ content: <MCPAnalyticsNotifications />,
+ link: combineUrl(urls.mcpAnalyticsNotifications(), sharedParams).url,
+ 'data-attr': 'mcp-analytics-notifications-tab',
+ },
]
return (
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.ts
index 9162c1e4e7d0..6b3f3de1f8b8 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.ts
@@ -7,7 +7,13 @@ import { sceneLogic } from '~/scenes/sceneLogic'
import { mcpAnalyticsOnboardingLogic } from './mcpAnalyticsOnboardingLogic'
-export type MCPAnalyticsTab = 'activity' | 'dashboard' | 'sessions' | 'tool-quality' | 'intent-clustering'
+export type MCPAnalyticsTab =
+ | 'activity'
+ | 'dashboard'
+ | 'sessions'
+ | 'tool-quality'
+ | 'intent-clustering'
+ | 'notifications'
export const TAB_DESCRIPTIONS: Record<MCPAnalyticsTab, string> = {
activity: 'Live feed of tool calls and what agents are trying to do with your MCP server.',
@@ -16,6 +22,8 @@ export const TAB_DESCRIPTIONS: Record<MCPAnalyticsTab, string> = {
'tool-quality': 'Understand how reliably your MCP tools support user workflows.',
'intent-clustering':
'Cluster semantically similar user intents and see which tools each cluster routes to. Highlights inconsistent routing.',
+ notifications:
+ 'Recurring summaries of what agents are doing, plus instant alerts for the things you need to know about right away.',
}
// Per-tab question seeded into PostHog AI so the answer is grounded in what the user is looking at.
@@ -29,7 +37,9 @@ export const TAB_AI_PROMPTS: Record<MCPAnalyticsTab, string> = {
'tool-quality':
'Which of my MCP tools are least reliable? Break down $mcp_tool_call error rate and p95 $mcp_duration_ms by $mcp_tool_name.',
'intent-clustering':
- "What's the biggest unmet need agents have that my MCP tools don't cover? Look at $mcp_missing_capability and $mcp_intent.",
+ "What's the biggest unmet need agents have that my MCP tools don't cover? Look at $mcp_intent on failing tool calls.",
+ notifications:
+ 'What MCP events should I be notified about? Summarize what agents were trying to do on failing $mcp_tool_call events.',
}
const SCENE_KEY_TO_TAB: Record<string, MCPAnalyticsTab> = {
@@ -38,6 +48,7 @@ const SCENE_KEY_TO_TAB: Record<string, MCPAnalyticsTab> = {
mcpAnalyticsSessions: 'sessions',
mcpAnalyticsToolQuality: 'tool-quality',
mcpAnalyticsIntentClustering: 'intent-clustering',
+ mcpAnalyticsNotifications: 'notifications',
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
diff --git a/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsx b/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsx
new file mode 100644
index 000000000000..fd2dc42ea662
--- /dev/null
+++ b/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsx
@@ -0,0 +1,262 @@
+import { useActions, useValues } from 'kea'
+import { combineUrl, router } from 'kea-router'
+import { useEffect } from 'react'
+
+import { IconPlus, IconWarning } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonCard, LemonSkeleton, LemonSwitch, 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 {
+ 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 { MCPNotificationPreview } from './MCPNotificationPreview'
+import { MCPRecurringReports } from './MCPRecurringReports'
+
+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
+}
+
+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}`}
+ >
+ {notifications.length > 0 ? 'Add' : 'Notify me'}
+ </LemonButton>
+ </div>
+
+ <MCPNotificationPreview
+ 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>
+ )}
+ </LemonCard>
+ )
+}
+
+export function MCPAnalyticsNotifications(): JSX.Element {
+ const { notifications, notificationsLoaded, notificationsFailed } = 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])
+
+ 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>
+ )}
+ </>
+ )
+
+ return (
+ <div className="flex flex-col gap-6" data-attr="mcp-analytics-notifications">
+ <MCPRecurringReports />
+
+ <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.
+ </p>
+ {instantAlerts}
+ </section>
+
+ {USE_CASES.map((config) => (
+ <NewNotificationDialog
+ key={config.subTemplateId}
+ subTemplateId={config.subTemplateId}
+ onCreated={onCreated}
+ title={config.dialogTitle}
+ />
+ ))}
+ </div>
+ )
+}
diff --git a/products/mcp_analytics/frontend/notifications/MCPNotificationPreview.tsx b/products/mcp_analytics/frontend/notifications/MCPNotificationPreview.tsx
new file mode 100644
index 000000000000..bdd691063b51
--- /dev/null
+++ b/products/mcp_analytics/frontend/notifications/MCPNotificationPreview.tsx
@@ -0,0 +1,59 @@
+import { Fragment } from 'react'
+
+import { LemonTag } from '@posthog/lemon-ui'
+
+import { Logomark } from 'lib/brand'
+
+// Slack mrkdwn, limited to the two markers our messages actually use.
+const MARKUP_SEGMENT = /(\*[^*]+\*|_[^_]+_)/g
+
+function renderSlackMarkup(message: string): JSX.Element[] {
+ return message
+ .split(MARKUP_SEGMENT)
+ .filter(Boolean)
+ .map((segment, index) => {
+ if (segment.length > 2 && segment.startsWith('*') && segment.endsWith('*')) {
+ return <strong key={index}>{segment.slice(1, -1)}</strong>
+ }
+ if (segment.length > 2 && segment.startsWith('_') && segment.endsWith('_')) {
+ return <em key={index}>{segment.slice(1, -1)}</em>
+ }
+ return <Fragment key={index}>{segment}</Fragment>
+ })
+}
+
+export interface MCPNotificationPreviewProps {
+ /** Slack mrkdwn, as produced by `mcpNotificationPreviewMessage` */
+ message: string
+ buttonLabel: string
+ /** Where the interpolated values came from — the project's own events, or sample copy. */
+ caption: string
+}
+
+/**
+ * A Slack-styled render of the message a notification posts, so you can see what lands in the
+ * channel before connecting one. Deliberately static: the copy comes from the real template, but
+ * the values are samples.
+ */
+export function MCPNotificationPreview({ message, buttonLabel, caption }: MCPNotificationPreviewProps): JSX.Element {
+ return (
+ <div className="flex gap-2 rounded border bg-surface-primary p-2">
+ <div className="flex h-6 w-6 shrink-0 items-center justify-center rounded bg-surface-secondary">
+ <Logomark size="xs" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="text-sm font-semibold">PostHog</span>
+ <LemonTag type="muted" size="small">
+ APP
+ </LemonTag>
+ <span className="text-xs text-muted">·&nbsp;{caption}</span>
+ </div>
+ <p className="m-0 mt-0.5 break-words text-sm">{renderSlackMarkup(message)}</p>
+ <span className="mt-1.5 inline-flex rounded border bg-surface-secondary px-2 py-0.5 text-xs font-medium">
+ {buttonLabel}
+ </span>
+ </div>
+ </div>
+ )
+}
diff --git a/products/mcp_analytics/frontend/notifications/MCPRecurringReports.tsx b/products/mcp_analytics/frontend/notifications/MCPRecurringReports.tsx
new file mode 100644
index 000000000000..a1b1422ff49e
--- /dev/null
+++ b/products/mcp_analytics/frontend/notifications/MCPRecurringReports.tsx
@@ -0,0 +1,82 @@
+import { IconCalendar, IconOpenSidebar } from '@posthog/icons'
+import { LemonButton, LemonCard, LemonTag, Link } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { urls } from 'scenes/urls'
+
+import { MCP_RECURRING_REPORTS, MCPRecurringReport, urlForRecurringReport } from './recurringReportDefinitions'
+
+function ReportCard({ report, enabled }: { report: MCPRecurringReport; enabled: boolean }): 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="min-w-0">
+ <div className="flex items-center gap-1.5">
+ <h3 className="m-0 text-sm font-semibold">{report.headline}</h3>
+ <LemonTag type="muted" size="small">
+ {report.frequency === 'daily' ? 'Daily' : 'Weekly'}
+ </LemonTag>
+ </div>
+ <p className="m-0 text-xs text-muted">{report.lead}</p>
+ </div>
+ {enabled && (
+ <LemonButton
+ type="primary"
+ size="xsmall"
+ icon={<IconCalendar />}
+ to={urlForRecurringReport(report)}
+ data-attr={`mcp-analytics-recurring-report-${report.key}`}
+ >
+ Set up
+ </LemonButton>
+ )}
+ </div>
+
+ {/* The report itself is written by an LLM each run, so there's nothing faithful to preview.
+ Showing the question it asks is the honest version — and it's editable before saving. */}
+ <div className="rounded border bg-surface-primary p-2">
+ <div className="text-xs font-medium text-muted">What it asks</div>
+ <p className="m-0 mt-0.5 text-xs">{report.prompt}</p>
+ </div>
+ </LemonCard>
+ )
+}
+
+/**
+ * Recurring AI reports for the two questions that suit a digest better than a per-event ping: what
+ * agents keep asking for, and how the tools are holding up. Both are summaries over a window, so
+ * they stay useful on a quiet server and can't flood a channel the way a per-event alert can.
+ */
+export function MCPRecurringReports(): JSX.Element {
+ const aiSubscriptionsEnabled = useFeatureFlag('SUBSCRIPTION_AI_PROMPT')
+
+ return (
+ <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>
+ <p className="m-0 text-sm text-muted">
+ A written summary on a schedule, delivered to Slack or email. Best for the questions you want to think
+ about regularly rather than react to.
+ </p>
+
+ {!aiSubscriptionsEnabled && (
+ <p className="m-0 text-xs text-muted">
+ AI reports are in early access.{' '}
+ <Link to={urls.featurePreview(FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT)}>
+ Turn them on for your account <IconOpenSidebar />
+ </Link>{' '}
+ to set one up.
+ </p>
+ )}
+
+ <div className="grid gap-2 md:grid-cols-2">
+ {MCP_RECURRING_REPORTS.map((report) => (
+ <ReportCard key={report.key} report={report} enabled={aiSubscriptionsEnabled} />
+ ))}
+ </div>
+ </section>
+ )
+}
diff --git a/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.test.ts b/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.test.ts
new file mode 100644
index 000000000000..c56dfa0cb4f2
--- /dev/null
+++ b/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.test.ts
@@ -0,0 +1,186 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import api from 'lib/api'
+import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
+
+import { initKeaTests } from '~/test/init'
+import { HogFunctionType } from '~/types'
+
+import { getMCPNotificationUseCase, mcpAnalyticsNotificationsLogic } from './mcpAnalyticsNotificationsLogic'
+
+jest.mock('lib/utils/deleteWithUndo', () => ({
+ deleteWithUndo: jest.fn(),
+}))
+
+const mockedDeleteWithUndo = jest.mocked(deleteWithUndo)
+
+function makeNotification(id: string, overrides: Partial<HogFunctionType> = {}): HogFunctionType {
+ return {
+ id,
+ name: `Notification ${id}`,
+ enabled: false,
+ deleted: false,
+ filters: { events: [{ id: '$mcp_tool_call', type: 'events' }] },
+ inputs: {},
+ icon_url: null,
+ ...overrides,
+ } as HogFunctionType
+}
+
+function createDeferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((promiseResolve) => {
+ resolve = promiseResolve
+ })
+ return { promise, resolve }
+}
+
+describe('mcpAnalyticsNotificationsLogic', () => {
+ let logic: ReturnType<typeof mcpAnalyticsNotificationsLogic.build>
+ let listSpy: jest.SpyInstance
+
+ beforeEach(async () => {
+ initKeaTests()
+ listSpy = jest.spyOn(api.hogFunctions, 'list').mockResolvedValue({
+ count: 2,
+ next: null,
+ previous: null,
+ results: [],
+ })
+ jest.spyOn(api.hogFunctions, 'update').mockResolvedValue(makeNotification('updated'))
+ jest.spyOn(lemonToast, 'warning').mockImplementation(() => 'toast-id')
+ mockedDeleteWithUndo.mockReset().mockResolvedValue()
+
+ logic = mcpAnalyticsNotificationsLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.restoreAllMocks()
+ })
+
+ test.each([
+ ['$mcp_tool_call', 'tool-error'],
+ ['$mcp_missing_capability', null],
+ ['$pageview', null],
+ ])('classifies the %s event as %s', (eventId, expected) => {
+ expect(
+ getMCPNotificationUseCase({
+ filters: { events: [{ id: eventId, type: 'events' }] },
+ })
+ ).toBe(expected)
+ })
+
+ it('loads only a lightweight count when mounted', () => {
+ expect(logic.values.notificationCount).toBe(2)
+ expect(listSpy).toHaveBeenCalledTimes(1)
+ expect(listSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ limit: 1,
+ types: ['destination'],
+ })
+ )
+ expect(listSpy.mock.calls[0][0]).not.toHaveProperty('full')
+ })
+
+ it('keeps the fetched rows and warns when the list is truncated', async () => {
+ const notifications = [makeNotification('a'), makeNotification('b')]
+ listSpy.mockReset().mockResolvedValue({
+ count: 501,
+ next: 'http://localhost/api/projects/1/hog_functions/?limit=500&offset=500',
+ previous: null,
+ results: notifications,
+ })
+
+ logic.actions.loadNotificationCountSuccess(501)
+
+ await expectLogic(logic, () => logic.actions.loadNotifications())
+ .toFinishAllListeners()
+ .toMatchValues({
+ notificationCount: 501,
+ notifications,
+ notificationsFailed: false,
+ notificationsTruncated: true,
+ })
+
+ expect(listSpy).toHaveBeenCalledWith(expect.objectContaining({ full: true, limit: 500 }))
+ expect(lemonToast.warning).toHaveBeenCalledWith(expect.stringContaining('first 500'))
+ })
+
+ it('blocks a second toggle and reconciles the first with the server response', async () => {
+ const notification = makeNotification('toggle')
+ const serverNotification = makeNotification('toggle', { enabled: false, name: 'Server name' })
+ const updateDeferred = createDeferred<HogFunctionType>()
+ const updateSpy = jest.spyOn(api.hogFunctions, 'update').mockReturnValue(updateDeferred.promise)
+ logic.actions.loadNotificationsSuccess([notification])
+
+ logic.actions.toggleNotificationEnabled(notification.id, true)
+
+ expect(logic.values.pendingToggleIds).toEqual({ [notification.id]: true })
+ expect(logic.values.notifications[0].enabled).toBe(true)
+
+ logic.actions.toggleNotificationEnabled(notification.id, false)
+ expect(updateSpy).toHaveBeenCalledTimes(1)
+
+ updateDeferred.resolve(serverNotification)
+ await expectLogic(logic)
+ .toFinishAllListeners()
+ .toMatchValues({
+ notifications: [serverNotification],
+ pendingToggleIds: {},
+ })
+ })
+
+ it('keeps an in-flight reload visible when a toggle writes its confirmed row', async () => {
+ const pendingReload = createDeferred<Awaited<ReturnType<typeof api.hogFunctions.list>>>()
+ listSpy.mockReset().mockReturnValue(pendingReload.promise)
+
+ logic.actions.loadNotifications()
+ expect(logic.values.notificationsLoading).toBe(true)
+
+ logic.actions.setNotifications([makeNotification('toggle', { enabled: true })])
+
+ // Writing through the loader's own success action would clear notificationsLoading here,
+ // so the settling toggle below would skip the corrective reload and let the stale
+ // in-flight GET revert the confirmed value.
+ expect(logic.values.notificationsLoading).toBe(true)
+
+ logic.actions.toggleNotificationEnabledSettled('toggle')
+ expect(listSpy).toHaveBeenCalledTimes(2)
+
+ pendingReload.resolve({ count: 0, next: null, previous: null, results: [] })
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ it('reloads server truth when an optimistic delete fails', async () => {
+ const deletedNotification = makeNotification('delete')
+ const concurrentlyUpdatedNotification = makeNotification('keep', { enabled: true })
+ const serverNotification = makeNotification('server')
+ const deleteDeferred = createDeferred<void>()
+ mockedDeleteWithUndo.mockReturnValue(deleteDeferred.promise)
+ listSpy.mockReset().mockResolvedValue({
+ count: 2,
+ next: null,
+ previous: null,
+ results: [concurrentlyUpdatedNotification, serverNotification],
+ })
+ logic.actions.loadNotificationsSuccess([deletedNotification, makeNotification('keep')])
+
+ logic.actions.deleteNotification(deletedNotification)
+ expect(logic.values.notifications).toEqual([makeNotification('keep')])
+
+ logic.actions.loadNotificationsSuccess([concurrentlyUpdatedNotification])
+ deleteDeferred.resolve()
+
+ await expectLogic(logic)
+ .toFinishAllListeners()
+ .toMatchValues({
+ notifications: [concurrentlyUpdatedNotification, serverNotification],
+ })
+ expect(listSpy).toHaveBeenCalledWith(expect.objectContaining({ full: true }))
+ })
+})
diff --git a/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.ts b/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.ts
new file mode 100644
index 000000000000..7e8ee2916a8a
--- /dev/null
+++ b/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.ts
@@ -0,0 +1,328 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } 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(getFiltersFromSubTemplateId).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[]
+ notificationsFailed: boolean
+ notificationsLoaded: boolean
+ notificationsLoading: boolean
+ notificationsTruncated: boolean
+ pendingDeleteIds: Record<string, true>
+ pendingToggleIds: Record<string, true>
+}
+
+// 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
+ }
+}
+
+export type mcpAnalyticsNotificationsLogicType = MakeLogicType<
+ mcpAnalyticsNotificationsLogicValues,
+ mcpAnalyticsNotificationsLogicActions
+>
+
+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,
+ },
+ ],
+ }),
+ 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()
+ }),
+])
diff --git a/products/mcp_analytics/frontend/notifications/mcpNotificationExamplesLogic.test.ts b/products/mcp_analytics/frontend/notifications/mcpNotificationExamplesLogic.test.ts
new file mode 100644
index 000000000000..33571686c6ab
--- /dev/null
+++ b/products/mcp_analytics/frontend/notifications/mcpNotificationExamplesLogic.test.ts
@@ -0,0 +1,39 @@
+import { MCP_MESSAGE_FIELD_LIMITS } from 'scenes/hog-functions/sub-templates/sub-templates'
+
+import { parseExampleRows } from './mcpNotificationExamplesLogic'
+
+// Rows arrive positionally: [use_case, client_name, server_name, intent, tool_name]. The query
+// derives use_case, since the failure use cases all share the $mcp_tool_call event.
+const TOOL_ERROR_ROW = ['tool-error', 'Claude Code', 'acme-mcp', 'why did signups drop', 'query-events']
+
+describe('parseExampleRows', () => {
+ it('maps a failure example from its positional columns', () => {
+ expect(parseExampleRows([TOOL_ERROR_ROW])).toEqual({
+ 'tool-error': {
+ clientName: 'Claude Code',
+ serverName: 'acme-mcp',
+ intent: 'why did signups drop',
+ toolName: 'query-events',
+ },
+ })
+ })
+
+ // A half-real example (project's client name, our invented intent) reads as genuine but isn't,
+ // so an incomplete row is dropped in favour of the honest sample copy.
+ it.each([
+ ['missing intent', ['tool-error', 'Claude Code', 'acme-mcp', '', 'query-events']],
+ ['missing client name', ['tool-error', null, 'acme-mcp', 'why', 'query-events']],
+ ['no tool name', ['tool-error', 'Claude Code', 'acme-mcp', 'why', '']],
+ ['an unrecognized use case', ['something-else', 'Cursor', 'acme-mcp', 'why', 'query-events']],
+ ])('drops a row with %s', (_label, row) => {
+ expect(parseExampleRows([row])).toEqual({})
+ })
+
+ it('cuts a field at the limit the delivered message uses', () => {
+ const intent = 'x'.repeat(MCP_MESSAGE_FIELD_LIMITS.intent + 50)
+
+ const parsed = parseExampleRows([['tool-error', 'Cursor', 'acme-mcp', intent, 'query-events']])
+
+ expect(parsed['tool-error']?.intent).toHaveLength(MCP_MESSAGE_FIELD_LIMITS.intent)
+ })
+})
diff --git a/products/mcp_analytics/frontend/notifications/mcpNotificationExamplesLogic.ts b/products/mcp_analytics/frontend/notifications/mcpNotificationExamplesLogic.ts
new file mode 100644
index 000000000000..7f430a4a9540
--- /dev/null
+++ b/products/mcp_analytics/frontend/notifications/mcpNotificationExamplesLogic.ts
@@ -0,0 +1,133 @@
+import { MakeLogicType, kea, path } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+import { MCP_MESSAGE_FIELD_LIMITS, MCPMessageField } from 'scenes/hog-functions/sub-templates/sub-templates'
+
+import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'
+
+import { asString } from '../queryResultParsers'
+import { MCPNotificationUseCase } from './mcpAnalyticsNotificationsLogic'
+
+export type MCPNotificationExample = Record<MCPMessageField, string>
+export type MCPNotificationExamples = Partial<Record<MCPNotificationUseCase, MCPNotificationExample>>
+
+// The most recent real event per use case, so a preview can show the project's own traffic instead
+// of invented values. One scan serves every card: the three failure use cases all live in
+// $mcp_tool_call and are separated by error type, so the use case is derived first and grouped on,
+// letting argMax pick each one's latest. Time-bounded to keep it cheap; the preview falls back to
+// sample copy when a project has nothing (yet), so an empty result is normal, not an error.
+//
+// The effective-tool expression mirrors EFFECTIVE_TOOL_SQL in
+// products/mcp_analytics/backend/hogql_queries/base.py — the inner tool when the call came through
+// the single-exec wrapper, else the directly-registered name.
+const EXAMPLES_QUERY = `
+SELECT
+ 'tool-error' AS use_case,
+ argMax(toString(properties.$mcp_client_name), timestamp) AS client_name,
+ argMax(toString(properties.$mcp_server_name), timestamp) AS server_name,
+ argMax(toString(properties.$mcp_intent), timestamp) AS intent,
+ argMax(
+ coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)),
+ timestamp
+ ) AS tool_name
+FROM events
+WHERE timestamp >= now() - INTERVAL 90 DAY
+ AND event = '$mcp_tool_call'
+ AND toBool(properties.$mcp_is_error)
+`
+
+const KNOWN_USE_CASES: MCPNotificationUseCase[] = ['tool-error']
+
+// Every field the message renders must be present, otherwise the "real" example would be a mix of
+// the project's data and our invented copy — more misleading than an honest sample.
+const REQUIRED_FIELDS: Record<MCPNotificationUseCase, MCPMessageField[]> = {
+ 'tool-error': ['clientName', 'serverName', 'intent', 'toolName'],
+}
+
+// Array.from so a cut can't land inside a surrogate pair and render as a replacement character.
+function truncateField(field: MCPMessageField, value: string): string {
+ const characters = Array.from(value)
+ return characters.length > MCP_MESSAGE_FIELD_LIMITS[field]
+ ? characters.slice(0, MCP_MESSAGE_FIELD_LIMITS[field]).join('')
+ : value
+}
+
+export function parseExampleRows(rows: unknown[]): MCPNotificationExamples {
+ const examples: MCPNotificationExamples = {}
+
+ for (const row of rows) {
+ const [rawUseCase, clientName, serverName, intent, toolName] = row as unknown[]
+ const useCase = KNOWN_USE_CASES.find((candidate) => candidate === asString(rawUseCase))
+ if (!useCase) {
+ continue
+ }
+
+ const candidate: MCPNotificationExample = {
+ clientName: asString(clientName),
+ serverName: asString(serverName),
+ intent: asString(intent),
+ toolName: asString(toolName),
+ }
+ if (!REQUIRED_FIELDS[useCase].every((field) => candidate[field])) {
+ continue
+ }
+
+ examples[useCase] = {
+ clientName: truncateField('clientName', candidate.clientName),
+ serverName: truncateField('serverName', candidate.serverName),
+ intent: truncateField('intent', candidate.intent),
+ toolName: truncateField('toolName', candidate.toolName),
+ }
+ }
+
+ return examples
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface mcpNotificationExamplesLogicValues {
+ examples: MCPNotificationExamples
+ examplesLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface mcpNotificationExamplesLogicActions {
+ loadExamples: () => any
+ loadExamplesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadExamplesSuccess: (
+ examples: Partial<Record<'tool-error', MCPNotificationExample>>,
+ payload?: any
+ ) => {
+ examples: Partial<Record<'tool-error', MCPNotificationExample>>
+ payload?: any
+ }
+}
+
+export type mcpNotificationExamplesLogicType = MakeLogicType<
+ mcpNotificationExamplesLogicValues,
+ mcpNotificationExamplesLogicActions
+>
+
+export const mcpNotificationExamplesLogic = kea<mcpNotificationExamplesLogicType>([
+ path(['products', 'mcp_analytics', 'frontend', 'notifications', 'mcpNotificationExamplesLogic']),
+ loaders({
+ examples: [
+ {} as MCPNotificationExamples,
+ {
+ loadExamples: async (): Promise<MCPNotificationExamples> => {
+ const response = (await api.query({
+ kind: NodeKind.HogQLQuery,
+ query: EXAMPLES_QUERY,
+ })) as HogQLQueryResponse
+ return parseExampleRows(response?.results ?? [])
+ },
+ },
+ ],
+ }),
+])
diff --git a/products/mcp_analytics/frontend/notifications/recurringReportDefinitions.ts b/products/mcp_analytics/frontend/notifications/recurringReportDefinitions.ts
new file mode 100644
index 000000000000..b767b7753b84
--- /dev/null
+++ b/products/mcp_analytics/frontend/notifications/recurringReportDefinitions.ts
@@ -0,0 +1,70 @@
+import { combineUrl } from 'kea-router'
+
+import { urls } from 'scenes/urls'
+
+export interface MCPRecurringReport {
+ key: string
+ headline: string
+ lead: string
+ frequency: 'daily' | 'weekly'
+ title: string
+ /**
+ * Handed to the AI-subscription planner, which writes and runs its own HogQL. Names the
+ * $mcp_* properties explicitly so it queries the right ones rather than guessing.
+ */
+ prompt: string
+}
+
+export const MCP_RECURRING_REPORTS: MCPRecurringReport[] = [
+ {
+ key: 'intent-roundup',
+ headline: 'What agents are trying to do',
+ lead: 'Their goals in their own words, grouped and ranked, with the ones that keep failing called out.',
+ frequency: 'weekly',
+ title: 'MCP intent roundup',
+ // Reads $mcp_intent on tool calls rather than $mcp_missing_capability: that event has never
+ // been emitted by any project, while $mcp_intent is set on ~88% of calls. "Couldn't do it"
+ // is inferred from the error flag on the same call, which is a signal that actually exists.
+ prompt: [
+ 'Summarize what AI agents were trying to do with our MCP server this week,',
+ 'using the $mcp_intent property on $mcp_tool_call events.',
+ 'Group similar intents together and rank the groups by how often they came up,',
+ 'quoting one or two verbatim $mcp_intent examples per group.',
+ 'For each group, give the share of those calls that failed ($mcp_is_error) — an intent',
+ 'agents keep attempting and keep failing is the most useful thing in this report.',
+ 'Call out intents that are new compared with previous weeks, and finish with the single',
+ 'change to our tools that would help the most agents.',
+ ].join(' '),
+ },
+ {
+ key: 'tool-health',
+ headline: 'How your tools held up',
+ lead: 'Volume, error rate and latency per tool, with the failures worth acting on.',
+ // Weekly, not daily: a typical MCP server sees a few dozen calls a day, so a daily error
+ // rate or p95 is noise. A week gives those numbers enough data to mean something.
+ frequency: 'weekly',
+ title: 'MCP tool health',
+ prompt: [
+ 'Report on our MCP server’s health for the last week using $mcp_tool_call events.',
+ 'Cover total calls, calls per tool (use $mcp_exec_tool_call_name when set, else $mcp_tool_name),',
+ 'the error rate from $mcp_is_error, the most common $mcp_error_type values with example',
+ '$mcp_error_message text, and p95 of $mcp_duration_ms per tool.',
+ 'Highlight tools whose error rate or latency is clearly worse than the weeks before,',
+ 'and skip sections where nothing notable happened.',
+ ].join(' '),
+ },
+]
+
+/**
+ * Opens the AI-subscription form with the report already written, so setting one up is choosing a
+ * destination and a cadence rather than composing a prompt.
+ */
+export function urlForRecurringReport(report: MCPRecurringReport): string {
+ return combineUrl(urls.subscriptionNew(), {
+ resource_type: 'ai_prompt',
+ prompt: report.prompt,
+ title: report.title,
+ frequency: report.frequency,
+ target_type: 'slack',
+ }).url
+}
diff --git a/products/mcp_analytics/frontend/queryResultParsers.ts b/products/mcp_analytics/frontend/queryResultParsers.ts
index be75f4c9eb9a..020180de803b 100644
--- a/products/mcp_analytics/frontend/queryResultParsers.ts
+++ b/products/mcp_analytics/frontend/queryResultParsers.ts
@@ -2,3 +2,6 @@
// possibly stringified. Coerce numerically so a stringified "0" can never read
// as truthy.
export const asNumber = (value: unknown): number => Number(value) || 0
+
+/** String columns arrive null when the property is missing — normalize those to an empty string. */
+export const asString = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')
diff --git a/products/mcp_analytics/manifest.tsx b/products/mcp_analytics/manifest.tsx
index 124220a024d2..f084a5f23c42 100644
--- a/products/mcp_analytics/manifest.tsx
+++ b/products/mcp_analytics/manifest.tsx
@@ -41,6 +41,7 @@ export const manifest: ProductManifest = {
'/mcp-analytics/tool-quality': ['MCPAnalytics', 'mcpAnalyticsToolQuality'],
'/mcp-analytics/tool-quality/:toolName': ['MCPAnalyticsToolDetail', 'mcpAnalyticsTool'],
'/mcp-analytics/intent-clustering': ['MCPAnalytics', 'mcpAnalyticsIntentClustering'],
+ '/mcp-analytics/notifications': ['MCPAnalytics', 'mcpAnalyticsNotifications'],
},
redirects: {
// `landing=auto` marks "arrived via the bare URL": the scene resolves it to the
@@ -56,6 +57,7 @@ export const manifest: ProductManifest = {
mcpAnalyticsToolQuality: (): string => '/mcp-analytics/tool-quality',
mcpAnalyticsTool: (toolName: string): string => `/mcp-analytics/tool-quality/${encodeURIComponent(toolName)}`,
mcpAnalyticsIntentClustering: (): string => '/mcp-analytics/intent-clustering',
+ mcpAnalyticsNotifications: (): string => '/mcp-analytics/notifications',
},
setupProbe: {
productKey: ProductKey.MCP_ANALYTICS,
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
index 4d5d94e6cb7c..27be12540197 100644
--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
@@ -147,6 +147,39 @@ describe('subscriptionLogic', () => {
})
})
+ // Products deep-link here with a ready-made report (the MCP analytics recurring-report cards),
+ // so dropping this prefill would silently open an empty form and lose the whole one-click flow.
+ it('prefills a ready-made AI report from the parent-less new-subscription URL', async () => {
+ const promptLogic = subscriptionLogic({ id: 'new' })
+ promptLogic.mount()
+
+ router.actions.push(
+ '/subscriptions/new?resource_type=ai_prompt&prompt=Rank%20what%20agents%20asked%20for&title=MCP%20intent%20roundup&frequency=weekly&target_type=slack'
+ )
+ await expectLogic(promptLogic).toFinishListeners()
+
+ expect(promptLogic.values.subscription).toMatchObject({
+ resource_type: 'ai_prompt',
+ prompt: 'Rank what agents asked for',
+ title: 'MCP intent roundup',
+ frequency: 'weekly',
+ target_type: 'slack',
+ })
+ })
+
+ it.each([
+ ['an unsupported frequency', 'frequency=hourly', 'frequency', 'weekly'],
+ ['a blank prompt', 'prompt=', 'prompt', undefined],
+ ])('ignores %s in the prefill', async (_label, search, field, expected) => {
+ const promptLogic = subscriptionLogic({ id: 'new' })
+ promptLogic.mount()
+
+ router.actions.push(`/subscriptions/new?${search}`)
+ await expectLogic(promptLogic).toFinishListeners()
+
+ expect(promptLogic.values.subscription[field as 'frequency' | 'prompt']).toBe(expected)
+ })
+
it.each<[string, string, string]>([
// The notification's source_url carries via=notification; the transient toast via=toast.
// Absent via defaults to notification for safety.
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
index e0536568c6af..bbbcc3b5e9c7 100644
--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
@@ -113,6 +113,9 @@ function subscriptionSaveErrorMessage(error: unknown): string {
return 'Could not save subscription. Please try again.'
}
+// Frequencies a deep link may prefill. Anything else is ignored rather than trusted into the form.
+const FREQUENCY_PREFILL_VALUES: SubscriptionType['frequency'][] = ['daily', 'weekly', 'monthly']
+
const NEW_SUBSCRIPTION: Partial<SubscriptionType> = {
resource_type: SubscriptionResourceTypes.Insight,
frequency: 'weekly',
@@ -733,6 +736,23 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
if (searchParams.target_type) {
actions.setSubscriptionValue('target_type', searchParams.target_type)
}
+ // Products link here with a ready-made report (e.g. the MCP analytics recurring-report
+ // cards) so the user picks a destination instead of writing a prompt. Set through
+ // setSubscriptionValues so the form starts dirty — the prefill is a deliberate change,
+ // not a pristine default, so "Create" doesn't need a no-op edit first.
+ const prefill: Partial<SubscriptionType> = {}
+ if (typeof searchParams.prompt === 'string' && searchParams.prompt) {
+ prefill.prompt = searchParams.prompt.slice(0, AI_PROMPT_MAX_LENGTH)
+ }
+ if (typeof searchParams.title === 'string' && searchParams.title) {
+ prefill.title = searchParams.title
+ }
+ if (FREQUENCY_PREFILL_VALUES.includes(searchParams.frequency)) {
+ prefill.frequency = searchParams.frequency
+ }
+ if (Object.keys(prefill).length > 0) {
+ actions.setSubscriptionValues(prefill)
+ }
},
'/subscriptions/:id/edit': () => {
actions.loadSubscription()