:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp-analytics): nudge mcp-titled insights and dashboards to mcp analytics (#111963)
Mike Warrenbb3524ef6a87
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 47947fc22b1d..d9582af05129 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -12370,6 +12370,10 @@ snapshots:hash: v1.k794b7964.b33c74ffb5531cf86afcd5fa718200c83a0863450ca85a5c94d026264f81dc4c.awlyXScQ759I0zP7I5rQA8PEIunmftZStWnJ90q-tpwscenes-app-mcp-analytics-notification-types-table--nothing-set-up--light:hash: v1.k794b7964.d0cb2086e12994284977aa2d895e1214c0261d2505022d9df4aef0d15c6562c6.fKwM2EVKz22cubQjamzL4YJN2CWRvtdpvYIifmijXtA+ scenes-app-mcp-analytics-nudge-toast--default--dark:+ hash: v1.k794b7964.1cc84f683757e63495ffa98459b9556442c3535018f4379e0e522a6bda285f4c.6ZS_Z7xaUDE5IW381cySLT26W5FmcdMyCK9qASAfATM+ scenes-app-mcp-analytics-nudge-toast--default--light:+ hash: v1.k794b7964.e7ac9b38fc3e2fdfdd1189c833ff16264f3807a5489fc1be778aa06be372538c.K4vqorVUJpvkp2t_j2mlWWbQwYG5wbaxGAUvetJbcrQscenes-app-mcp-analytics-tool-detail--tool-detail--medium--dark:hash: v1.k794b7964.e58395cb8a2827fc6dc6f95a7758eee7e72d0ee902de43db257a2e53012e1b0b.zQ8oyEjDSPkbT4yXup07uT_zvITN1oMbJzAJFp-7vIAscenes-app-mcp-analytics-tool-detail--tool-detail--medium--light:diff --git a/frontend/src/scenes/dashboard/newDashboardLogic.ts b/frontend/src/scenes/dashboard/newDashboardLogic.tsindex 39ca2309ddff..06191b51d21f 100644--- a/frontend/src/scenes/dashboard/newDashboardLogic.ts+++ b/frontend/src/scenes/dashboard/newDashboardLogic.ts@@ -44,6 +44,10 @@ import {} from '~/types'import { WEBSITE_METRICS_METRIC_CARD_TILES } from 'products/dashboards/frontend/websiteMetricsMetricCardTemplate'+import {+ titleMentionsMCP,+ tryShowMCPAnalyticsNudge,+} from 'products/mcp_analytics/frontend/nudge/mcpAnalyticsNudgeLogic'import { UNFILED_DASHBOARDS_FOLDER } from './dashboardConstants'@@ -393,9 +397,13 @@ export const newDashboardLogic = kea<newDashboardLogicType>([const queryBasedDashboard = getQueryBasedDashboard(result)queryBasedDashboard && dashboardsModel.actions.addDashboardSuccess(queryBasedDashboard)actions.submitNewDashboardSuccessWithResult(result, undefined, setAsHomeTabDashboard, openAI)- tryShowMCPHint('dashboards.create', {- derivedPrompt: result.name ? `Build a dashboard called ${result.name}` : undefined,- })+ if (titleMentionsMCP(result.name)) {+ tryShowMCPAnalyticsNudge('dashboard')+ } else {+ tryShowMCPHint('dashboards.create', {+ derivedPrompt: result.name ? `Build a dashboard called ${result.name}` : undefined,+ })+ }if (show && redirectAfterCreation) {breakpoint()router.actions.push(urls.dashboard(result.id))diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsxindex d97664921f25..34d0eb8e54c7 100644--- a/frontend/src/scenes/insights/insightLogic.tsx+++ b/frontend/src/scenes/insights/insightLogic.tsx@@ -73,6 +73,10 @@ import {} from '~/types'import { insightAlertsLogic } from 'products/alerts/frontend/logic/insightAlertsLogic'+import {+ titleMentionsMCP,+ tryShowMCPAnalyticsNudge,+} from 'products/mcp_analytics/frontend/nudge/mcpAnalyticsNudgeLogic'import { mathsLogic } from 'products/product_analytics/frontend/insights/trends/mathsLogic'import type { MathDefinition } from 'products/product_analytics/frontend/insights/trends/mathsLogic'import { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'@@ -1187,9 +1191,15 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType},})const insightName = savedInsight.name || savedInsight.derived_name- tryShowMCPHint('insights.create', {- derivedPrompt: insightName ? `Build an insight called ${insightName}` : undefined,- })+ // An MCP-titled insight suggests a hand-rolled MCP server tracker, so offer MCP analytics+ // instead of the PostHog MCP hint. Two MCP toasts about different products would confuse.+ if (insightNumericId === undefined && titleMentionsMCP(insightName)) {+ tryShowMCPAnalyticsNudge('insight')+ } else {+ tryShowMCPHint('insights.create', {+ derivedPrompt: insightName ? `Build an insight called ${insightName}` : undefined,+ })+ }dashboardsModel.findMounted()?.actions.updateDashboardInsight(savedInsight)diff --git a/products/mcp_analytics/frontend/nudge/MCPAnalyticsNudgeToast.stories.tsx b/products/mcp_analytics/frontend/nudge/MCPAnalyticsNudgeToast.stories.tsxnew file mode 100644index 000000000000..5acae164685f--- /dev/null+++ b/products/mcp_analytics/frontend/nudge/MCPAnalyticsNudgeToast.stories.tsx@@ -0,0 +1,27 @@+import { Meta, StoryObj } from '@storybook/react'++import { MCPAnalyticsNudgeToast } from './MCPAnalyticsNudgeToast'++const meta: Meta<typeof MCPAnalyticsNudgeToast> = {+ title: 'Scenes-App/MCP Analytics/Nudge Toast',+ component: MCPAnalyticsNudgeToast,+ parameters: {+ // The component is normally rendered inside a react-toastify toast.+ // The decorator below approximates that container so the story is visually meaningful.+ layout: 'centered',+ },+ decorators: [+ (Story) => (+ <div className="max-w-md min-w-140 bg-surface-primary border border-primary rounded-lg shadow-lg p-3">+ <Story />+ </div>+ ),+ ],+}+export default meta++type Story = StoryObj<typeof MCPAnalyticsNudgeToast>++export const Default: Story = {+ args: { surface: 'insight' },+}diff --git a/products/mcp_analytics/frontend/nudge/MCPAnalyticsNudgeToast.tsx b/products/mcp_analytics/frontend/nudge/MCPAnalyticsNudgeToast.tsxnew file mode 100644index 000000000000..4b2396e20bf3--- /dev/null+++ b/products/mcp_analytics/frontend/nudge/MCPAnalyticsNudgeToast.tsx@@ -0,0 +1,62 @@+import { router } from 'kea-router'+import posthog from 'posthog-js'++import { IconMCP } from '@posthog/icons'++import { CommandBlock } from 'lib/components/CommandBlock/CommandBlock'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { urls } from 'scenes/urls'++import { useMCPAnalyticsWizardCommand } from '../onboarding/MCPAnalyticsInstall'+import type { MCPAnalyticsNudgeSurface } from './mcpAnalyticsNudgeLogic'++export const MCP_ANALYTICS_NUDGE_TOAST_ID = 'mcp-analytics-nudge'++export function MCPAnalyticsNudgeToast({ surface }: { surface: MCPAnalyticsNudgeSurface }): JSX.Element {+ const { command, isCloudOrDev } = useMCPAnalyticsWizardCommand()++ return (+ <div className="flex flex-col gap-1.5 py-1 pr-1 min-w-0 items-start">+ <div className="flex items-center gap-1.5 text-sm font-semibold">+ <IconMCP className="size-4 shrink-0 text-primary" />+ <span>Skip the maintenance. Let MCP analytics handle it</span>+ </div>+ <div className="flex flex-col items-start gap-1.5 ml-5.5 min-w-0 w-full">+ <div className="text-xs text-secondary leading-snug">+ MCP analytics captures every tool call with its failure rate and latency, so you don't need custom+ events.+ {isCloudOrDev+ ? ' Run the Wizard in your MCP server repository. The setup agent installs it for you:'+ : null}+ </div>+ {isCloudOrDev && (+ <CommandBlock+ command={command}+ copyLabel="MCP analytics wizard command"+ ariaLabel="Copy MCP analytics wizard command"+ size="sm"+ decoration="rainbow"+ silentCopy+ condensed+ onCopy={() => posthog.capture('mcp analytics nudge command copied', { surface })}+ className="bg-surface-secondary border border-primary !m-0 hover:border-accent max-w-full"+ />+ )}+ <LemonButton+ type="primary"+ size="small"+ className="!mx-0"+ data-attr="mcp-analytics-nudge-toast-cta"+ onClick={() => {+ posthog.capture('mcp analytics nudge cta clicked', { surface })+ lemonToast.dismiss(MCP_ANALYTICS_NUDGE_TOAST_ID)+ router.actions.push(urls.mcpAnalytics())+ }}+ >+ Set up MCP analytics+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/products/mcp_analytics/frontend/nudge/mcpAnalyticsNudgeLogic.test.ts b/products/mcp_analytics/frontend/nudge/mcpAnalyticsNudgeLogic.test.tsnew file mode 100644index 000000000000..d4bc56f313e4--- /dev/null+++ b/products/mcp_analytics/frontend/nudge/mcpAnalyticsNudgeLogic.test.ts@@ -0,0 +1,63 @@+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { mcpAnalyticsNudgeLogic } from './mcpAnalyticsNudgeLogic'++describe('mcpAnalyticsNudgeLogic', () => {+ let logic: ReturnType<typeof mcpAnalyticsNudgeLogic.build>+ let toolCallDefinitions: { id: string; name: string }[]+ let infoSpy: jest.SpyInstance+ let captureSpy: jest.SpyInstance++ beforeEach(() => {+ localStorage.clear()+ toolCallDefinitions = []+ useMocks({+ get: {+ '/api/projects/:team/event_definitions/': () => [+ 200,+ { count: toolCallDefinitions.length, results: toolCallDefinitions },+ ],+ },+ })+ initKeaTests()+ infoSpy = jest.spyOn(lemonToast, 'info').mockImplementation(() => 'toast-id')+ captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)+ logic = mcpAnalyticsNudgeLogic()+ logic.mount()+ })++ afterEach(() => {+ infoSpy.mockRestore()+ captureSpy.mockRestore()+ })++ it.each([+ ['shows the nudge when the project has no tool calls', false, 1],+ ['skips the nudge when the project already collects tool calls', true, 0],+ ])('%s', async (_, hasToolCalls, expectedToasts) => {+ if (hasToolCalls) {+ toolCallDefinitions = [{ id: '1', name: '$mcp_tool_call' }]+ }+ logic.actions.maybeShowNudge('insight')+ await expectLogic(logic).toFinishAllListeners()+ expect(infoSpy).toHaveBeenCalledTimes(expectedToasts)+ expect(captureSpy.mock.calls.filter(([event]) => event === 'mcp analytics nudge shown')).toEqual(+ expectedToasts ? [['mcp analytics nudge shown', { surface: 'insight' }]] : []+ )+ })++ it('shows the nudge only once per project', async () => {+ logic.actions.maybeShowNudge('insight')+ logic.actions.maybeShowNudge('dashboard')+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.maybeShowNudge('dashboard')+ await expectLogic(logic).toFinishAllListeners()+ expect(infoSpy).toHaveBeenCalledTimes(1)+ })+})diff --git a/products/mcp_analytics/frontend/nudge/mcpAnalyticsNudgeLogic.tsx b/products/mcp_analytics/frontend/nudge/mcpAnalyticsNudgeLogic.tsxnew file mode 100644index 000000000000..e82536191047--- /dev/null+++ b/products/mcp_analytics/frontend/nudge/mcpAnalyticsNudgeLogic.tsx@@ -0,0 +1,88 @@+import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'+import posthog from 'posthog-js'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { teamLogic } from 'scenes/teamLogic'++import { eventDefinitionsList } from 'products/event_definitions/frontend/generated/api'++import { MCP_ANALYTICS_NUDGE_TOAST_ID, MCPAnalyticsNudgeToast } from './MCPAnalyticsNudgeToast'++export type MCPAnalyticsNudgeSurface = 'insight' | 'dashboard'++export function titleMentionsMCP(title: string | null | undefined): boolean {+ return !!title && /mcp/i.test(title)+}++/** Shows the MCP analytics nudge if the project has no `$mcp_tool_call` events yet. Fire and forget. */+export function tryShowMCPAnalyticsNudge(surface: MCPAnalyticsNudgeSurface): void {+ try {+ if (!mcpAnalyticsNudgeLogic.isMounted()) {+ mcpAnalyticsNudgeLogic.mount()+ }+ mcpAnalyticsNudgeLogic.actions.maybeShowNudge(surface)+ } catch (error) {+ console.warn('[mcpAnalyticsNudge] dispatch failed', { surface, error })+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface mcpAnalyticsNudgeLogicValues {+ handledTeamIds: number[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface mcpAnalyticsNudgeLogicActions {+ markTeamHandled: (teamId: number) => {+ teamId: number+ }+ maybeShowNudge: (surface: MCPAnalyticsNudgeSurface) => {+ surface: MCPAnalyticsNudgeSurface+ }+}++export type mcpAnalyticsNudgeLogicType = MakeLogicType<mcpAnalyticsNudgeLogicValues, mcpAnalyticsNudgeLogicActions>++export const mcpAnalyticsNudgeLogic = kea<mcpAnalyticsNudgeLogicType>([+ // pinned: the path sets the localStorage key of handledTeamIds+ path(['products', 'mcp_analytics', 'frontend', 'nudge', 'mcpAnalyticsNudgeLogic']),+ actions({+ maybeShowNudge: (surface: MCPAnalyticsNudgeSurface) => ({ surface }),+ markTeamHandled: (teamId: number) => ({ teamId }),+ }),+ reducers({+ handledTeamIds: [+ [] as number[],+ { persist: true },+ {+ markTeamHandled: (state, { teamId }) => (state.includes(teamId) ? state : [...state, teamId]),+ },+ ],+ }),+ listeners(({ values, actions }) => ({+ maybeShowNudge: async ({ surface }) => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId || values.handledTeamIds.includes(teamId)) {+ return+ }+ // Claim the team before the request, so two quick saves cannot both show the toast.+ actions.markTeamHandled(teamId)++ try {+ const response = await eventDefinitionsList(String(teamId), { names: ['$mcp_tool_call'], limit: 1 })+ if (response.results.length > 0 || teamLogic.values.currentTeamId !== teamId) {+ return+ }+ } catch {+ return+ }++ lemonToast.info(<MCPAnalyticsNudgeToast surface={surface} />, {+ toastId: MCP_ANALYTICS_NUDGE_TOAST_ID,+ autoClose: false,+ icon: false, // the body carries its own MCP icon+ })+ posthog.capture('mcp analytics nudge shown', { surface })+ },+ })),+])