: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): list sessions on the fly from events (#59618)
Georgis Andonis77fc38a6b12c
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 7152d6fc7560..ab8cef89a57c 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -43,7 +43,8 @@ class Product(StrEnum):LOGS = "logs"MARKETING_ANALYTICS = "marketing_analytics"MAX_AI = "max_ai"- MCP = "mcp"+ MCP = "mcp" # queries originating through the MCP server (agent tool calls)+ MCP_ANALYTICS = "mcp_analytics" # queries from the MCP analytics product (insights, dashboards, sessions)MESSAGING = "messaging"MOBILE_REPLAY = "mobile_replay"PIPELINE_DESTINATIONS = "pipeline_destinations"diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.pyindex 57f983e8fd4a..2c5e593b1211 100644--- a/products/mcp_analytics/backend/logic.py+++ b/products/mcp_analytics/backend/logic.py@@ -1,7 +1,8 @@from datetime import timedeltafrom typing import Any-from django.db.models import CharField, F, Func, Q, QuerySet, Value+from django.core.cache import cache+from django.db.models import QuerySetfrom django.utils import timezonefrom posthog.hogql import ast@@ -13,9 +14,10 @@ from posthog.models.person import Personfrom posthog.models.person.util import get_persons_mapped_by_distinct_idfrom posthog.models.team.team import Teamfrom posthog.models.user import User+from posthog.utils import generate_cache_keyfrom products.mcp_analytics.backend.facade import contracts, enums-from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot, MCPSession+from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshotMCP_TOOL_CALL_EVENT = "mcp_tool_call"@@ -56,24 +58,78 @@ SESSION_SORT_FIELDS: frozenset[str] = frozenset("distinct_id",})-DEFAULT_SESSION_ORDER_BY = "-session_end"+DEFAULT_SESSION_SORT_COLUMN = "session_end"++# 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.+MCP_SESSIONS_LOOKBACK = timedelta(hours=24)++# Short TTL so concurrent dashboard tabs / auto-refreshes share one ClickHouse+# aggregation instead of each re-running it — long enough to absorb a burst,+# 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+# (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.+_MCP_SESSIONS_SQL = """+SELECT+ properties.$mcp_session_id AS session_id,+ min(timestamp) AS session_start,+ max(timestamp) AS session_end,+ dateDiff('second', min(timestamp), max(timestamp)) AS duration_seconds,+ count() AS tool_call_count,+ groupUniqArray(properties.$mcp_tool_name) AS tools_used,+ argMax(distinct_id, timestamp) AS distinct_id,+ argMax(properties.$mcp_client_name, timestamp) AS mcp_client_name+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, '') != ''+GROUP BY session_id+__HAVING__+ORDER BY __ORDER__+LIMIT {limit}+OFFSET {offset}+"""++# Search is post-aggregation (HAVING) so a match returns the whole session, not+# just the matching events. tools_used / distinct_id / mcp_client_name are+# aggregates, so they can only be filtered after GROUP BY.+_SESSION_SEARCH_HAVING = (+ "HAVING session_id ILIKE {search} "+ "OR distinct_id ILIKE {search} "+ "OR mcp_client_name ILIKE {search} "+ "OR arrayExists(t -> t ILIKE {search}, tools_used)"+)-def _normalise_order_by(order_by: str) -> str:- """Validate and normalise the order_by query param.+def _normalise_order_by(order_by: str) -> tuple[str, bool]:+ """Validate the order_by query param into ``(column, descending)``.Accepts a single column with an optional leading '-' for descending. Falls- back to the default if the field isn't whitelisted; we don't want a stray- query param to ORDER BY an arbitrary column.+ back to the default if the field isn't whitelisted; we never ORDER BY an+ arbitrary client-supplied column."""raw = (order_by or "").strip()if not raw:- return DEFAULT_SESSION_ORDER_BY+ return DEFAULT_SESSION_SORT_COLUMN, Truedescending = raw.startswith("-")field = raw.lstrip("-")if field not in SESSION_SORT_FIELDS:- return DEFAULT_SESSION_ORDER_BY- return f"-{field}" if descending else field+ return DEFAULT_SESSION_SORT_COLUMN, True+ return field, descending+++def _sessions_cache_key(team_id: int, limit: int, offset: int, search: str, order_by: str) -> str:+ payload = f"mcp_sessions_{int(MCP_SESSIONS_LOOKBACK.total_seconds())}_{limit}_{offset}_{search}_{order_by}"+ return generate_cache_key(team_id, payload)def list_mcp_sessions(@@ -83,46 +139,100 @@ def list_mcp_sessions(search: str = "",order_by: str = "",) -> list[contracts.MCPSession]:- """Read the denormalized session metadata that the Temporal backfill maintains.+ """List MCP sessions for a team, aggregated on the fly from mcp_tool_call events.- Person email/name are resolved on the fly by joining MCPSession.distinct_id to- the Person model (routed through personhog), matching how SessionRecording- handles it. event_count is approximated by the size of tools_used since the- new table does not carry a per-call counter.+ One row per $mcp_session_id over the last 24h, grouped in ClickHouse and+ scoped to the team so the events sort key prunes the scan. Results are cached+ briefly so concurrent dashboard refreshes share a single aggregation.``search`` does case-insensitive substring matching across session_id,- distinct_id, mcp_client_name, and any element of tools_used.+ distinct_id, mcp_client_name, and any element of tools_used. ``order_by`` is a+ whitelisted column name; prefix with '-' for descending.- ``order_by`` is a whitelisted column name; prefix with '-' for descending.+ Person email/name are resolved from distinct_id via personhog. ``intent`` is+ empty until the ad-hoc summary endpoint (separate PR) fills the intent seam."""- queryset: QuerySet[MCPSession] = MCPSession.objects.filter(team=team)+ cache_key = _sessions_cache_key(team.id, limit, offset, search, order_by)+ cached = cache.get(cache_key)+ if cached is not None:+ return cached++ sessions = _query_mcp_sessions(team, limit=limit, offset=offset, search=search, order_by=order_by)+ # Don't cache empty results: a newly set-up team's first sessions would+ # otherwise stay hidden for the full TTL.+ if sessions:+ cache.set(cache_key, sessions, SESSIONS_CACHE_TTL_SECONDS)+ return sessions+++def _query_mcp_sessions(+ team: Team,+ limit: int,+ offset: int,+ search: str,+ order_by: str,+) -> list[contracts.MCPSession]:+ column, descending = _normalise_order_by(order_by)+ order_text = f"{column} {'DESC' if descending else 'ASC'}"++ placeholders: dict[str, ast.Expr] = {+ "event": ast.Constant(value=MCP_TOOL_CALL_EVENT),+ "date_from": ast.Constant(value=timezone.now() - MCP_SESSIONS_LOOKBACK),+ "limit": ast.Constant(value=limit),+ "offset": ast.Constant(value=offset),+ }++ having_text = ""term = search.strip()if term:- # tools_used is a Postgres array; flatten it to a single string so a single- # ILIKE catches the substring match across all tool names.- queryset = queryset.annotate(- _tools_used_text=Func(- F("tools_used"),- Value(" "),- function="array_to_string",- output_field=CharField(),- )- ).filter(- Q(session_id__icontains=term)- | Q(distinct_id__icontains=term)- | Q(mcp_client_name__icontains=term)- | Q(_tools_used_text__icontains=term)- )- rows = list(queryset.order_by(_normalise_order_by(order_by))[offset : offset + limit])- persons_by_distinct_id = _resolve_persons(team.id, rows)- return [_to_session_contract(row, persons_by_distinct_id) for row in rows]+ having_text = _SESSION_SEARCH_HAVING+ placeholders["search"] = ast.Constant(value=f"%{term}%")++ sql = _MCP_SESSIONS_SQL.replace("__HAVING__", having_text).replace("__ORDER__", order_text)+ query = parse_select(sql, placeholders=placeholders)++ # name matches the endpoint operation_id so the query is traceable in query_log+ # (JSONExtractString(log_comment, 'name') = 'mcp_analytics_sessions_list').+ with tags_context(+ product=Product.MCP_ANALYTICS, feature=Feature.QUERY, team_id=team.id, name="mcp_analytics_sessions_list"+ ):+ response = execute_hogql_query(query=query, team=team)++ rows = [_row_to_session_dict(row) for row in (response.results or [])]+ persons_by_distinct_id = _resolve_persons(team.id, [row["distinct_id"] for row in rows])+ intents_by_session = _attach_intents(team, [row["session_id"] for row in rows])+ return [_to_session_contract(row, persons_by_distinct_id, intents_by_session) for row in rows]+++def _row_to_session_dict(row: tuple[Any, ...]) -> dict[str, Any]:+ return {+ "session_id": row[0] or "",+ "session_start": row[1],+ "session_end": row[2],+ "duration_seconds": max(0, int(row[3] or 0)),+ "tool_call_count": int(row[4] or 0),+ "tools_used": [tool for tool in (row[5] or []) if tool],+ "distinct_id": row[6] or "",+ "mcp_client_name": row[7] or "",+ }+++def _attach_intents(team: Team, session_ids: list[str]) -> dict[str, str]:+ """Look up persisted session intents keyed by session_id.++ Inert for now: the ad-hoc summary endpoint (separate PR) will persist intents+ in a dedicated MCPSessionIntent table, and this becomes a single indexed+ lookup over the page's session_ids. Kept as a seam so wiring intent in later+ is a pure addition rather than a listing rewrite.+ """+ return {}-def _resolve_persons(team_id: int, rows: list[MCPSession]) -> dict[str, Person]:- distinct_ids = list({row.distinct_id for row in rows if row.distinct_id})- if not distinct_ids:+def _resolve_persons(team_id: int, distinct_ids: list[str]) -> dict[str, Person]:+ unique_ids = list({distinct_id for distinct_id in distinct_ids if distinct_id})+ if not unique_ids:return {}- return get_persons_mapped_by_distinct_id(team_id, distinct_ids)+ return get_persons_mapped_by_distinct_id(team_id, unique_ids)def _person_display(person: Person | None) -> dict[str, str]:@@ -135,21 +245,24 @@ def _person_display(person: Person | None) -> dict[str, str]:}-def _to_session_contract(row: MCPSession, persons_by_distinct_id: dict[str, Person]) -> contracts.MCPSession:- person_display = _person_display(persons_by_distinct_id.get(row.distinct_id))- tools_used = list(row.tools_used or [])+def _to_session_contract(+ row: dict[str, Any],+ persons_by_distinct_id: dict[str, Person],+ intents_by_session: dict[str, str],+) -> contracts.MCPSession:+ person_display = _person_display(persons_by_distinct_id.get(row["distinct_id"]))return contracts.MCPSession(- session_id=row.session_id,- tool_calls=row.tool_call_count,- session_start=row.session_start,- session_end=row.session_end,+ session_id=row["session_id"],+ tool_calls=row["tool_call_count"],+ session_start=row["session_start"],+ session_end=row["session_end"],distinct_id_count=0,- tools_used=tools_used,- mcp_client_name=row.mcp_client_name or "",- distinct_id=row.distinct_id or "",+ tools_used=row["tools_used"],+ mcp_client_name=row["mcp_client_name"],+ distinct_id=row["distinct_id"],person_email=person_display["email"],person_name=person_display["name"],- intent=row.intent or "",+ intent=intents_by_session.get(row["session_id"], ""),)@@ -161,7 +274,9 @@ def list_mcp_tool_calls(team: Team, session_id: str) -> list[contracts.MCPToolCa"session_id": ast.Constant(value=session_id),},)- with tags_context(product=Product.MCP, feature=Feature.QUERY, team_id=team.id):+ with tags_context(+ product=Product.MCP_ANALYTICS, feature=Feature.QUERY, team_id=team.id, name="mcp_analytics_sessions_tool_calls"+ ):response = execute_hogql_query(query=query, team=team)return [contracts.MCPToolCall(diff --git a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.pyindex b90217d6c45c..3f562e3d9182 100644--- a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py+++ b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py@@ -184,14 +184,10 @@ class Command(BaseCommand):distinct_id = f"anon_{uuid.uuid4().hex[:8]}"client_name = rng.choice(CLIENT_NAMES)calls = rng.randint(min_calls, max_calls)- # Anchor each session so it is in the sweet spot for BOTH workflows on the- # next scheduled tick:- # * Backfill discover window = last 1 hour → session must have at- # least one event in the last hour, so session_end >= now - 1h.- # * Summariser idle filter = >= 30 min → session_end <= now - 30 min.- # Picking session_end uniformly in 31-59 minutes ago places every seeded- # session in that overlap, so a single seed run yields an immediately- # backfill-able and immediately summarise-able fixture.+ # Anchor each session within the listing's default 24h window so it shows+ # up on the next request. The listing aggregates recent events on the fly,+ # so any recent session_end works; 31-59 minutes ago keeps the fixtures+ # clearly "in the past" without flirting with the window edge.call_intervals = [rng.randint(15, 90) for _ in range(calls)]total_call_duration = timedelta(seconds=sum(call_intervals))session_end_offset_min = rng.randint(31, 59)@@ -232,10 +228,8 @@ class Command(BaseCommand):)total_events += 1- # 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_session_id.+ # Don't write to MCPSession (it's dormant) — the listing derives sessions+ # on the fly from the events we just captured, grouped by $mcp_session_id.self.stdout.write(f" session {session_idx + 1}/{session_count}: {calls} tool calls (mcp_session_id={mcp_session_id})")diff --git a/products/mcp_analytics/backend/tests/test_api.py b/products/mcp_analytics/backend/tests/test_api.pyindex eb096c5c2f8e..e74441f7bcc2 100644--- a/products/mcp_analytics/backend/tests/test_api.py+++ b/products/mcp_analytics/backend/tests/test_api.py@@ -1,12 +1,13 @@from datetime import UTC, datetime, timedelta-from posthog.test.base import APIBaseTest+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event++from django.core.cache import cachefrom posthog.models.utils import uuid7from products.mcp_analytics.backend.facade import api, contracts, enums-from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPSession-from products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin+from products.mcp_analytics.backend.models import MCPAnalyticsSubmissionclass TestMCPAnalyticsFacade(APIBaseTest):@@ -59,89 +60,126 @@ class TestMCPAnalyticsFacade(APIBaseTest):assert submissions[0].kind == enums.SubmissionKind.MISSING_CAPABILITY-class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):- def _create_session(+class TestListMCPSessions(ClickhouseTestMixin, APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ # Listing results are cached briefly; clear so each test sees fresh data.+ cache.clear()++ def _seed_session(self,session_id: str,- tools_used: list[str],+ tool_sequence: list[str],+ *,client_name: str = "Claude Desktop",distinct_id: str = "anon_seed",session_start: datetime | None = None,session_end: datetime | None = None,- ) -> MCPSession:- session_start = session_start or datetime.now(tz=UTC) - timedelta(minutes=5)- session_end = session_end or datetime.now(tz=UTC)- return MCPSession.objects.create(- team=self.team,- session_id=session_id,- session_start=session_start,- session_end=session_end,- duration_seconds=int((session_end - session_start).total_seconds()),- tools_used=tools_used,- distinct_id=distinct_id,- mcp_client_name=client_name,- )+ ) -> None:+ """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.+ """+ now = datetime.now(tz=UTC)+ session_start = session_start or now - timedelta(minutes=5)+ session_end = session_end or now+ n = len(tool_sequence)+ span = session_end - session_start+ for i, tool in enumerate(tool_sequence):+ timestamp = session_end if n == 1 else session_start + span * (i / (n - 1))+ _create_event(+ team=self.team,+ event="mcp_tool_call",+ distinct_id=distinct_id,+ timestamp=timestamp,+ properties={+ "$mcp_session_id": session_id,+ "$mcp_tool_name": tool,+ "$mcp_client_name": client_name,+ },+ )def test_lists_sessions_in_newest_first_order(self) -> None:session_a = str(uuid7())session_b = str(uuid7())now = datetime.now(tz=UTC)- self._create_session(+ self._seed_session(session_a,- tools_used=["query_run", "insight_get"],+ ["query_run", "insight_get"],session_start=now - timedelta(minutes=10),session_end=now - timedelta(minutes=8),)- self._create_session(+ self._seed_session(session_b,- tools_used=["dashboard_get", "query_run"],+ ["dashboard_get", "query_run"],client_name="Cursor",session_start=now - timedelta(minutes=5),session_end=now - timedelta(minutes=4),)- sessions = api.list_mcp_sessions(self.team, limit=50, offset=0)+ sessions = [+ s for s in api.list_mcp_sessions(self.team, limit=50, offset=0) if s.session_id in {session_a, session_b}+ ]assert len(sessions) == 2# Newest session_end firstassert sessions[0].session_id == session_bassert sessions[0].mcp_client_name == "Cursor"assert sorted(sessions[0].tools_used) == ["dashboard_get", "query_run"]- # tool_calls reflects the persisted total from the backfill activity- assert sessions[0].tool_calls == 0+ # tool_calls is now the live event count, not a persisted total+ assert sessions[0].tool_calls == 2assert sessions[1].session_id == session_aassert sessions[1].mcp_client_name == "Claude Desktop"assert sorted(sessions[1].tools_used) == ["insight_get", "query_run"]- assert sessions[1].tool_calls == 0+ assert sessions[1].tool_calls == 2def test_returns_empty_list_when_no_sessions(self) -> None:assert api.list_mcp_sessions(self.team, limit=50, offset=0) == []+ def test_does_not_cache_empty_responses(self) -> None:+ # An empty result must not be cached, so a session created moments later+ # shows up immediately instead of being hidden by a cached empty list.+ assert api.list_mcp_sessions(self.team, limit=50, offset=0) == []+ session_id = str(uuid7())+ self._seed_session(session_id, ["query_run"])++ sessions = api.list_mcp_sessions(self.team, limit=50, offset=0)++ assert [s.session_id for s in sessions] == [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+ # collapse into one empty-keyed "session".+ kept = str(uuid7())+ self._seed_session(kept, ["query_run"])+ _create_event(+ team=self.team,+ event="mcp_tool_call",+ distinct_id="anon_noisy",+ timestamp=datetime.now(tz=UTC),+ properties={"$mcp_tool_name": "query_run"},+ )++ sessions = api.list_mcp_sessions(self.team, limit=50, offset=0)++ assert [s.session_id for s in sessions] == [kept]+def test_search_filters_across_multiple_columns(self) -> None:alice_id = str(uuid7())bob_id = str(uuid7())misc_id = str(uuid7())- self._create_session(+ self._seed_session(alice_id,- tools_used=["query_run", "insight_get"],+ ["query_run", "insight_get"],client_name="Claude Desktop",distinct_id="[email protected]",)- self._create_session(- bob_id,- tools_used=["dashboard_get"],- client_name="Cursor",- distinct_id="[email protected]",- )- self._create_session(- misc_id,- tools_used=["feature_flag_get"],- client_name="Windsurf",- distinct_id="anon_dead",- )+ self._seed_session(bob_id, ["dashboard_get"], client_name="Cursor", distinct_id="[email protected]")+ self._seed_session(misc_id, ["feature_flag_get"], client_name="Windsurf", distinct_id="anon_dead")def search(term: str) -> set[str]:return {s.session_id for s in api.list_mcp_sessions(self.team, limit=50, offset=0, search=term)}@@ -155,8 +193,7 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):# session_id substring — use suffix because uuid7 prefixes (timestamp) collide# when sessions are created microseconds apart.assert search(alice_id[-12:]) == {alice_id}- # empty search returns everything we created (DB may contain other rows from- # earlier test runs if transactions aren't isolating; subset is enough).+ # empty search returns everything we createdassert {alice_id, bob_id, misc_id}.issubset(search(""))# no matchassert search("zzzz") == set()@@ -167,33 +204,25 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):big_id = str(uuid7())now = datetime.now(tz=UTC)- self._create_session(+ # tool_call_count == number of events; counts chosen so big > old > new.+ self._seed_session(old_id,- tools_used=["query_run"],+ ["query_run"] * 3,session_start=now - timedelta(minutes=120),session_end=now - timedelta(minutes=110),)- old_row = MCPSession.objects.get(session_id=old_id)- old_row.tool_call_count = 3- old_row.save(update_fields=["tool_call_count"])- self._create_session(+ self._seed_session(new_id,- tools_used=["dashboard_get"],+ ["dashboard_get"],session_start=now - timedelta(minutes=20),session_end=now - timedelta(minutes=10),)- new_row = MCPSession.objects.get(session_id=new_id)- new_row.tool_call_count = 1- new_row.save(update_fields=["tool_call_count"])- self._create_session(+ self._seed_session(big_id,- tools_used=["insight_get"],+ ["insight_get"] * 5,session_start=now - timedelta(minutes=60),session_end=now - timedelta(minutes=50),)- big_row = MCPSession.objects.get(session_id=big_id)- big_row.tool_call_count = 99- big_row.save(update_fields=["tool_call_count"])# Restrict to the three we just created so other rows don't interfere.target = {old_id, new_id, big_id}