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): source session grouping from $mcp_session_id (#59506)

Lucas Ricoy1c83df353ea3
diff --git a/posthog/temporal/mcp_analytics/backfill_sessions/activities.py b/posthog/temporal/mcp_analytics/backfill_sessions/activities.py
index fa1aa5217bca..baa83422dc33 100644
--- a/posthog/temporal/mcp_analytics/backfill_sessions/activities.py
+++ b/posthog/temporal/mcp_analytics/backfill_sessions/activities.py
@@ -15,20 +15,20 @@ LOGGER = get_write_only_logger()
# Two-pass aggregate:
-# 1. Inner subquery (cheap) — list conversation ids that received any mcp_tool_call event
+# 1. Inner subquery (cheap) — list session ids that received any mcp_tool_call event
# in the last lookback_hours. These are the only sessions whose Postgres row could be
# stale.
-# 2. Outer query — re-aggregate the FULL history of each active conversation id (bounded
+# 2. Outer query — re-aggregate the FULL history of each active session id (bounded
# only by the retention window) so the upsert reflects the complete picture, not just
# what landed in the lookback. Avoids the corruption that a naive lookback-window
# aggregate would cause when a long-lived session gets a fresh event late.
-# The grouping key is $mcp_conversation_id, which the MCP service stamps onto every event in
-# the same conversation. We persist it as MCPSession.session_id since that is the
+# The grouping key is $mcp_session_id, which the MCP SDK stamps onto every event in
+# the same session. We persist it as MCPSession.session_id since that is the
# product-facing identifier of an MCP session.
_AGGREGATE_QUERY = """
SELECT
team_id,
- JSONExtractString(properties, '$mcp_conversation_id') AS session_id,
+ JSONExtractString(properties, '$mcp_session_id') AS session_id,
toString(min(timestamp)) AS session_start,
toString(max(timestamp)) AS session_end,
count() AS tool_call_count,
@@ -37,11 +37,11 @@ SELECT
argMax(JSONExtractString(properties, '$mcp_client_name'), timestamp) AS mcp_client_name
FROM events
WHERE event = 'mcp_tool_call'
- AND JSONExtractString(properties, '$mcp_conversation_id') IN (
- SELECT DISTINCT JSONExtractString(properties, '$mcp_conversation_id')
+ AND JSONExtractString(properties, '$mcp_session_id') IN (
+ SELECT DISTINCT JSONExtractString(properties, '$mcp_session_id')
FROM events
WHERE event = 'mcp_tool_call'
- AND JSONExtractString(properties, '$mcp_conversation_id') != ''
+ AND JSONExtractString(properties, '$mcp_session_id') != ''
AND timestamp >= now() - INTERVAL %(lookback_hours)s HOUR
)
AND timestamp >= now() - INTERVAL %(retention_days)s DAY
diff --git a/posthog/temporal/mcp_analytics/summarize_session_intents/activities.py b/posthog/temporal/mcp_analytics/summarize_session_intents/activities.py
index e8c235a0546c..c4c00905e517 100644
--- a/posthog/temporal/mcp_analytics/summarize_session_intents/activities.py
+++ b/posthog/temporal/mcp_analytics/summarize_session_intents/activities.py
@@ -22,7 +22,7 @@ logger = structlog.get_logger(__name__)
_PRIORITY_TEAM_ID = 2
# Per-team cap for non-priority teams in a single batch. Stops one team from
-# monopolising the global LLM budget by emitting many unique conversation ids.
+# monopolising the global LLM budget by emitting many unique session ids.
_PER_TEAM_CAP = 10
SYSTEM_PROMPT = (
@@ -40,7 +40,7 @@ SELECT JSONExtractString(properties, '$mcp_intent') AS intent
FROM events
WHERE team_id = %(team_id)s
AND event = 'mcp_tool_call'
- AND JSONExtractString(properties, '$mcp_conversation_id') = %(session_id)s
+ AND JSONExtractString(properties, '$mcp_session_id') = %(session_id)s
AND JSONExtractString(properties, '$mcp_intent') != ''
ORDER BY timestamp ASC
LIMIT 200
diff --git a/products/mcp_analytics/backend/intent_clustering.py b/products/mcp_analytics/backend/intent_clustering.py
index 006386b6b640..a3e6981387dc 100644
--- a/products/mcp_analytics/backend/intent_clustering.py
+++ b/products/mcp_analytics/backend/intent_clustering.py
@@ -67,7 +67,7 @@ class IntentRecord:
# TODO(mcp-sessions): when the parallel-team posthog_mcp_session table ships,
# change MCPSession.objects.filter(...) below to point at the real model.
# TODO(intent-routing): chaining is by $session_id today; swap to
-# $conversation_id once tool calls carry it.
+# $mcp_session_id once tool calls carry it consistently.
_SESSION_TOOL_STATS_SQL = """
SELECT
properties.$session_id AS session_id,
diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.py
index 8074fb56c26a..57f983e8fd4a 100644
--- a/products/mcp_analytics/backend/logic.py
+++ b/products/mcp_analytics/backend/logic.py
@@ -35,7 +35,7 @@ SELECT
toString(properties.$mcp_duration_ms) AS duration_ms_raw
FROM events
WHERE event = {event}
- AND properties.$mcp_conversation_id = {session_id}
+ AND properties.$mcp_session_id = {session_id}
ORDER BY timestamp ASC
LIMIT 500
"""
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 53b2881b7494..b90217d6c45c 100644
--- a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py
+++ b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py
@@ -170,10 +170,10 @@ class Command(BaseCommand):
)
for session_idx in range(session_count):
- # $mcp_conversation_id is the canonical session grouping key emitted by the MCP
- # service. Use uuid4 because that's the format the real service emits (e.g.
+ # $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).
- conversation_id = str(uuid.uuid4())
+ 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 = str(uuid7())
@@ -218,7 +218,7 @@ class Command(BaseCommand):
timestamp=timestamp,
properties={
"$session_id": session_id,
- "$mcp_conversation_id": conversation_id,
+ "$mcp_session_id": mcp_session_id,
"$mcp_tool_name": tool_name,
"$mcp_intent": intent,
"$mcp_error_message": "Upstream returned 500" if is_error else "",
@@ -235,9 +235,9 @@ class Command(BaseCommand):
# Don't write to MCPSession directly — the backfill Temporal activity is
# the source of truth and will derive the row from the events we just
# captured. Pre-populating here would produce duplicates keyed on the
- # uuid7 $session_id instead of the uuid4 $mcp_conversation_id.
+ # uuid7 $session_id instead of the uuid4 $mcp_session_id.
self.stdout.write(
- f" session {session_idx + 1}/{session_count}: {calls} tool calls (conversation_id={conversation_id})"
+ f" session {session_idx + 1}/{session_count}: {calls} tool calls (mcp_session_id={mcp_session_id})"
)
self.stdout.write(
diff --git a/products/mcp_analytics/backend/presentation/views.py b/products/mcp_analytics/backend/presentation/views.py
index d69cd6520931..3923913d762e 100644
--- a/products/mcp_analytics/backend/presentation/views.py
+++ b/products/mcp_analytics/backend/presentation/views.py
@@ -125,7 +125,7 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@extend_schema(
operation_id="mcp_analytics_sessions_list",
- description="List MCP sessions for the current project, derived by grouping mcp_tool_call events by $mcp_conversation_id. Ordered by most recent activity first by default.",
+ description="List MCP sessions for the current project, derived by grouping mcp_tool_call events by $mcp_session_id. Ordered by most recent activity first by default.",
parameters=[
OpenApiParameter(
name="search",
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
index 9e44c39d8098..cce1076d3008 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
@@ -164,10 +164,10 @@ function StatStrip({ summary, loading }: { summary: ToolSummary | null; loading:
<Stat label="p95 latency" loading={loading} value={formatDurationMs(summary?.p95_ms ?? null)} />
<Stat label="Users" loading={loading} value={humanFriendlyNumber(summary?.users ?? 0)} />
<Stat
- label="Conversations"
+ label="Sessions"
loading={loading}
value={humanFriendlyNumber(summary?.conversations ?? 0)}
- tooltip="Unique $mcp_conversation_id values, falling back to $session_id where missing."
+ tooltip="Unique $mcp_session_id values, falling back to $session_id where missing."
/>
</div>
)
diff --git a/products/mcp_analytics/frontend/generated/api.ts b/products/mcp_analytics/frontend/generated/api.ts
index aa7b60815d28..005a9fefe576 100644
--- a/products/mcp_analytics/frontend/generated/api.ts
+++ b/products/mcp_analytics/frontend/generated/api.ts
@@ -179,7 +179,7 @@ export const getMcpAnalyticsSessionsListUrl = (projectId: string, params?: McpAn
}
/**
- * List MCP sessions for the current project, derived by grouping mcp_tool_call events by $mcp_conversation_id. Ordered by most recent activity first by default.
+ * List MCP sessions for the current project, derived by grouping mcp_tool_call events by $mcp_session_id. Ordered by most recent activity first by default.
*/
export const mcpAnalyticsSessionsList = async (
projectId: string,
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
index c8ea5c67f135..a45fd72c5c86 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
@@ -69,7 +69,7 @@ SELECT
round(quantileIf(0.5)(toFloat(properties.$mcp_duration_ms), timestamp >= now() - INTERVAL 7 DAY)) AS p50_ms,
round(quantileIf(0.95)(toFloat(properties.$mcp_duration_ms), timestamp >= now() - INTERVAL 7 DAY)) AS p95_ms,
uniqIf(distinct_id, timestamp >= now() - INTERVAL 7 DAY) AS users,
- uniqIf(coalesce(nullIf(toString(properties.$mcp_conversation_id), ''), toString(properties.$session_id)), timestamp >= now() - INTERVAL 7 DAY) AS conversations,
+ uniqIf(coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id)), timestamp >= now() - INTERVAL 7 DAY) AS conversations,
countIf(timestamp >= now() - INTERVAL 14 DAY AND timestamp < now() - INTERVAL 7 DAY) AS calls_prev,
countIf(timestamp >= now() - INTERVAL 14 DAY AND timestamp < now() - INTERVAL 7 DAY AND toBool(properties.$mcp_is_error)) AS errors_prev
FROM events
@@ -301,14 +301,14 @@ LIMIT 5
query: `
WITH tool_calls AS (
SELECT
- coalesce(nullIf(toString(properties.$mcp_conversation_id), ''), toString(properties.$session_id)) AS conv_id,
+ coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id)) AS conv_id,
timestamp,
${EFFECTIVE_TOOL_HOGQL} AS tool
FROM events
WHERE event = 'mcp_tool_call'
AND timestamp >= now() - INTERVAL 7 DAY
AND ${NEW_SDK_FILTER}
- AND notEmpty(coalesce(nullIf(toString(properties.$mcp_conversation_id), ''), toString(properties.$session_id)))
+ AND notEmpty(coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id)))
)
SELECT
prev_tool AS tool,
@@ -344,14 +344,14 @@ LIMIT 5
query: `
WITH tool_calls AS (
SELECT
- coalesce(nullIf(toString(properties.$mcp_conversation_id), ''), toString(properties.$session_id)) AS conv_id,
+ coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id)) AS conv_id,
timestamp,
${EFFECTIVE_TOOL_HOGQL} AS tool
FROM events
WHERE event = 'mcp_tool_call'
AND timestamp >= now() - INTERVAL 7 DAY
AND ${NEW_SDK_FILTER}
- AND notEmpty(coalesce(nullIf(toString(properties.$mcp_conversation_id), ''), toString(properties.$session_id)))
+ AND notEmpty(coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id)))
)
SELECT
next_tool AS tool,