: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
fix(mcp-analytics): read canonical $mcp_tool_call event (#64521)
Georgis Andonisa66e23015c00
diff --git a/products/mcp_analytics/backend/constants.py b/products/mcp_analytics/backend/constants.pynew file mode 100644index 000000000000..9074ce83e382--- /dev/null+++ b/products/mcp_analytics/backend/constants.py@@ -0,0 +1,5 @@+# The @posthog/mcp SDK and PostHog's own MCP server both emit this canonical,+# $-prefixed event. PostHog's server additionally dual-emits a legacy `mcp_tool_call`+# alias for older dashboards; reading both names would double-count its calls, so we+# key on the canonical name only.+MCP_TOOL_CALL_EVENT = "$mcp_tool_call"diff --git a/products/mcp_analytics/backend/dashboard_templates.py b/products/mcp_analytics/backend/dashboard_templates.pyindex ce4fa5e3e28a..339b1b91e3bd 100644--- a/products/mcp_analytics/backend/dashboard_templates.py+++ b/products/mcp_analytics/backend/dashboard_templates.py@@ -18,8 +18,8 @@ def get_mcp_analytics_default_template() -> DashboardTemplate:"kind": "TrendsQuery","series": [{- "event": "mcp_initialize",- "name": "mcp_initialize",+ "event": "$mcp_initialize",+ "name": "$mcp_initialize","kind": "EventsNode",}],@@ -55,16 +55,16 @@ def get_mcp_analytics_default_template() -> DashboardTemplate:"series": [{"kind": "EventsNode",- "event": "mcp_initialize",- "name": "mcp_initialize",+ "event": "$mcp_initialize",+ "name": "$mcp_initialize","custom_name": "users","math": "hogql","math_hogql": "count(DISTINCT person_id)",},{"kind": "EventsNode",- "event": "mcp_initialize",- "name": "mcp_initialize",+ "event": "$mcp_initialize",+ "name": "$mcp_initialize","custom_name": "sessions","math": "hogql","math_hogql": "count(DISTINCT properties.$mcp_session_id)",@@ -94,8 +94,8 @@ def get_mcp_analytics_default_template() -> DashboardTemplate:"series": [{"kind": "EventsNode",- "event": "mcp_tool_call",- "name": "mcp_tool_call",+ "event": "$mcp_tool_call",+ "name": "$mcp_tool_call","math": "total",}],diff --git a/products/mcp_analytics/backend/intent_generation.py b/products/mcp_analytics/backend/intent_generation.pyindex dc75049b485a..f1a3630ba10c 100644--- a/products/mcp_analytics/backend/intent_generation.py+++ b/products/mcp_analytics/backend/intent_generation.py@@ -21,9 +21,9 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models.team.team import Team+from products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENTfrom products.mcp_analytics.backend.facade.contracts import IntentGenerationUnavailable-MCP_TOOL_CALL_EVENT = "mcp_tool_call"INTENT_MODEL = "gpt-4.1-mini"MAX_INTENTS = 500# Session-detail queries look up one $mcp_session_id; without a timestamp bounddiff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.pyindex cb615a767e1d..73dbf79b4b9f 100644--- a/products/mcp_analytics/backend/logic.py+++ b/products/mcp_analytics/backend/logic.py@@ -18,11 +18,10 @@ from posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.utils import generate_cache_keyfrom products.mcp_analytics.backend import intent_generation+from products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENTfrom products.mcp_analytics.backend.facade import contracts, enumsfrom products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot, MCPSession-MCP_TOOL_CALL_EVENT = "mcp_tool_call"-# How long a snapshot may sit in COMPUTING before we assume the task died and# auto-recover. Generous because a real recompute completes in well under a# minute even at the top_n=500 cap; anything past 10 minutes is a dead task.@@ -63,7 +62,7 @@ SESSION_SORT_FIELDS: frozenset[str] = frozenset()DEFAULT_SESSION_SORT_COLUMN = "session_start"-# PR1 aggregates the last 24h of mcp_tool_call events on the fly, scoped to the+# PR1 aggregates the last 24h of $mcp_tool_call events on the fly, scoped to the# team. Wider windows (7d/30d) land in PR2. See# products/mcp_analytics/docs/sessions-overview.md for why this replaced the# disabled Temporal backfill.@@ -146,9 +145,9 @@ def list_mcp_sessions(search: str = "",order_by: str = "",) -> contracts.MCPSessionsPage:- """List a page of MCP sessions for a team, aggregated on the fly from mcp_tool_call events.+ """List a page of MCP sessions for a team, aggregated on the fly from $mcp_tool_call events.- One row per $mcp_session_id over the last 24h, grouped in ClickHouse and+ One row per $mcp_session_id over the last 24h of $mcp_tool_call events, grouped in ClickHouse andscoped to the team so the events sort key prunes the scan. Over-fetches one rowto report ``has_next`` (replay-style) without a separate count query. Resultsare cached briefly so concurrent dashboard refreshes share a single aggregation.diff --git a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.pyindex 0cad152d34ca..ab5f69708b7c 100644--- a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py+++ b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py@@ -152,7 +152,7 @@ EXCEPTION_PAIR_PROBABILITY = 0.6class Command(BaseCommand):- help = "Seed mcp_tool_call events into ClickHouse for local testing of MCP analytics."+ help = "Seed $mcp_tool_call events into ClickHouse for local testing of MCP analytics."def add_arguments(self, parser: CommandParser) -> None:parser.add_argument("--team-id", type=int, required=True, help="Team ID to seed events for.")@@ -169,7 +169,7 @@ class Command(BaseCommand):parser.add_argument("--clear",action="store_true",- help="Delete existing mcp_tool_call events for the team before seeding (clean slate).",+ help="Delete existing $mcp_tool_call events for the team before seeding (clean slate).",)def handle(self, *args: Any, **options: Any) -> None:@@ -194,7 +194,7 @@ class Command(BaseCommand):if clear:sync_execute(f"ALTER TABLE {EVENTS_DATA_TABLE()} DELETE WHERE team_id = %(team_id)s "- "AND (event = 'mcp_tool_call' OR (event = '$exception' AND JSONExtractString(properties, '$mcp_tool_name') != '')) "+ "AND (event = '$mcp_tool_call' OR (event = '$exception' AND JSONExtractString(properties, '$mcp_tool_name') != '')) ""SETTINGS mutations_sync=1",{"team_id": team_id},)@@ -301,7 +301,7 @@ class Command(BaseCommand):duration_ms = int(duration_ms * rng.uniform(1.5, 3.0))create_event(event_uuid=uuid.uuid4(),- event="mcp_tool_call",+ event="$mcp_tool_call",team=team,distinct_id=distinct_id,timestamp=timestamp,diff --git a/products/mcp_analytics/backend/tests/test_api.py b/products/mcp_analytics/backend/tests/test_api.pyindex eaac94d037a5..aee457cd0a53 100644--- a/products/mcp_analytics/backend/tests/test_api.py+++ b/products/mcp_analytics/backend/tests/test_api.py@@ -94,7 +94,7 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin,session_start: datetime | None = None,session_end: datetime | None = None,) -> None:- """Seed one mcp_tool_call event per element of ``tool_sequence``.+ """Seed one $mcp_tool_call event per element of ``tool_sequence``.tool_call_count == len(tool_sequence); tools_used == its distinct values.Events span [session_start, session_end] so min/max timestamps line up.@@ -108,7 +108,7 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin,timestamp = session_end if n == 1 else session_start + span * (i / (n - 1))_create_event(team=self.team,- event="mcp_tool_call",+ event="$mcp_tool_call",distinct_id=distinct_id,timestamp=timestamp,properties={@@ -177,7 +177,7 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin,self._seed_session(kept, ["query_run"])_create_event(team=self.team,- event="mcp_tool_call",+ event="$mcp_tool_call",distinct_id="anon_noisy",timestamp=datetime.now(tz=UTC),properties={"$mcp_tool_name": "query_run"},@@ -303,7 +303,7 @@ class TestGenerateSessionIntent(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestdef _seed_intent_event(self, session_id: str, intent: str, tool: str = "query_run") -> None:_create_event(team=self.team,- event="mcp_tool_call",+ event="$mcp_tool_call",distinct_id="seed",timestamp=datetime.now(tz=UTC),properties={"$mcp_session_id": session_id, "$mcp_tool_name": tool, "$mcp_intent": intent},@@ -349,10 +349,10 @@ class TestGenerateSessionIntent(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestdef test_no_recorded_intents_returns_message_without_calling_llm_or_persisting(self) -> None:session_id = str(uuid7())- # mcp_tool_call event without a $mcp_intent property.+ # $mcp_tool_call event without a $mcp_intent property._create_event(team=self.team,- event="mcp_tool_call",+ event="$mcp_tool_call",distinct_id="seed",timestamp=datetime.now(tz=UTC),properties={"$mcp_session_id": session_id, "$mcp_tool_name": "query_run"},@@ -386,7 +386,7 @@ class TestSessionEventsLookbackBound(_MCPAnalyticsTeamScopedTestMixin, Clickhousdef _seed_tool_call(self, session_id: str, *, timestamp: datetime, tool: str, intent: str) -> None:_create_event(team=self.team,- event="mcp_tool_call",+ event="$mcp_tool_call",distinct_id="seed",timestamp=timestamp,properties={"$mcp_session_id": session_id, "$mcp_tool_name": tool, "$mcp_intent": intent},diff --git a/products/mcp_analytics/backend/tests/test_dashboard_templates.py b/products/mcp_analytics/backend/tests/test_dashboard_templates.pyindex 62ce01a8c797..5a22d7e95f62 100644--- a/products/mcp_analytics/backend/tests/test_dashboard_templates.py+++ b/products/mcp_analytics/backend/tests/test_dashboard_templates.py@@ -12,7 +12,7 @@ def test_mcp_analytics_default_template_includes_oauth_client_pie_chart() -> Nonsource = tile["query"]["source"]assert tile["name"] == "MCP clients"- assert source["series"][0]["event"] == "mcp_initialize"+ assert source["series"][0]["event"] == "$mcp_initialize"assert source["breakdownFilter"] == {"breakdown_type": "event","breakdown": "$mcp_client_name",@@ -35,16 +35,16 @@ def test_mcp_analytics_default_template_includes_users_and_sessions() -> None:assert source["series"] == [{"kind": "EventsNode",- "event": "mcp_initialize",- "name": "mcp_initialize",+ "event": "$mcp_initialize",+ "name": "$mcp_initialize","custom_name": "users","math": "hogql","math_hogql": "count(DISTINCT person_id)",},{"kind": "EventsNode",- "event": "mcp_initialize",- "name": "mcp_initialize",+ "event": "$mcp_initialize",+ "name": "$mcp_initialize","custom_name": "sessions","math": "hogql","math_hogql": "count(DISTINCT properties.$mcp_session_id)",@@ -67,8 +67,8 @@ def test_mcp_analytics_default_template_includes_tool_calls_by_error_status() ->assert source["series"] == [{"kind": "EventsNode",- "event": "mcp_tool_call",- "name": "mcp_tool_call",+ "event": "$mcp_tool_call",+ "name": "$mcp_tool_call","math": "total",}]diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.tsindex 573e59e9b94b..a300382dc64e 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts@@ -26,6 +26,9 @@ const DEFAULT_DATE_FILTER: DateFilter = { dateFrom: '-7d', dateTo: null }// of equal length. The current/previous split is applied in `buildKPIs` against// the time buckets, so the query only needs the doubled date range. `__BUCKET__`// is replaced with a dateTrunc at the active interval at call time.+//+// Queries key on the canonical, $-prefixed event — PostHog's MCP server dual-emits a+// legacy `mcp_tool_call` alias, so matching both names would double-count it.const KPI_QUERY = `SELECT__BUCKET__ AS bucket,@@ -34,7 +37,7 @@ SELECTcountIf(toBool(properties.$mcp_is_error)) AS errors,round(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95FROM events-WHERE event = 'mcp_tool_call'+WHERE event = '$mcp_tool_call'AND properties.$mcp_tool_name IS NOT NULLAND properties.$mcp_tool_name != ''AND {filters}@@ -54,7 +57,7 @@ SELECTuniq(toString(properties.$mcp_tool_name)) AS distinct_tools,max(timestamp) AS last_seenFROM events-WHERE event = 'mcp_tool_call'+WHERE event = '$mcp_tool_call'AND properties.$mcp_session_id IS NOT NULLAND properties.$mcp_session_id != ''AND properties.$mcp_tool_name IS NOT NULL@@ -76,7 +79,7 @@ SELECTround(countIf(toBool(properties.$mcp_is_error)) * 100.0 / count(), 1) AS error_rate_pct,round(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95_duration_msFROM events-WHERE event = 'mcp_tool_call'+WHERE event = '$mcp_tool_call'AND properties.$mcp_tool_name IS NOT NULLAND properties.$mcp_tool_name != ''AND {filters}@@ -92,7 +95,7 @@ SELECTcountIf(toBool(properties.$mcp_is_error)) AS errors,countDistinctIf(toString(properties.$mcp_session_id), toString(properties.$mcp_session_id) != '') AS sessionsFROM events-WHERE event = 'mcp_tool_call'+WHERE event = '$mcp_tool_call'AND properties.$mcp_client_name IS NOT NULLAND properties.$mcp_client_name != ''AND {filters}@@ -108,7 +111,7 @@ SELECTcountIf(NOT toBool(properties.$mcp_is_error)) AS successes,countIf(toBool(properties.$mcp_is_error)) AS errorsFROM events-WHERE event = 'mcp_tool_call'+WHERE event = '$mcp_tool_call'AND properties.$mcp_tool_name IS NOT NULLAND properties.$mcp_tool_name != ''AND {filters}@@ -123,7 +126,7 @@ SELECTtoString(properties.$mcp_tool_name) AS tool,count() AS callsFROM events-WHERE event = 'mcp_tool_call'+WHERE event = '$mcp_tool_call'AND properties.$mcp_tool_name IS NOT NULLAND properties.$mcp_tool_name != ''AND {filters}