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.

fix(mcp-analytics): key sessions on $session_id (#64524)

Georgis Andonis17a388079070
diff --git a/products/mcp_analytics/backend/dashboard_templates.py b/products/mcp_analytics/backend/dashboard_templates.py
index 339b1b91e3bd..238d7c99f016 100644
--- a/products/mcp_analytics/backend/dashboard_templates.py
+++ b/products/mcp_analytics/backend/dashboard_templates.py
@@ -67,7 +67,7 @@ def get_mcp_analytics_default_template() -> DashboardTemplate:
"name": "$mcp_initialize",
"custom_name": "sessions",
"math": "hogql",
- "math_hogql": "count(DISTINCT properties.$mcp_session_id)",
+ "math_hogql": "count(DISTINCT properties.$session_id)",
},
],
"trendsFilter": {},
diff --git a/products/mcp_analytics/backend/intent_generation.py b/products/mcp_analytics/backend/intent_generation.py
index f1a3630ba10c..2be2dbc63abe 100644
--- a/products/mcp_analytics/backend/intent_generation.py
+++ b/products/mcp_analytics/backend/intent_generation.py
@@ -26,7 +26,7 @@ from products.mcp_analytics.backend.facade.contracts import IntentGenerationUnav
INTENT_MODEL = "gpt-4.1-mini"
MAX_INTENTS = 500
-# Session-detail queries look up one $mcp_session_id; without a timestamp bound
+# Session-detail queries look up one $session_id; without a timestamp bound
# the events sort key (team_id, toDate(timestamp), event, ...) can't prune and
# the scan covers the team's full history. Sessions reachable in the UI are at
# most MCP_SESSIONS_LOOKBACK (24h) old, so 7 days is a generous safety margin.
@@ -52,7 +52,7 @@ SELECT toString(properties.$mcp_intent) AS intent
FROM events
WHERE event = {event}
AND timestamp >= {date_from}
- AND properties.$mcp_session_id = {session_id}
+ AND $session_id = {session_id}
AND coalesce(properties.$mcp_intent, '') != ''
ORDER BY timestamp ASC
LIMIT {limit}
diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.py
index 73dbf79b4b9f..ebbeb3da6f18 100644
--- a/products/mcp_analytics/backend/logic.py
+++ b/products/mcp_analytics/backend/logic.py
@@ -39,7 +39,7 @@ SELECT
FROM events
WHERE event = {event}
AND timestamp >= {date_from}
- AND properties.$mcp_session_id = {session_id}
+ AND $session_id = {session_id}
ORDER BY timestamp ASC
LIMIT 500
"""
@@ -77,14 +77,19 @@ assert intent_generation.SESSION_EVENTS_LOOKBACK >= MCP_SESSIONS_LOOKBACK, (
# short enough that "Reload" still feels live.
SESSIONS_CACHE_TTL_SECONDS = 30
-# One row per $mcp_session_id, aggregated straight from events. The column shape
+# One row per $session_id, aggregated straight from events. The column shape
# (min/max/count/groupUniqArray/argMax) maps 1:1 onto a future AggregatingMergeTree
# if per-team volume ever warrants materialising it. __HAVING__ / __ORDER__ are
# validated structural fragments injected before parsing; {placeholders} are HogQL
# value placeholders.
+# NB: the session id reads from the `$session_id` field, NOT `properties.$session_id`.
+# `$session_id` is a materialised events column; the `properties.` accessor renders it
+# null-wrapped in SELECT but the raw column in HAVING/ORDER, so the search HAVING would
+# mismatch the GROUP BY key and ClickHouse rejects it. The bare field renders the raw
+# column consistently across SELECT/GROUP/HAVING/ORDER.
_MCP_SESSIONS_SQL = """
SELECT
- properties.$mcp_session_id AS session_id,
+ $session_id AS session_id,
min(timestamp) AS session_start,
max(timestamp) AS session_end,
dateDiff('second', min(timestamp), max(timestamp)) AS duration_seconds,
@@ -95,9 +100,9 @@ SELECT
FROM events
WHERE event = {event}
AND timestamp >= {date_from}
- -- coalesce: HogQL property access is nullable (missing key -> NULL) and its
- -- `!=` is null-tolerant, so a bare `!= ''` would keep keyless events.
- AND coalesce(properties.$mcp_session_id, '') != ''
+ -- $session_id is a materialised String column — '' (not NULL) for sessionless
+ -- events — so a bare `!= ''` drops them without a coalesce.
+ AND $session_id != ''
GROUP BY session_id
__HAVING__
ORDER BY __ORDER__
@@ -147,7 +152,7 @@ def list_mcp_sessions(
) -> contracts.MCPSessionsPage:
"""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 of $mcp_tool_call events, grouped in ClickHouse and
+ One row per $session_id over the last 24h of $mcp_tool_call events, grouped in ClickHouse and
scoped to the team so the events sort key prunes the scan. Over-fetches one row
to report ``has_next`` (replay-style) without a separate count query. Results
are 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.py
index ab5f69708b7c..54c9afeed32b 100644
--- a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py
+++ b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py
@@ -254,12 +254,9 @@ class Command(BaseCommand):
)
for session_idx in range(session_count):
- # $mcp_session_id is the canonical session grouping key emitted by the MCP
- # SDK. Use uuid4 because that's the format the real service emits (e.g.
- # ba10420e-7ff2-4253-a6ac-3e404f14f8be).
- mcp_session_id = str(uuid.uuid4())
- # $session_id keeps the PostHog uuid7 convention so session-replay-style
- # consumers don't choke on it.
+ # $session_id is the canonical session key — the @posthog/mcp SDK emits only
+ # this (no $mcp_session_id), so these fixtures mirror a plain SDK-instrumented
+ # server. uuid7 matches the PostHog session-id convention.
session_id = str(uuid7())
if rng.random() < IDENTIFIED_PROBABILITY:
persona = rng.choice(IDENTIFIED_PERSONAS)
@@ -309,7 +306,6 @@ class Command(BaseCommand):
person_properties=person_props,
properties={
"$session_id": session_id,
- "$mcp_session_id": mcp_session_id,
"$mcp_source": NEW_SDK_SOURCE,
"$mcp_tool_name": tool_name,
"$mcp_tool_category": TOOL_CATEGORIES.get(tool_name, "Other"),
@@ -340,7 +336,6 @@ class Command(BaseCommand):
person_properties=person_props,
properties={
"$session_id": session_id,
- "$mcp_session_id": mcp_session_id,
"$mcp_tool_name": tool_name,
"$mcp_client_name": client_name,
"$exception_message": rng.choice(EXCEPTION_MESSAGES),
@@ -356,7 +351,7 @@ class Command(BaseCommand):
team=team, session_id=session_id, defaults={"intent": session_intent}
)
self.stdout.write(
- f" session {session_idx + 1}/{session_count}: {calls} tool calls (mcp_session_id={mcp_session_id})"
+ f" session {session_idx + 1}/{session_count}: {calls} tool calls (session_id={session_id})"
)
self.stdout.write(
diff --git a/products/mcp_analytics/backend/tests/test_api.py b/products/mcp_analytics/backend/tests/test_api.py
index aee457cd0a53..ad9b02053f35 100644
--- a/products/mcp_analytics/backend/tests/test_api.py
+++ b/products/mcp_analytics/backend/tests/test_api.py
@@ -112,7 +112,7 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin,
distinct_id=distinct_id,
timestamp=timestamp,
properties={
- "$mcp_session_id": session_id,
+ "$session_id": session_id,
"$mcp_tool_name": tool,
"$mcp_client_name": client_name,
},
@@ -170,8 +170,8 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin,
assert [s.session_id for s in page.results] == [session_id]
- def test_excludes_events_without_mcp_session_id(self) -> None:
- # Events with no $mcp_session_id (e.g. the bare-schema producers) must not
+ def test_excludes_events_without_session_id(self) -> None:
+ # Events with no $session_id (e.g. the bare-schema producers) must not
# collapse into one empty-keyed "session".
kept = str(uuid7())
self._seed_session(kept, ["query_run"])
@@ -306,7 +306,7 @@ class TestGenerateSessionIntent(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTest
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},
+ properties={"$session_id": session_id, "$mcp_tool_name": tool, "$mcp_intent": intent},
)
def test_returns_cached_intent_without_calling_llm(self) -> None:
@@ -355,7 +355,7 @@ class TestGenerateSessionIntent(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTest
event="$mcp_tool_call",
distinct_id="seed",
timestamp=datetime.now(tz=UTC),
- properties={"$mcp_session_id": session_id, "$mcp_tool_name": "query_run"},
+ properties={"$session_id": session_id, "$mcp_tool_name": "query_run"},
)
with patch.object(intent_generation, "summarize_intents") as mock_summarize:
@@ -389,7 +389,7 @@ class TestSessionEventsLookbackBound(_MCPAnalyticsTeamScopedTestMixin, Clickhous
event="$mcp_tool_call",
distinct_id="seed",
timestamp=timestamp,
- properties={"$mcp_session_id": session_id, "$mcp_tool_name": tool, "$mcp_intent": intent},
+ properties={"$session_id": session_id, "$mcp_tool_name": tool, "$mcp_intent": intent},
)
@parameterized.expand(
diff --git a/products/mcp_analytics/backend/tests/test_dashboard_templates.py b/products/mcp_analytics/backend/tests/test_dashboard_templates.py
index 5a22d7e95f62..3262e6812355 100644
--- a/products/mcp_analytics/backend/tests/test_dashboard_templates.py
+++ b/products/mcp_analytics/backend/tests/test_dashboard_templates.py
@@ -47,7 +47,7 @@ def test_mcp_analytics_default_template_includes_users_and_sessions() -> None:
"name": "$mcp_initialize",
"custom_name": "sessions",
"math": "hogql",
- "math_hogql": "count(DISTINCT properties.$mcp_session_id)",
+ "math_hogql": "count(DISTINCT properties.$session_id)",
},
]
diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
index 0e8a129da5fa..7d83c49b89a1 100644
--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
@@ -35,7 +35,7 @@ const DEFAULT_DATE_FILTER: DateFilter = { dateFrom: '-7d', dateTo: null }
const KPI_QUERY = `
SELECT
__BUCKET__ AS bucket,
- countDistinctIf(toString(properties.$mcp_session_id), toString(properties.$mcp_session_id) != '') AS sessions,
+ countDistinctIf($session_id, $session_id != '') AS sessions,
count() AS tool_calls,
countIf(toBool(properties.$mcp_is_error)) AS errors,
round(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95
@@ -52,7 +52,7 @@ ORDER BY bucket
// applies fixed rules over this set; no per-rule SQL.
const SESSION_ROWS_QUERY = `
SELECT
- toString(properties.$mcp_session_id) AS session_id,
+ $session_id AS session_id,
count() AS tool_calls,
countIf(toBool(properties.$mcp_is_error)) AS errors,
round(countIf(toBool(properties.$mcp_is_error)) * 100.0 / count(), 1) AS error_rate_pct,
@@ -61,8 +61,7 @@ SELECT
max(timestamp) AS last_seen
FROM events
WHERE event = '$mcp_tool_call'
- AND properties.$mcp_session_id IS NOT NULL
- AND properties.$mcp_session_id != ''
+ AND $session_id != ''
AND properties.$mcp_tool_name IS NOT NULL
AND properties.$mcp_tool_name != ''
AND {filters}
@@ -121,7 +120,7 @@ SELECT
) AS client,
count() AS total_calls,
countIf(toBool(properties.$mcp_is_error)) AS errors,
- countDistinctIf(toString(properties.$mcp_session_id), toString(properties.$mcp_session_id) != '') AS sessions
+ countDistinctIf($session_id, $session_id != '') AS sessions
FROM events
WHERE event = '$mcp_tool_call'
AND {filters}