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): bound session-detail queries to a 7-day lookback (#62719)

Paul D'Ambradb8d71d33a5e
diff --git a/products/mcp_analytics/backend/intent_generation.py b/products/mcp_analytics/backend/intent_generation.py
index 03f7301e7e9d..dc75049b485a 100644
--- a/products/mcp_analytics/backend/intent_generation.py
+++ b/products/mcp_analytics/backend/intent_generation.py
@@ -5,7 +5,10 @@ and condense them into a short natural-language summary via an LLM. Pure
generation only — caching and persistence live in ``logic.generate_session_intent``.
"""
+from datetime import timedelta
+
from django.conf import settings
+from django.utils import timezone
import openai
import posthoganalytics
@@ -23,6 +26,11 @@ from products.mcp_analytics.backend.facade.contracts import IntentGenerationUnav
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 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.
+SESSION_EVENTS_LOOKBACK = timedelta(days=7)
# Persisted (and returned) when a session has no recorded intents, so callers
# get a definitive answer and we don't re-query ClickHouse on the next request.
NO_INTENT_MESSAGE = "No agent intent was recorded for this session."
@@ -43,6 +51,7 @@ _SESSION_INTENTS_SQL = """
SELECT toString(properties.$mcp_intent) AS intent
FROM events
WHERE event = {event}
+ AND timestamp >= {date_from}
AND properties.$mcp_session_id = {session_id}
AND coalesce(properties.$mcp_intent, '') != ''
ORDER BY timestamp ASC
@@ -56,6 +65,7 @@ def fetch_session_intents(team: Team, session_id: str) -> list[str]:
_SESSION_INTENTS_SQL,
placeholders={
"event": ast.Constant(value=MCP_TOOL_CALL_EVENT),
+ "date_from": ast.Constant(value=timezone.now() - SESSION_EVENTS_LOOKBACK),
"session_id": ast.Constant(value=session_id),
"limit": ast.Constant(value=MAX_INTENTS),
},
diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.py
index 20973d33350c..4ddfc3d42fa6 100644
--- a/products/mcp_analytics/backend/logic.py
+++ b/products/mcp_analytics/backend/logic.py
@@ -38,6 +38,7 @@ SELECT
toString(properties.$mcp_duration_ms) AS duration_ms_raw
FROM events
WHERE event = {event}
+ AND timestamp >= {date_from}
AND properties.$mcp_session_id = {session_id}
ORDER BY timestamp ASC
LIMIT 500
@@ -67,6 +68,10 @@ DEFAULT_SESSION_SORT_COLUMN = "session_start"
# disabled Temporal backfill.
MCP_SESSIONS_LOOKBACK = timedelta(hours=24)
+assert intent_generation.SESSION_EVENTS_LOOKBACK >= MCP_SESSIONS_LOOKBACK, (
+ "SESSION_EVENTS_LOOKBACK must be >= MCP_SESSIONS_LOOKBACK or detail views will silently truncate for listed sessions"
+)
+
# 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.
@@ -306,6 +311,7 @@ def list_mcp_tool_calls(team: Team, session_id: str) -> list[contracts.MCPToolCa
_MCP_TOOL_CALLS_SQL,
placeholders={
"event": ast.Constant(value=MCP_TOOL_CALL_EVENT),
+ "date_from": ast.Constant(value=timezone.now() - intent_generation.SESSION_EVENTS_LOOKBACK),
"session_id": ast.Constant(value=session_id),
},
)
diff --git a/products/mcp_analytics/backend/tests/test_api.py b/products/mcp_analytics/backend/tests/test_api.py
index 0e42a60f94df..eaac94d037a5 100644
--- a/products/mcp_analytics/backend/tests/test_api.py
+++ b/products/mcp_analytics/backend/tests/test_api.py
@@ -5,6 +5,8 @@ from unittest.mock import patch
from django.core.cache import cache
+from parameterized import parameterized
+
from posthog.models.utils import uuid7
from products.mcp_analytics.backend import intent_generation
@@ -375,3 +377,46 @@ class TestGenerateSessionIntent(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTest
assert len(sessions) == 1
assert sessions[0].intent == "Persisted summary."
+
+
+class TestSessionEventsLookbackBound(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):
+ """Session-detail queries bound the scan to SESSION_EVENTS_LOOKBACK so the
+ events sort key can prune instead of reading the team's full history."""
+
+ def _seed_tool_call(self, session_id: str, *, timestamp: datetime, tool: str, intent: str) -> None:
+ _create_event(
+ team=self.team,
+ event="mcp_tool_call",
+ distinct_id="seed",
+ timestamp=timestamp,
+ properties={"$mcp_session_id": session_id, "$mcp_tool_name": tool, "$mcp_intent": intent},
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "tool_calls",
+ lambda self, sid: [c.tool_name for c in api.list_mcp_tool_calls(self.team, session_id=sid)],
+ ["recent_tool"],
+ ),
+ (
+ "session_intents",
+ lambda self, sid: intent_generation.fetch_session_intents(self.team, sid),
+ ["recent intent"],
+ ),
+ ]
+ )
+ def test_excludes_events_older_than_lookback(self, _name, fetch, expected) -> None:
+ session_id = str(uuid7())
+ now = datetime.now(tz=UTC)
+ self._seed_tool_call(
+ session_id, timestamp=now - timedelta(minutes=5), tool="recent_tool", intent="recent intent"
+ )
+ self._seed_tool_call(
+ session_id,
+ timestamp=now - intent_generation.SESSION_EVENTS_LOOKBACK - timedelta(days=1),
+ tool="ancient_tool",
+ intent="ancient intent",
+ )
+
+ assert fetch(self, session_id) == expected