: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): show next steps and a failures link on the activity tab (#103108)
Lucas Faria15a51cff9fd9
diff --git a/docs/published/docs/mcp-analytics/activity.mdx b/docs/published/docs/mcp-analytics/activity.mdxnew file mode 100644index 000000000000..954b3e6b4d4b--- /dev/null+++ b/docs/published/docs/mcp-analytics/activity.mdx@@ -0,0 +1,28 @@+---+title: Activity tab and recent activity+---++The **Activity** tab is where a new MCP analytics project lands until it has enough tool calls for the dashboard's charts to mean something.+It answers "what are agents doing with my server?" one call at a time.++## What is on the tab++- A one-line summary of the last 30 days: calls, clients, the most used tool, and how many calls failed. Select the failure count to filter the feed to failed calls.+- **Next steps**, shown only while something still needs doing. A step disappears once it is done.+- The **live activity** feed: every tool call with its tool, agent intent, result, duration, client and a link to its session. It refreshes every minute. Expand a row to see the event's properties, and use the date range and property filters to narrow it.+- **Who is calling your server**: the same share-of-calls-by-harness and by-model cards as the dashboard, over the last 30 days.++## Next steps++Each step reflects what the last 30 days of calls show:++- **Capture what agents are trying to do** appears when fewer than half of your calls carry an agent intent. Select **Fix with your agent** for a prompt to paste into your coding agent, which updates the SDK and configures the intent fallback. The docs link covers the manual route.+- **Get alerted when a tool call fails** appears when calls failed and no enabled failure alert exists. It opens the Notifications tab.+- **Group tool calls into sessions** appears when almost every call is its own session, or calls carry no session ID. The agent prompt checks your server's transport before enabling conversation IDs.++Steps only evaluate once a project has at least 10 calls.++## Recent activity on the dashboard++The dashboard ends with the 20 newest tool calls under the dashboard's date range, property filters and test-account setting.+**View all tool calls** opens the Activity tab on the same filters.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 6d4fc632579b..e948f6241757 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9389,9 +9389,9 @@ snapshots:scenes-app-max-ai-replay-vision-scan-widget--with-skipped--light:hash: v1.k794b7964.c543228b0f31abb2aae3b274819abdee4ba6a89fb3324fc6aaa2b18aefee5815.S9etTEY8oT2JhOgLO5hdc6VqvbvYhD-nU4P1WKh24ygscenes-app-mcp-analytics--activity--dark:- hash: v1.k794b7964.edf86d02a0ac4cabd95b3e8af8db7abd119a53c680f3f1b71df2b3a27049cfea.zOBLOGJlEPy2ashr-wi9dmUHykgI0F5TDO3Tl2aBNWk+ hash: v1.k794b7964.b37608cc060bbf4a503ebfd0bb87d5160b926b50526eac8a2468a934b5d8a3bf.DeZJNA_NnBvpfBGlMJMIQGPtCBv-7Nw7UcXhISEGiI8scenes-app-mcp-analytics--activity--light:- hash: v1.k794b7964.cf96991f52bc956ec928681ee1f96e42140d31e0991c5a40c7da6b81259503b7.CgitfYGcu4KCWE6xQwDuctd_OZUhu99nMoY4gY8C2oQ+ hash: v1.k794b7964.b5b79d2bd502d8bc4c96fa698d4ff42687da96f6ad1db3b751a4ffdbeed7c7a9.1NKRmJQ6fzE1AWKFq632SoapJensy4UrDKiL20KiuxQscenes-app-mcp-analytics--dashboard--medium--dark:hash: v1.k794b7964.d720f243a9d94d614c00a31063df879f070eac53b3fce76c9d42931304941769.nsNkPSEGWTyU5u1XdmhHnveET4Lvu2hC4egcz9pV12Mscenes-app-mcp-analytics--dashboard--medium--light:@@ -9405,9 +9405,9 @@ snapshots:scenes-app-mcp-analytics--dashboard-narrow--light:hash: v1.k794b7964.1b0f034d65b83b016c1b956f6fd26ceeea9b3eec2b911fd914abdba311d3bcdf.u4FmLXfh5WKo8bYdFk1OcMlYEt7RDMn3Gs2hjTOiCPwscenes-app-mcp-analytics--dashboard-with-menu-bar--dark:- hash: v1.k794b7964.07cc8cb35a57fde33df026df8215dcf756051282b7308852bdfa04580c028ef1._z2sT7s18QVHgntxbY0lgZ-jl_s_gzZpfSX8GUaVrlo+ hash: v1.k794b7964.8a64effc30dcb139ee46eb38eab71c5f7ee39b5fdd8df865f9ebd82b15e9e752.lF2iXnflVWCXsmZXOukWLUQTKgKM5Ijb9OGMO1jUwUcscenes-app-mcp-analytics--dashboard-with-menu-bar--light:- hash: v1.k794b7964.8ab00a0c164b749682df44ba4c3242570a49a273597c02f33c713bf06bdae66a.mCVrrwiO3s7_HpM-H9awFD4PAI-JgGKeDyp9z8cLemI+ hash: v1.k794b7964.5950f14c1cba87ea5610ce1ae7f67791bf2320688e3bd04ffbd1154e465a163f.dyk-zwl99Fj0Dg39JnvwPOnx-zbxUeoxq1nT9FHqGfMscenes-app-mcp-analytics--intent-clustering--dark:hash: v1.k794b7964.9549b853f80d754b9d6ccf17ab144d24218143200c90df7af687e184e7de5329.Er1_HM8avmrqmulj2hCLnkp98-HeuRvF5ed3j-_jS2Ascenes-app-mcp-analytics--intent-clustering--light:diff --git a/products/mcp_analytics/frontend/components/toolCallFeedQuery.test.ts b/products/mcp_analytics/frontend/components/toolCallFeedQuery.test.tsindex ea72064a0a3b..b429cc434f17 100644--- a/products/mcp_analytics/frontend/components/toolCallFeedQuery.test.ts+++ b/products/mcp_analytics/frontend/components/toolCallFeedQuery.test.ts@@ -1,3 +1,4 @@+import { DataTableNode, EventsQuery, NodeKind } from '~/queries/schema/schema-general'import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'import {@@ -7,6 +8,7 @@ import {MCP_ACTIVITY_PAGE_SIZE,MCP_RECENT_TOOL_CALLS_LIMIT,buildRecentToolCallsQuery,+ withFailedCallsOnly,} from './toolCallFeedQuery'describe('tool call feed queries', () => {@@ -29,6 +31,34 @@ describe('tool call feed queries', () => {expect(MCP_ACTIVITY_COLUMNS.find((column) => column.endsWith('-- Tool'))).toContain('$mcp_exec_tool_call_name')})+ it('narrows the feed to failed calls without dropping other filters or stacking itself', () => {+ const toolFilter: AnyPropertyFilter = {+ key: '$mcp_tool_name',+ value: ['search'],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ }+ // Same key on a person property is a different filter and must survive.+ const personFilter: AnyPropertyFilter = {+ key: '$mcp_is_error',+ value: ['true'],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Person,+ }+ const query: DataTableNode = {+ ...DEFAULT_MCP_ACTIVITY_QUERY,+ source: { ...(DEFAULT_MCP_ACTIVITY_QUERY.source as EventsQuery), properties: [toolFilter, personFilter] },+ }++ const once = withFailedCallsOnly(query)+ const twice = withFailedCallsOnly(once)++ expect(once.source.kind).toBe(NodeKind.EventsQuery)+ expect(twice.source).toMatchObject({+ properties: [toolFilter, personFilter, { key: '$mcp_is_error', value: ['true', '1'] }],+ })+ })+it('scopes the dashboard glance to the dashboard filters and drops the toolbar', () => {const toolFilter: AnyPropertyFilter = {key: '$mcp_tool_name',diff --git a/products/mcp_analytics/frontend/components/toolCallFeedQuery.ts b/products/mcp_analytics/frontend/components/toolCallFeedQuery.tsindex 9bd2293ec890..8fa84aa5f721 100644--- a/products/mcp_analytics/frontend/components/toolCallFeedQuery.ts+++ b/products/mcp_analytics/frontend/components/toolCallFeedQuery.ts@@ -2,6 +2,7 @@ import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { MCP_TOOL_CALL_EVENT } from 'lib/components/TaxonomicFilter/utils/mcpProperties'import { DataTableNode, HogQLFilters, NodeKind } from '~/queries/schema/schema-general'+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'export const MCP_ACTIVITY_DATA_COLLECTION_ID = 'mcp-analytics-activity'export const MCP_ACTIVITY_PAGE_SIZE = 100@@ -67,3 +68,23 @@ export function buildRecentToolCallsQuery(filters: HogQLFilters): DataTableNodeshowReload: false,}}++// Matches both encodings the backend counts as failures (see MCP_ERROR_VALUES in ToolCallFeed).+const FAILED_CALLS_FILTER: AnyPropertyFilter = {+ key: '$mcp_is_error',+ value: ['true', '1'],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+}++/** The feed narrowed to failed calls, keeping any other filter the user already applied. */+export function withFailedCallsOnly(query: DataTableNode): DataTableNode {+ if (query.source.kind !== NodeKind.EventsQuery) {+ return query+ }+ const otherFilters = (query.source.properties ?? []).filter(+ (filter) =>+ !(filter.type === FAILED_CALLS_FILTER.type && 'key' in filter && filter.key === FAILED_CALLS_FILTER.key)+ )+ return { ...query, source: { ...query.source, properties: [...otherFilters, FAILED_CALLS_FILTER] } }+}diff --git a/products/mcp_analytics/frontend/earlyData/ActivityNextSteps.tsx b/products/mcp_analytics/frontend/earlyData/ActivityNextSteps.tsxnew file mode 100644index 000000000000..6320d4a09112--- /dev/null+++ b/products/mcp_analytics/frontend/earlyData/ActivityNextSteps.tsx@@ -0,0 +1,102 @@+import { useValues } from 'kea'+import { useState } from 'react'++import { IconSparkles } from '@posthog/icons'+import { LemonButton, LemonModal } from '@posthog/lemon-ui'++import { CodeSnippet } from 'lib/components/CodeSnippet/CodeSnippet'++import { Card } from '../dashboard/Card'+import { mcpEarlyDataLogic } from './mcpEarlyDataLogic'+import type { NextStep } from './nextSteps'++// Mirrors the empty state's "Install with your agent" modal so the two setup surfaces read the same.+function AgentPromptAction({+ step,+ prompt,+ docsUrl,+}: {+ step: NextStep+ prompt: string+ docsUrl: string+}): JSX.Element {+ const [open, setOpen] = useState(false)+ return (+ <>+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconSparkles />}+ onClick={() => setOpen(true)}+ data-attr={`mcp-analytics-activity-next-step-${step.key}`}+ >+ Fix with your agent+ </LemonButton>+ <LemonButton+ type="tertiary"+ size="small"+ to={docsUrl}+ targetBlank+ data-attr={`mcp-analytics-activity-next-step-${step.key}-docs`}+ >+ Docs+ </LemonButton>+ <LemonModal title={step.title} isOpen={open} onClose={() => setOpen(false)} width={640}>+ <p>Open the repository containing your MCP server in your coding agent, then paste this prompt.</p>+ <CodeSnippet wrap compact maxLinesWithoutExpansion={5} thing="prompt">+ {prompt}+ </CodeSnippet>+ <p className="text-secondary mt-4 mb-0">+ Once the change is deployed, new tool calls show up here with the extra data.+ </p>+ </LemonModal>+ </>+ )+}++function NextStepActions({ step }: { step: NextStep }): JSX.Element {+ if (step.action.kind === 'link') {+ return (+ <LemonButton+ type="secondary"+ size="small"+ to={step.action.to}+ data-attr={`mcp-analytics-activity-next-step-${step.key}`}+ >+ {step.action.label}+ </LemonButton>+ )+ }+ return <AgentPromptAction step={step} prompt={step.action.prompt} docsUrl={step.action.docsUrl} />+}++export function ActivityNextSteps(): JSX.Element | null {+ const { nextSteps } = useValues(mcpEarlyDataLogic)++ if (nextSteps.length === 0) {+ return null+ }++ return (+ <Card title="Next steps">+ <ul+ className="m-0 flex list-none flex-col divide-y divide-primary p-0"+ data-attr="mcp-analytics-activity-next-steps"+ >+ {nextSteps.map((step) => (+ <li key={step.key} className="@container py-3 first:pt-0 last:pb-0">+ <div className="flex flex-col gap-2 @2xl:flex-row @2xl:items-center @2xl:justify-between @2xl:gap-6">+ <div className="min-w-0">+ <div className="font-medium">{step.title}</div>+ <div className="text-muted text-sm">{step.detail}</div>+ </div>+ <div className="flex shrink-0 items-center gap-1">+ <NextStepActions step={step} />+ </div>+ </div>+ </li>+ ))}+ </ul>+ </Card>+ )+}diff --git a/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsx b/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsxindex 37dba5c7af8d..12ade5f11b38 100644--- a/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsx+++ b/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsx@@ -1,4 +1,4 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'import { LemonSkeleton, Link } from '@posthog/lemon-ui'@@ -8,20 +8,22 @@ import { formatNumber } from '../dashboard/formatters'import { METRICS_UNLOCK_LIFETIME_CALLS, mcpAnalyticsOnboardingLogic } from '../mcpAnalyticsOnboardingLogic'import { ActivityCallers } from './ActivityCallers'import { ActivityFeed } from './ActivityFeed'+import { ActivityNextSteps } from './ActivityNextSteps'import { mcpEarlyDataLogic } from './mcpEarlyDataLogic'/*** The Activity tab: answers "what are agents doing with my server?" with the- * live feed as the hero, a one-line summary above it, and the dashboard's- * caller charts below. It refreshes live and is the default landing tab for- * low-volume projects, where the windowed metrics dashboard would be noise;- * higher-volume projects land on the Dashboard tab but can always come here- * for recency.+ * live feed as the hero, a one-line summary above it, the next setup step only+ * when there is one, and the dashboard's caller charts below. It refreshes+ * live and is the default landing tab for low-volume projects, where the+ * windowed metrics dashboard would be noise; higher-volume projects land on+ * the Dashboard tab but can always come here for recency.*/export function MCPAnalyticsActivityDashboard(): JSX.Element {return (<div className="flex flex-col gap-4" data-attr="mcp-analytics-activity"><ActivitySummary />+ <ActivityNextSteps /><ActivityFeed /><ActivityCallers /></div>@@ -31,18 +33,30 @@ export function MCPAnalyticsActivityDashboard(): JSX.Element {function ActivitySummary(): JSX.Element {const { dashboardStage } = useValues(mcpAnalyticsOnboardingLogic)const { summary, overview, overviewLoading } = useValues(mcpEarlyDataLogic)+ const { showFailedCallsOnly } = useActions(mcpEarlyDataLogic)// The sentence is derived from the overview, and an absent overview reads as zero calls —// so the first load would claim "No tool calls in the last 30 days" until the numbers// arrive. Only the first load skeletons: the 60s refresh keeps the sentence it already has// rather than flashing back to a placeholder every minute.const awaitingFirstOverview = overviewLoading && !overview+ // Each refreshing value sits in its own element: a bare text node next to siblings breaks under in-page translation.return (<div data-attr="mcp-analytics-activity-summary">{awaitingFirstOverview ? (<LemonSkeleton className="h-6 w-80 max-w-full my-1" />) : (- <h2 className="text-lg font-semibold m-0">{summary}</h2>+ <h2 className="text-lg font-semibold m-0">+ <span>{summary.headline}</span>+ {summary.failures ? (+ <>+ <span>{summary.headline.endsWith('.') ? ' ' : '. '}</span>+ <Link onClick={showFailedCallsOnly} data-attr="mcp-analytics-activity-failures-link">+ <span>{summary.failures}</span> worth a look+ </Link>+ </>+ ) : null}+ </h2>)}<p className="text-muted m-0 mt-1">This view fills in live as agents use your server.diff --git a/products/mcp_analytics/frontend/earlyData/activitySummary.ts b/products/mcp_analytics/frontend/earlyData/activitySummary.tsindex 455c0cf8bf8f..50898920885a 100644--- a/products/mcp_analytics/frontend/earlyData/activitySummary.ts+++ b/products/mcp_analytics/frontend/earlyData/activitySummary.ts@@ -9,36 +9,50 @@ export interface ActivitySummaryInput {topTool: string | null}+export interface ActivitySummary {+ headline: string+ /** The failure count as a phrase ("4 failures"), or null when nothing failed. Rendered as a feed filter. */+ failures: string | null+}+/*** The activity stage's "key metric" is a sentence, not a tile grid: at low* volume the user's question is "what are agents doing with my server?", and a* plain-language answer beats six sparse KPIs. Serves the same intro job as the* one-time first-look hero, but persistent and tailored to early data.*/-export function buildActivitySummary(input: ActivitySummaryInput): string {+export function buildActivitySummary(input: ActivitySummaryInput): ActivitySummary {const { lifetimeCalls, totalCalls, distinctClients, errorCalls, topTool } = inputconst resolvedLifetimeCalls = lifetimeCalls === null ? null : Math.max(lifetimeCalls, totalCalls)+ const failures =+ totalCalls > 0 && errorCalls > 0+ ? `${humanFriendlyNumber(errorCalls)} failure${errorCalls === 1 ? '' : 's'}`+ : nullif (totalCalls === 0) {- return resolvedLifetimeCalls === 0 ? 'Waiting for your first tool call…' : 'No tool calls in the last 30 days'+ return {+ headline:+ resolvedLifetimeCalls === 0 ? 'Waiting for your first tool call…' : 'No tool calls in the last 30 days',+ failures,+ }}if (resolvedLifetimeCalls !== null && resolvedLifetimeCalls <= 5) {- return resolvedLifetimeCalls === 1- ? "Your first tool call arrived. Here's what the agent tried."- : `Your first ${resolvedLifetimeCalls} tool calls arrived. Here's what agents tried.`+ return {+ headline:+ resolvedLifetimeCalls === 1+ ? "Your first tool call arrived. Here's what the agent tried."+ : `Your first ${resolvedLifetimeCalls} tool calls arrived. Here's what agents tried.`,+ failures,+ }}const parts = [`${humanFriendlyLargeNumber(totalCalls)} tool calls in the last 30 days`]if (distinctClients > 0) {parts.push(`from ${humanFriendlyNumber(distinctClients)} client${distinctClients === 1 ? '' : 's'}`)}- let summary = parts.join(' ')+ let headline = parts.join(' ')if (topTool) {- summary += `. ${topTool} is the favorite`- }- if (errorCalls > 0) {- const failures = `${humanFriendlyNumber(errorCalls)} failure${errorCalls === 1 ? '' : 's'}`- summary += `. ${failures} worth a look`+ headline += `. ${topTool} is the favorite`}- return summary+ return { headline, failures }}diff --git a/products/mcp_analytics/frontend/earlyData/earlyData.test.ts b/products/mcp_analytics/frontend/earlyData/earlyData.test.tsindex b0bca23360f6..dc7e545046e8 100644--- a/products/mcp_analytics/frontend/earlyData/earlyData.test.ts+++ b/products/mcp_analytics/frontend/earlyData/earlyData.test.ts@@ -1,4 +1,16 @@import { buildActivitySummary } from './activitySummary'+import { EarlyStats, buildNextSteps } from './nextSteps'++const stats = (overrides: Partial<EarlyStats>): EarlyStats => ({+ totalCalls: 0,+ distinctTools: 0,+ distinctSessions: 0,+ distinctClients: 0,+ callsWithIntent: 0,+ errorCalls: 0,+ missingCapabilityReports: 0,+ ...overrides,+})describe('early data derivations', () => {it.each([@@ -6,31 +18,38 @@ describe('early data derivations', () => {[{ lifetimeCalls: 1, totalCalls: 1, distinctClients: 1, errorCalls: 0, topTool: null },/first tool call arrived/,+ null,],[{ lifetimeCalls: 4, totalCalls: 4, distinctClients: 1, errorCalls: 1, topTool: 'search' },/first 4 tool calls arrived/,+ '1 failure',],[{ lifetimeCalls: 25_000_000, totalCalls: 0, distinctClients: 0, errorCalls: 0, topTool: null },/^No tool calls in the last 30 days$/,+ null,],[{ lifetimeCalls: null, totalCalls: 0, distinctClients: 0, errorCalls: 0, topTool: null },/^No tool calls in the last 30 days$/,+ null,],[{ lifetimeCalls: null, totalCalls: 4, distinctClients: 1, errorCalls: 0, topTool: null },/^4 tool calls in the last 30 days from 1 client$/,+ null,],[{ lifetimeCalls: 3, totalCalls: 4, distinctClients: 1, errorCalls: 0, topTool: null },/^Your first 4 tool calls arrived/,+ null,],- // The full sentence composes favorite + failures with correct punctuation.+ // The failure count is its own phrase so the view can render it as a feed filter.[{ lifetimeCalls: 25_000_000, totalCalls: 42, distinctClients: 3, errorCalls: 4, topTool: 'search_docs' },- /^42 tool calls in the last 30 days from 3 clients\. search_docs is the favorite\. 4 failures worth a look$/,+ /^42 tool calls in the last 30 days from 3 clients\. search_docs is the favorite$/,+ '4 failures',],// Big client and failure counts get thousands separators, unlike the abbreviated call count.[@@ -41,18 +60,56 @@ describe('early data derivations', () => {errorCalls: 533_638,topTool: 'execute-sql',},- /^21\.7M tool calls in the last 30 days from 1,051 clients\. execute-sql is the favorite\. 533,638 failures worth a look$/,+ /^21\.7M tool calls in the last 30 days from 1,051 clients\. execute-sql is the favorite$/,+ '533,638 failures',],- // Failures read grammatically even without a favorite tool.[{ lifetimeCalls: 42, totalCalls: 42, distinctClients: 0, errorCalls: 1, topTool: null },- /^42 tool calls in the last 30 days\. 1 failure worth a look$/,+ /^42 tool calls in the last 30 days$/,+ '1 failure',],+ ])('summarizes %j', (input, headline, failures) => {+ const summary = buildActivitySummary(input)+ expect(summary.headline).toMatch(headline)+ expect(summary.failures).toBe(failures)+ })++ it.each([+ // Under 10 calls ratios are noise: no instrumentation nag yet.+ [stats({ totalCalls: 5, callsWithIntent: 0, distinctSessions: 5 }), false, []],+ // Everything wired and an alert in place: nothing to do, so the row disappears.+ [stats({ totalCalls: 40, callsWithIntent: 35, distinctSessions: 8, errorCalls: 3 }), true, []],+ // No intent + stateless sessions + failures without an alert: priority order.[- { lifetimeCalls: 42, totalCalls: 42, distinctClients: 1, errorCalls: 0, topTool: null },- /^42 tool calls in the last 30 days from 1 client$/,+ stats({ totalCalls: 40, callsWithIntent: 2, distinctSessions: 40, errorCalls: 3 }),+ false,+ ['intent', 'notification', 'sessions'],],- ])('summarizes %j', (input, expected) => {- expect(buildActivitySummary(input)).toMatch(expected)+ // Calls without any session ID need conversation IDs as much as one-session-per-call does.+ [stats({ totalCalls: 40, callsWithIntent: 35, distinctSessions: 0 }), true, ['sessions']],+ // 90% of calls being sessions is already degenerate, not just 100%.+ [stats({ totalCalls: 100, callsWithIntent: 90, distinctSessions: 90 }), true, ['sessions']],+ // Failures never prompt an alert while the count is still unknown.+ [stats({ totalCalls: 40, callsWithIntent: 35, distinctSessions: 8, errorCalls: 3 }), null, []],+ [stats({ totalCalls: 40, callsWithIntent: 35, distinctSessions: 8, errorCalls: 3 }), false, ['notification']],+ ])('picks next steps for %j with notification=%s', (input, hasFailureNotification, expectedKeys) => {+ expect(buildNextSteps(input, hasFailureNotification).map((step) => step.key)).toEqual(expectedKeys)+ })++ it('hands instrumentation steps to an agent and product steps to a link', () => {+ const steps = buildNextSteps(+ stats({ totalCalls: 40, callsWithIntent: 0, distinctSessions: 8, errorCalls: 1 }),+ false+ )++ expect(steps.map((step) => [step.key, step.action.kind])).toEqual([+ ['intent', 'agent-prompt'],+ ['notification', 'link'],+ ])+ expect(steps[0].action).toMatchObject({+ prompt: expect.stringContaining('posthog.com/docs/mcp-analytics/intent'),+ docsUrl: expect.stringContaining('posthog.com/docs/mcp-analytics/intent'),+ })+ expect(steps[1].action).toMatchObject({ to: '/mcp-analytics/notifications' })})})diff --git a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.tsindex dd6962c23a09..2e7f0193a097 100644--- a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts+++ b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts@@ -12,24 +12,23 @@ import {MCPModelBreakdownItem,NodeKind,} from '~/queries/schema/schema-general'+import type { HogFunctionType } from '~/types'-import { DEFAULT_MCP_ACTIVITY_QUERY, MCP_ACTIVITY_DATA_COLLECTION_ID } from '../components/toolCallFeedQuery'+import {+ DEFAULT_MCP_ACTIVITY_QUERY,+ MCP_ACTIVITY_DATA_COLLECTION_ID,+ withFailedCallsOnly,+} from '../components/toolCallFeedQuery'import { mcpAnalyticsSessionsActivityOverview } from '../generated/api'import type { MCPActivityOverviewApi } from '../generated/api.schemas'import { mcpAnalyticsOnboardingLogic } from '../mcpAnalyticsOnboardingLogic'import type { MCPOnboardingSignals } from '../mcpAnalyticsOnboardingLogic'import type { HarnessRow, ModelRow } from '../mcpDashboardOverviewLogic'-import { buildActivitySummary } from './activitySummary'+import { mcpAnalyticsNotificationsLogic } from '../notifications/mcpAnalyticsNotificationsLogic'+import { ActivitySummary, buildActivitySummary } from './activitySummary'+import { EarlyStats, NextStep, buildNextSteps } from './nextSteps'-export interface EarlyStats {- totalCalls: number- distinctTools: number- distinctSessions: number- distinctClients: number- callsWithIntent: number- errorCalls: number- missingCapabilityReports: number-}+export type { EarlyStats, NextStep } from './nextSteps'export interface EarlyToolRow {tool: string@@ -58,24 +57,36 @@ const REFRESH_INTERVAL_MS = 60000// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpEarlyDataLogicValues {+ notifications: HogFunctionType[] // mcpAnalyticsNotificationsLogicsignals: MCPOnboardingSignals | null // mcpAnalyticsOnboardingLogiccurrentProjectId: number | string // teamLogicactivityQuery: DataTableNodeharnessRows: HarnessRow[]harnessRowsLoading: boolean+ hasFailureNotification: boolean | nullhasModelData: booleanmodelRows: ModelRow[]modelRowsLoading: boolean+ nextSteps: NextStep[]+ notificationsResolved: booleanoverview: MCPActivityOverviewApi | nulloverviewLoading: booleanstats: EarlyStats- summary: string+ summary: ActivitySummarytopTools: EarlyToolRow[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpEarlyDataLogicActions {reloadActivityQuery: () => {} // dataNodeCollectionLogic+ loadNotifications: () => any // mcpAnalyticsNotificationsLogic+ loadNotificationsSuccess: (+ notifications: HogFunctionType[],+ payload?: any+ ) => {+ notifications: HogFunctionType[]+ payload?: any+ } // mcpAnalyticsNotificationsLogicloadSignals: (_?: void | undefined) => void // mcpAnalyticsOnboardingLogicloadHarnessRows: (_: void) => voidloadHarnessRowsFailure: (@@ -128,6 +139,9 @@ export interface mcpEarlyDataLogicActions {setActivityQuery: (query: DataTableNode) => {query: DataTableNode}+ showFailedCallsOnly: () => {+ value: true+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -135,7 +149,9 @@ export interface mcpEarlyDataLogicMeta {__keaTypeGenInternalSelectorTypes: {stats: (overview: MCPActivityOverviewApi | null) => EarlyStatstopTools: (overview: MCPActivityOverviewApi | null) => EarlyToolRow[]- summary: (signals: MCPOnboardingSignals | null, stats: EarlyStats, topTools: EarlyToolRow[]) => string+ summary: (signals: MCPOnboardingSignals | null, stats: EarlyStats, topTools: EarlyToolRow[]) => ActivitySummary+ hasFailureNotification: (notificationsResolved: boolean, notifications: HogFunctionType[]) => boolean | null+ nextSteps: (stats: EarlyStats, hasFailureNotification: boolean | null) => NextStep[]hasModelData: (modelRows: ModelRow[]) => boolean}}@@ -150,12 +166,21 @@ export type mcpEarlyDataLogicType = MakeLogicType<export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([path(['products', 'mcp_analytics', 'frontend', 'earlyData', 'mcpEarlyDataLogic']),connect(() => ({- values: [mcpAnalyticsOnboardingLogic, ['signals'], teamLogic, ['currentProjectId']],+ values: [+ mcpAnalyticsOnboardingLogic,+ ['signals'],+ teamLogic,+ ['currentProjectId'],+ mcpAnalyticsNotificationsLogic,+ ['notifications'],+ ],actions: [// Refresh the lifetime signal with the overview so first-call copy can// advance even after the onboarding signal poll stops.mcpAnalyticsOnboardingLogic,['loadSignals'],+ mcpAnalyticsNotificationsLogic,+ ['loadNotifications', 'loadNotificationsSuccess'],dataNodeCollectionLogic({ key: MCP_ACTIVITY_DATA_COLLECTION_ID }),['reloadAll as reloadActivityQuery'],],@@ -163,9 +188,12 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([actions({refreshAll: true,setActivityQuery: (query: DataTableNode) => ({ query }),+ showFailedCallsOnly: true,}),reducers({activityQuery: [DEFAULT_MCP_ACTIVITY_QUERY, { setActivityQuery: (_, { query }) => query }],+ // The list defaults to empty before its first load, which would read as "no alert set up".+ notificationsResolved: [false, { loadNotificationsSuccess: () => true }],}),loaders(({ values }) => ({overview: {@@ -235,7 +263,7 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([],summary: [(s) => [s.signals, s.stats, s.topTools],- (signals: MCPOnboardingSignals | null, stats: EarlyStats, topTools: EarlyToolRow[]): string =>+ (signals: MCPOnboardingSignals | null, stats: EarlyStats, topTools: EarlyToolRow[]): ActivitySummary =>buildActivitySummary({lifetimeCalls: signals?.toolCallsTotal ?? null,totalCalls: stats.totalCalls,@@ -244,22 +272,38 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([topTool: stats.totalCalls > 10 ? (topTools[0]?.tool ?? null) : null,}),],+ // A paused alert notifies nobody, so only enabled ones count as "set up".+ hasFailureNotification: [+ (s) => [s.notificationsResolved, s.notifications],+ (resolved: boolean, notifications: HogFunctionType[]): boolean | null =>+ resolved ? notifications.some((notification) => notification.enabled) : null,+ ],+ nextSteps: [+ (s) => [s.stats, s.hasFailureNotification],+ (stats: EarlyStats, hasFailureNotification: boolean | null): NextStep[] =>+ buildNextSteps(stats, hasFailureNotification),+ ],hasModelData: [(s) => [s.modelRows],(modelRows: ModelRow[]): boolean => modelRows.some((row) => row.total_calls > 0),],}),- listeners(({ actions }) => ({+ listeners(({ actions, values }) => ({refreshAll: () => {actions.loadSignals()actions.loadOverview()+ actions.loadNotifications()actions.loadHarnessRows()actions.loadModelRows()actions.reloadActivityQuery()},+ showFailedCallsOnly: () => {+ actions.setActivityQuery(withFailedCallsOnly(values.activityQuery))+ },})),afterMount(({ actions, cache }) => {actions.loadOverview()+ actions.loadNotifications()actions.loadHarnessRows()actions.loadModelRows()cache.disposables.add(() => {diff --git a/products/mcp_analytics/frontend/earlyData/nextSteps.ts b/products/mcp_analytics/frontend/earlyData/nextSteps.tsnew file mode 100644index 000000000000..70225f462974--- /dev/null+++ b/products/mcp_analytics/frontend/earlyData/nextSteps.ts@@ -0,0 +1,78 @@+import { urls } from 'scenes/urls'++export interface EarlyStats {+ totalCalls: number+ distinctTools: number+ distinctSessions: number+ distinctClients: number+ callsWithIntent: number+ errorCalls: number+ missingCapabilityReports: number+}++export type NextStepAction =+ | { kind: 'link'; label: string; to: string }+ /** A self-contained instruction the user pastes into their coding agent, with the docs as the fallback. */+ | { kind: 'agent-prompt'; prompt: string; docsUrl: string }++export interface NextStep {+ key: 'intent' | 'notification' | 'sessions'+ title: string+ detail: string+ action: NextStepAction+}++const DOCS = {+ intent: 'https://posthog.com/docs/mcp-analytics/intent',+ conversationId: 'https://posthog.com/docs/mcp-analytics/conversation-id',+}++const INTENT_PROMPT = `My MCP server is instrumented with PostHog MCP analytics (@posthog/mcp for TypeScript or posthog.mcp for Python), but most tool calls arrive without an agent intent. Update the SDK to the latest version, confirm intent capture is enabled on instrument(), and configure the intent fallback so calls where the agent leaves the injected "context" argument empty still get an intent. Follow ${DOCS.intent}.`++const SESSIONS_PROMPT = `My MCP server is instrumented with PostHog MCP analytics (@posthog/mcp for TypeScript or posthog.mcp for Python), but almost every tool call lands in its own session. First check which transport the server uses. If requests are request-scoped or reconnect between calls (stateless HTTP, serverless), update the SDK to the latest version and make sure conversation IDs are enabled on instrument(), so the handle the server returns is echoed back by the agent and calls group into sessions. If one long-lived connection already represents one conversation, leave conversation IDs off and tell me why sessions still split. Follow ${DOCS.conversationId}.`++/** Below this, instrumentation ratios are noise — hold judgment rather than nag. */+const MIN_CALLS_FOR_SIGNAL = 10++/** More than this and the card competes with the feed for attention. */+const MAX_STEPS = 3++/** Only the applicable steps, in priority order: a step that is already done is dead space. */+export function buildNextSteps(stats: EarlyStats, hasFailureNotification: boolean | null): NextStep[] {+ const enoughSignal = stats.totalCalls >= MIN_CALLS_FOR_SIGNAL+ const intentShare = stats.totalCalls > 0 ? stats.callsWithIntent / stats.totalCalls : 0+ // One session per call means no session state survives between calls+ // (stateless/serverless server) — sessions degrade to singletons. No sessions at all means+ // the calls carry no session ID, which needs the same fix.+ const sessionsDegenerate =+ enoughSignal &&+ (stats.distinctSessions === 0 || stats.distinctSessions >= Math.max(2, Math.ceil(stats.totalCalls * 0.9)))++ const steps: NextStep[] = []+ if (enoughSignal && intentShare < 0.5) {+ steps.push({+ key: 'intent',+ title: 'Capture what agents are trying to do',+ detail: `Only ${Math.round(intentShare * 100)}% of tool calls carry an agent intent. With it, the feed shows the goal behind every call.`,+ action: { kind: 'agent-prompt', prompt: INTENT_PROMPT, docsUrl: DOCS.intent },+ })+ }+ // `null` means the count has not loaded; showing the step then would flash and vanish.+ if (stats.errorCalls > 0 && hasFailureNotification === false) {+ steps.push({+ key: 'notification',+ title: 'Get alerted when a tool call fails',+ detail: `${stats.errorCalls} tool call${stats.errorCalls === 1 ? '' : 's'} failed in the last 30 days. Send new failures to Slack, email, or a webhook.`,+ action: { kind: 'link', label: 'Set up an alert', to: urls.mcpAnalyticsNotifications() },+ })+ }+ if (sessionsDegenerate) {+ steps.push({+ key: 'sessions',+ title: 'Group tool calls into sessions',+ detail: 'Almost every call starts a new session, which is typical for stateless servers. Conversation IDs stitch them together.',+ action: { kind: 'agent-prompt', prompt: SESSIONS_PROMPT, docsUrl: DOCS.conversationId },+ })+ }+ return steps.slice(0, MAX_STEPS)+}