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): add date filter to sessions view (#65760)

Georgis Andonis2a75e0cff138
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 2949d49553d4..fda2bf428495 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5897,9 +5897,9 @@ snapshots:
scenes-app-mcp-analytics--intent-clustering--light:
hash: v1.k794b7964.eb1ee241dbc73a7253676466dff7c5261819f9076291a25d62c51f598dd9b97f.xRtze8s71MHoqaBCL6XlrDDX--gFjajvG_pT6YCuB90
scenes-app-mcp-analytics--sessions--dark:
- hash: v1.k794b7964.277463ad445565d14f2549a063a4f8c0c23a81af419bfafc9eefc65577fb0834.woelvjefGWPDW4Acae_sP2fA7YidrA7tkhfvC8u_AQ4
+ hash: v1.k794b7964.dadc88d76766e87974576e5b5f60e49bb8f2812a7db5613b56706d02ba8ef001.foRWPZ3o4a2CseWPV_XXN3szg68mJMW3qQJXf9R6rHk
scenes-app-mcp-analytics--sessions--light:
- hash: v1.k794b7964.bbe32ae76ef1ed9053d24d860933bc0bf1cca54ed3f601effaf515b8d9a6cd21.saYknnP-f1-BwcwRczq_p6CgUmnH8cmE8YJ_9XpN2Pk
+ hash: v1.k794b7964.0fde7827c45b36caad7e995dd6abd65d9e39c38a1ba522cb23ec75fc55c5458d.DOZyg9JkHNligLOj1PxNRW3LcPfR0Gmm5axD6F7hKGM
scenes-app-mcp-analytics--tool-quality--dark:
hash: v1.k794b7964.5b9e93282f8acb490cc1a994629d482c6b26958f5593d9bc0cf899ddf130aa23.ugxwut5_c5IGrho2rIygMeLWnCO7OJO2642TbxtgUck
scenes-app-mcp-analytics--tool-quality--light:
diff --git a/products/mcp_analytics/backend/facade/api.py b/products/mcp_analytics/backend/facade/api.py
index 81cd3fd67254..f72881c2d9cd 100644
--- a/products/mcp_analytics/backend/facade/api.py
+++ b/products/mcp_analytics/backend/facade/api.py
@@ -1,3 +1,5 @@
+from datetime import datetime
+
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -49,22 +51,32 @@ def create_missing_capability_submission(
def list_mcp_sessions(
- team: Team, limit: int, offset: int, search: str = "", order_by: str = ""
+ team: Team,
+ limit: int,
+ offset: int,
+ search: str = "",
+ order_by: str = "",
+ date_from: str | None = None,
+ date_to: str | None = None,
) -> contracts.MCPSessionsPage:
- return logic.list_mcp_sessions(team, limit=limit, offset=offset, search=search, order_by=order_by)
+ return logic.list_mcp_sessions(
+ team, limit=limit, offset=offset, search=search, order_by=order_by, date_from=date_from, date_to=date_to
+ )
-def list_mcp_tool_calls(team: Team, session_id: str) -> list[contracts.MCPToolCall]:
- return logic.list_mcp_tool_calls(team, session_id=session_id)
+def list_mcp_tool_calls(team: Team, session_id: str, date_from: datetime | None = None) -> list[contracts.MCPToolCall]:
+ return logic.list_mcp_tool_calls(team, session_id=session_id, date_from=date_from)
-def generate_session_intent(team: Team, session_id: str) -> str:
+def generate_session_intent(team: Team, session_id: str, date_from: datetime | None = None) -> str:
"""Generate (or return the cached) intent summary for an MCP session.
Shared entry point for the UI's on-demand button and any future caller
- (e.g. clustering). Persists the result to ``MCPSession.intent``.
+ (e.g. clustering). Persists the result to ``MCPSession.intent``. ``date_from``
+ bounds the event scan to keep older sessions summarisable (same bound as
+ ``list_mcp_tool_calls``).
"""
- return logic.generate_session_intent(team, session_id=session_id)
+ return logic.generate_session_intent(team, session_id=session_id, date_from=date_from)
def get_intent_cluster_snapshot(team: Team) -> contracts.IntentClusterSnapshot:
diff --git a/products/mcp_analytics/backend/intent_generation.py b/products/mcp_analytics/backend/intent_generation.py
index 2be2dbc63abe..54ac4ab8883a 100644
--- a/products/mcp_analytics/backend/intent_generation.py
+++ b/products/mcp_analytics/backend/intent_generation.py
@@ -5,7 +5,7 @@ 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 datetime import datetime, timedelta
from django.conf import settings
from django.utils import timezone
@@ -26,10 +26,9 @@ from products.mcp_analytics.backend.facade.contracts import IntentGenerationUnav
INTENT_MODEL = "gpt-4.1-mini"
MAX_INTENTS = 500
-# 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.
+# Fallback scan bound for the session-detail queries (tool calls + intents) — a single $session_id
+# isn't in the events sort key, so without a timestamp bound the scan covers the team's full
+# history. Callers normally pass the session's start; this covers ones that don't.
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.
@@ -59,13 +58,18 @@ LIMIT {limit}
"""
-def fetch_session_intents(team: Team, session_id: str) -> list[str]:
- """Return the session's recorded ``$mcp_intent``s in chronological order."""
+def fetch_session_intents(team: Team, session_id: str, date_from: datetime | None = None) -> list[str]:
+ """Return the session's recorded ``$mcp_intent``s in chronological order.
+
+ ``date_from`` is the timestamp lower bound that lets the events sort key prune the scan,
+ mirroring ``logic.list_mcp_tool_calls``: callers pass the session's start so the whole session
+ resolves, and it falls back to ``SESSION_EVENTS_LOOKBACK`` for callers that don't.
+ """
query = parse_select(
_SESSION_INTENTS_SQL,
placeholders={
"event": ast.Constant(value=MCP_TOOL_CALL_EVENT),
- "date_from": ast.Constant(value=timezone.now() - SESSION_EVENTS_LOOKBACK),
+ "date_from": ast.Constant(value=date_from or (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 ebbeb3da6f18..dae8b1a04848 100644
--- a/products/mcp_analytics/backend/logic.py
+++ b/products/mcp_analytics/backend/logic.py
@@ -1,15 +1,18 @@
-from datetime import timedelta
+from datetime import datetime, timedelta
from typing import Any
from django.core.cache import cache
from django.db.models import QuerySet
from django.utils import timezone
+from posthog.schema import DateRange
+
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.person import Person
from posthog.models.person.util import get_persons_mapped_by_distinct_id
from posthog.models.team.team import Team
@@ -62,15 +65,19 @@ 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
-# 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)
+# Default window when the caller doesn't pass a date range. Matches the dashboard
+# default so both tabs show the same set of sessions out of the box. The UI always
+# sends an explicit range; this only covers param-less API/token callers.
+DEFAULT_SESSIONS_DATE_FROM = "-7d"
-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"
-)
+# A session that overlaps the window must be reported with its *full* stats (true
+# session_start/end/duration/tool count), not just its in-window slice. We get that
+# by scanning a window padded by this buffer on each side, then keeping only sessions
+# with at least one event actually inside the window. The buffer bounds the extra scan
+# while capturing the whole span of any realistically-long MCP session; a session whose
+# span exceeds it would have its stats clipped at the buffer edge (rare — agent
+# sessions are minutes-to-hours; a multi-day span usually means a reused session_id).
+SESSION_OVERLAP_BUFFER = timedelta(days=1)
# Short TTL so concurrent dashboard tabs / auto-refreshes share one ClickHouse
# aggregation instead of each re-running it — long enough to absorb a burst,
@@ -79,9 +86,16 @@ SESSIONS_CACHE_TTL_SECONDS = 30
# 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
+# if per-team volume ever warrants materialising it. __SEARCH__ / __ORDER__ are
# validated structural fragments injected before parsing; {placeholders} are HogQL
# value placeholders.
+#
+# Session-level windowing: aggregate over the buffered range [scan_from, scan_to] so
+# each session's stats span its *whole* set of events, then keep only sessions with an
+# event inside the requested [window_from, window_to] via the HAVING countIf. This is
+# why a session straddling the window boundary reports full (not clipped) start/end/
+# duration/count, and why its detail view (bounded by session_start) shows every event.
+#
# 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
@@ -99,25 +113,30 @@ SELECT
argMax(properties.$mcp_client_name, timestamp) AS mcp_client_name
FROM events
WHERE event = {event}
- AND timestamp >= {date_from}
+ -- Buffered range so an overlapping session's events outside the window still
+ -- aggregate into its full stats; the timestamp bounds keep the sort key pruning.
+ AND timestamp >= {scan_from}
+ AND timestamp <= {scan_to}
-- $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__
+-- Session-level inclusion: at least one event inside the requested window.
+HAVING countIf(timestamp >= {window_from} AND timestamp <= {window_to}) > 0
+ __SEARCH__
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} "
+# Search is post-aggregation (folded into 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_FILTER = (
+ "AND (session_id ILIKE {search} "
"OR distinct_id ILIKE {search} "
"OR mcp_client_name ILIKE {search} "
- "OR arrayExists(t -> t ILIKE {search}, tools_used)"
+ "OR arrayExists(t -> t ILIKE {search}, tools_used))"
)
@@ -138,8 +157,10 @@ def _normalise_order_by(order_by: str) -> tuple[str, bool]:
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}"
+def _sessions_cache_key(
+ team_id: int, limit: int, offset: int, search: str, order_by: str, date_from: str, date_to: str
+) -> str:
+ payload = f"mcp_sessions_{date_from}_{date_to}_{limit}_{offset}_{search}_{order_by}"
return generate_cache_key(team_id, payload)
@@ -149,13 +170,21 @@ def list_mcp_sessions(
offset: int,
search: str = "",
order_by: str = "",
+ date_from: str | None = None,
+ date_to: str | None = None,
) -> contracts.MCPSessionsPage:
"""List a page of MCP sessions for a team, aggregated on the fly from $mcp_tool_call events.
- 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.
+ One row per $session_id whose session overlaps the selected window, grouped in ClickHouse and
+ scoped to the team so the events sort key prunes the scan. Stats are full-session: a session
+ that straddles the window boundary reports its true start/end/duration/tool count, not just the
+ in-window slice (see ``_MCP_SESSIONS_SQL`` for the buffered-scan + ``countIf`` mechanism).
+ 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.
+
+ ``date_from`` / ``date_to`` accept PostHog date strings (relative like ``-7d`` or absolute
+ ISO timestamps), resolved via ``QueryDateRange`` like the dashboard. ``date_from`` defaults to
+ ``DEFAULT_SESSIONS_DATE_FROM`` when omitted.
``search`` does case-insensitive substring matching across session_id,
distinct_id, mcp_client_name, and any element of tools_used. ``order_by`` is a
@@ -164,12 +193,21 @@ def list_mcp_sessions(
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.
"""
- cache_key = _sessions_cache_key(team.id, limit, offset, search, order_by)
+ effective_date_from = date_from or DEFAULT_SESSIONS_DATE_FROM
+ cache_key = _sessions_cache_key(team.id, limit, offset, search, order_by, effective_date_from, date_to or "")
cached = cache.get(cache_key)
if cached is not None:
return cached
- page = _query_mcp_sessions(team, limit=limit, offset=offset, search=search, order_by=order_by)
+ page = _query_mcp_sessions(
+ team,
+ limit=limit,
+ offset=offset,
+ search=search,
+ order_by=order_by,
+ date_from=effective_date_from,
+ date_to=date_to,
+ )
# Don't cache empty results: a newly set-up team's first sessions would
# otherwise stay hidden for the full TTL.
if page.results:
@@ -183,6 +221,8 @@ def _query_mcp_sessions(
offset: int,
search: str,
order_by: str,
+ date_from: str,
+ date_to: str | None,
) -> contracts.MCPSessionsPage:
column, descending = _normalise_order_by(order_by)
# Append the unique session_id as a tiebreaker so the sort is a *total* order.
@@ -191,21 +231,36 @@ def _query_mcp_sessions(
direction = "DESC" if descending else "ASC"
order_text = f"{column} {direction}" if column == "session_id" else f"{column} {direction}, session_id ASC"
+ # Resolve the date strings (relative like '-7d' or absolute ISO) to concrete bounds,
+ # the same path the dashboard uses. We need both the window and a buffered scan range,
+ # so resolve here rather than via the HogQL {filters} placeholder (which only yields one).
+ query_date_range = QueryDateRange(
+ date_range=DateRange(date_from=date_from, date_to=date_to),
+ team=team,
+ interval=None,
+ now=timezone.now(),
+ )
+ window_from = query_date_range.date_from()
+ window_to = query_date_range.date_to()
+
# Over-fetch one row to learn whether a next page exists, without a count query.
placeholders: dict[str, ast.Expr] = {
"event": ast.Constant(value=MCP_TOOL_CALL_EVENT),
- "date_from": ast.Constant(value=timezone.now() - MCP_SESSIONS_LOOKBACK),
+ "scan_from": ast.Constant(value=window_from - SESSION_OVERLAP_BUFFER),
+ "scan_to": ast.Constant(value=window_to + SESSION_OVERLAP_BUFFER),
+ "window_from": ast.Constant(value=window_from),
+ "window_to": ast.Constant(value=window_to),
"limit": ast.Constant(value=limit + 1),
"offset": ast.Constant(value=offset),
}
- having_text = ""
+ search_text = ""
term = search.strip()
if term:
- having_text = _SESSION_SEARCH_HAVING
+ search_text = _SESSION_SEARCH_FILTER
placeholders["search"] = ast.Constant(value=f"%{term}%")
- sql = _MCP_SESSIONS_SQL.replace("__HAVING__", having_text).replace("__ORDER__", order_text)
+ sql = _MCP_SESSIONS_SQL.replace("__SEARCH__", search_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
@@ -250,7 +305,7 @@ def _attach_intents(team: Team, session_ids: list[str]) -> dict[str, str]:
return {session_id: intent for session_id, intent in rows if intent}
-def generate_session_intent(team: Team, session_id: str) -> str:
+def generate_session_intent(team: Team, session_id: str, date_from: datetime | None = None) -> str:
"""Return the session's intent summary, generating and persisting it on first request.
Cache-on-empty: an existing non-empty ``MCPSession.intent`` is returned as-is. Otherwise the
@@ -259,12 +314,15 @@ def generate_session_intent(team: Team, session_id: str) -> str:
without an LLM call and without persisting anything, so it stays retryable and the listing
doesn't surface a non-intent as an intent.
Raises ``contracts.IntentGenerationUnavailable`` if the LLM is unreachable.
+
+ ``date_from`` bounds the event scan; the UI passes the session's start (the same bound
+ ``list_mcp_tool_calls`` uses) so any listed session stays summarisable.
"""
existing = MCPSession.objects.filter(team=team, session_id=session_id).values_list("intent", flat=True).first()
if existing:
return existing
- intents = intent_generation.fetch_session_intents(team, session_id)
+ intents = intent_generation.fetch_session_intents(team, session_id, date_from=date_from)
if not intents:
return intent_generation.NO_INTENT_MESSAGE
@@ -312,12 +370,19 @@ def _to_session_contract(
)
-def list_mcp_tool_calls(team: Team, session_id: str) -> list[contracts.MCPToolCall]:
+def list_mcp_tool_calls(team: Team, session_id: str, date_from: datetime | None = None) -> list[contracts.MCPToolCall]:
+ """List a session's $mcp_tool_call events in chronological order.
+
+ ``date_from`` is the timestamp lower bound that lets the events sort key prune the scan
+ (``$session_id`` alone isn't in the sort key). The caller passes the session's start so the
+ detail view stays correct for sessions older than the default ``SESSION_EVENTS_LOOKBACK``;
+ when omitted it falls back to that window for param-less API/token callers.
+ """
query = parse_select(
_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),
+ "date_from": ast.Constant(value=date_from or (timezone.now() - intent_generation.SESSION_EVENTS_LOOKBACK)),
"session_id": ast.Constant(value=session_id),
},
)
diff --git a/products/mcp_analytics/backend/presentation/views.py b/products/mcp_analytics/backend/presentation/views.py
index f122af593545..5f943e7b57eb 100644
--- a/products/mcp_analytics/backend/presentation/views.py
+++ b/products/mcp_analytics/backend/presentation/views.py
@@ -1,6 +1,8 @@
+from datetime import datetime
from typing import Any, cast
from django.db.models import QuerySet
+from django.utils.dateparse import parse_datetime
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
@@ -31,6 +33,15 @@ from .serializers import (
)
+def _parse_detail_date_from(raw: str | None) -> datetime | None:
+ """Parse the optional session-start bound for detail queries (an absolute ISO timestamp).
+
+ Returns None on missing or unparseable input so the logic layer falls back to its default
+ lookback rather than 400-ing — the bound is only a scan-pruning hint, never a filter.
+ """
+ return parse_datetime(raw) if raw else None
+
+
class MCPAnalyticsPagination(LimitOffsetPagination):
default_limit = 100
max_limit = 500
@@ -179,6 +190,23 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"Prefix with '-' for descending. Defaults to '-session_start' (newest sessions first)."
),
),
+ OpenApiParameter(
+ name="date_from",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description=(
+ "Start of the window to aggregate sessions over. PostHog date string — relative "
+ "(e.g. '-7d', '-24h') or an absolute ISO timestamp. Defaults to '-7d'."
+ ),
+ ),
+ OpenApiParameter(
+ name="date_to",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="End of the window. PostHog date string or absolute ISO timestamp. Defaults to now.",
+ ),
],
responses={200: MCPSessionSerializer(many=True)},
)
@@ -190,18 +218,41 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
offset = paginator.get_offset(request)
search = request.query_params.get("search", "")
order_by = request.query_params.get("order_by", "")
- page = api.list_mcp_sessions(self.team, limit=limit, offset=offset, search=search, order_by=order_by)
+ date_from = request.query_params.get("date_from") or None
+ date_to = request.query_params.get("date_to") or None
+ page = api.list_mcp_sessions(
+ self.team,
+ limit=limit,
+ offset=offset,
+ search=search,
+ order_by=order_by,
+ date_from=date_from,
+ date_to=date_to,
+ )
serializer = self.get_serializer(page.results, many=True)
return paginator.get_paginated_response(serializer.data, has_next=page.has_next)
@extend_schema(
operation_id="mcp_analytics_sessions_tool_calls",
description="List all $mcp_tool_call events that belong to a given $session_id, in chronological order.",
+ parameters=[
+ OpenApiParameter(
+ name="date_from",
+ type=OpenApiTypes.DATETIME,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description=(
+ "Absolute ISO timestamp lower bound for the event scan — pass the session's "
+ "start so older sessions resolve. Defaults to a 7-day lookback when omitted."
+ ),
+ ),
+ ],
responses={200: MCPToolCallSerializer(many=True)},
)
@action(detail=True, methods=["get"], url_path="tool_calls")
def tool_calls(self, request: Request, pk: str | None = None, *args: Any, **kwargs: Any) -> Response:
- tool_calls = api.list_mcp_tool_calls(self.team, session_id=str(pk or ""))
+ date_from = _parse_detail_date_from(request.query_params.get("date_from"))
+ tool_calls = api.list_mcp_tool_calls(self.team, session_id=str(pk or ""), date_from=date_from)
serializer = MCPToolCallSerializer(tool_calls, many=True)
# has_next is always false: this returns the whole (capped) call list, not a page.
# The field exists because the viewset's paginator shapes the response schema.
@@ -215,6 +266,18 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"the stored summary."
),
request=None,
+ parameters=[
+ OpenApiParameter(
+ name="date_from",
+ type=OpenApiTypes.DATETIME,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description=(
+ "Absolute ISO timestamp lower bound for the intent scan — pass the session's "
+ "start so older sessions resolve. Defaults to a 7-day lookback when omitted."
+ ),
+ ),
+ ],
responses={200: MCPSessionIntentSerializer},
)
@action(detail=True, methods=["post"], url_path="generate_intent")
@@ -222,8 +285,9 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
session_id = str(pk or "")
if not session_id:
return Response({"detail": "session_id is required."}, status=status.HTTP_400_BAD_REQUEST)
+ date_from = _parse_detail_date_from(request.query_params.get("date_from"))
try:
- intent = api.generate_session_intent(self.team, session_id=session_id)
+ intent = api.generate_session_intent(self.team, session_id=session_id, date_from=date_from)
except contracts.IntentGenerationUnavailable:
return Response(
{"detail": "Intent generation is unavailable (LLM not configured)."},
diff --git a/products/mcp_analytics/backend/tests/test_api.py b/products/mcp_analytics/backend/tests/test_api.py
index ad9b02053f35..9219f0e459b2 100644
--- a/products/mcp_analytics/backend/tests/test_api.py
+++ b/products/mcp_analytics/backend/tests/test_api.py
@@ -294,6 +294,150 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin,
paged = [s.session_id for s in first.results] + [s.session_id for s in second.results]
assert paged == ids
+ def test_default_window_includes_sessions_within_seven_days(self) -> None:
+ # Regression: the list previously used a fixed 24h lookback, so a session a few
+ # days old showed on the 7d dashboard but vanished from this list. The default
+ # window now matches the dashboard (DEFAULT_SESSIONS_DATE_FROM = '-7d').
+ session_id = str(uuid7())
+ three_days_ago = datetime.now(tz=UTC) - timedelta(days=3)
+ self._seed_session(
+ session_id,
+ ["query_run"],
+ session_start=three_days_ago,
+ session_end=three_days_ago + timedelta(minutes=1),
+ )
+
+ results = {s.session_id for s in api.list_mcp_sessions(self.team, limit=50, offset=0).results}
+
+ assert session_id in results
+
+ def test_date_from_narrows_the_window(self) -> None:
+ recent = str(uuid7())
+ older = str(uuid7())
+ now = datetime.now(tz=UTC)
+ self._seed_session(
+ recent,
+ ["query_run"],
+ session_start=now - timedelta(minutes=30),
+ session_end=now - timedelta(minutes=29),
+ )
+ self._seed_session(
+ older,
+ ["query_run"],
+ session_start=now - timedelta(hours=5),
+ session_end=now - timedelta(hours=5) + timedelta(minutes=1),
+ )
+
+ within_1h = {
+ s.session_id for s in api.list_mcp_sessions(self.team, limit=50, offset=0, date_from="-1h").results
+ }
+ within_7d = {
+ s.session_id for s in api.list_mcp_sessions(self.team, limit=50, offset=0, date_from="-7d").results
+ }
+
+ assert recent in within_1h
+ assert older not in within_1h
+ assert {recent, older}.issubset(within_7d)
+
+ def test_date_to_bounds_the_upper_end(self) -> None:
+ now = datetime.now(tz=UTC)
+ old = str(uuid7())
+ new = str(uuid7())
+ self._seed_session(
+ old,
+ ["query_run"],
+ session_start=now - timedelta(days=3),
+ session_end=now - timedelta(days=3) + timedelta(minutes=1),
+ )
+ self._seed_session(
+ new,
+ ["query_run"],
+ session_start=now - timedelta(minutes=5),
+ session_end=now - timedelta(minutes=4),
+ )
+
+ # Absolute window [7d ago, 2d ago] so neither bound is ambiguous: it spans the
+ # 3-day-old session but ends before the 5-minute-old one.
+ week_ago = (now - timedelta(days=7)).isoformat()
+ two_days_ago = (now - timedelta(days=2)).isoformat()
+ results = {
+ s.session_id
+ for s in api.list_mcp_sessions(
+ self.team, limit=50, offset=0, date_from=week_ago, date_to=two_days_ago
+ ).results
+ }
+
+ assert old in results
+ assert new not in results
+
+ def test_overlapping_session_reports_full_stats_not_clipped(self) -> None:
+ # A session straddling the window start is included with its FULL stats: the event
+ # before the window counts too, so start/duration/tool count span the whole session
+ # rather than just the in-window slice.
+ session_id = str(uuid7())
+ now = datetime.now(tz=UTC)
+ self._seed_session(
+ session_id,
+ ["query_run", "insight_get"],
+ session_start=now - timedelta(hours=2), # before the window
+ session_end=now - timedelta(minutes=10), # inside the window
+ )
+
+ one_hour_ago = (now - timedelta(hours=1)).isoformat()
+ sessions = [
+ s
+ for s in api.list_mcp_sessions(self.team, limit=50, offset=0, date_from=one_hour_ago).results
+ if s.session_id == session_id
+ ]
+
+ assert len(sessions) == 1
+ session = sessions[0]
+ assert session.tool_calls == 2
+ assert sorted(session.tools_used) == ["insight_get", "query_run"]
+ # session_start is the pre-window event, not clipped up to the window start.
+ assert session.session_start < now - timedelta(hours=1)
+
+ def test_session_entirely_outside_window_is_excluded(self) -> None:
+ # The buffered scan reads events just outside the window, but a session with no event
+ # *inside* the window must not leak in via the buffer.
+ session_id = str(uuid7())
+ now = datetime.now(tz=UTC)
+ self._seed_session(
+ session_id,
+ ["query_run"],
+ session_start=now - timedelta(hours=3),
+ session_end=now - timedelta(hours=2, minutes=59),
+ )
+
+ one_hour_ago = (now - timedelta(hours=1)).isoformat()
+ results = {
+ s.session_id for s in api.list_mcp_sessions(self.team, limit=50, offset=0, date_from=one_hour_ago).results
+ }
+
+ assert session_id not in results
+
+ def test_detail_shows_all_events_for_overlapping_session(self) -> None:
+ # Clicking an overlapping session shows every event: the UI passes the full
+ # session_start as the scan bound, so the pre-window event is included too.
+ session_id = str(uuid7())
+ now = datetime.now(tz=UTC)
+ self._seed_session(
+ session_id,
+ ["before_window", "in_window"],
+ session_start=now - timedelta(hours=2),
+ session_end=now - timedelta(minutes=10),
+ )
+
+ one_hour_ago = (now - timedelta(hours=1)).isoformat()
+ session = next(
+ s
+ for s in api.list_mcp_sessions(self.team, limit=50, offset=0, date_from=one_hour_ago).results
+ if s.session_id == session_id
+ )
+ calls = api.list_mcp_tool_calls(self.team, session_id=session_id, date_from=session.session_start)
+
+ assert [c.tool_name for c in calls] == ["before_window", "in_window"]
+
class TestGenerateSessionIntent(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):
def setUp(self) -> None:
@@ -380,8 +524,9 @@ class TestGenerateSessionIntent(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTest
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."""
+ """The session-detail queries (tool calls and intents alike) bound their scan to
+ SESSION_EVENTS_LOOKBACK by default, or to an explicit date_from, 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(
@@ -420,3 +565,28 @@ class TestSessionEventsLookbackBound(_MCPAnalyticsTeamScopedTestMixin, Clickhous
)
assert fetch(self, session_id) == expected
+
+ @parameterized.expand(
+ [
+ (
+ "tool_calls",
+ lambda self, sid, df: [
+ c.tool_name for c in api.list_mcp_tool_calls(self.team, session_id=sid, date_from=df)
+ ],
+ ["ancient_tool"],
+ ),
+ (
+ "session_intents",
+ lambda self, sid, df: intent_generation.fetch_session_intents(self.team, sid, date_from=df),
+ ["ancient intent"],
+ ),
+ ]
+ )
+ def test_date_from_override_includes_events_older_than_lookback(self, _name, fetch, expected) -> None:
+ # Passing the session's own start as the bound (what the UI does) resolves events older than
+ # the default fallback window, so any listed session stays openable / summarisable.
+ session_id = str(uuid7())
+ old_start = datetime.now(tz=UTC) - intent_generation.SESSION_EVENTS_LOOKBACK - timedelta(days=3)
+ self._seed_tool_call(session_id, timestamp=old_start, tool="ancient_tool", intent="ancient intent")
+
+ assert fetch(self, session_id, old_start - timedelta(minutes=1)) == expected
diff --git a/products/mcp_analytics/backend/tests/test_presentation.py b/products/mcp_analytics/backend/tests/test_presentation.py
index bfb6119907fd..5661b6991cf3 100644
--- a/products/mcp_analytics/backend/tests/test_presentation.py
+++ b/products/mcp_analytics/backend/tests/test_presentation.py
@@ -1,10 +1,15 @@
-from posthog.test.base import APIBaseTest
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event
from unittest.mock import patch
+from django.core.cache import cache
+
from parameterized import parameterized
from rest_framework import status
from posthog.models import Organization, Team
+from posthog.models.utils import uuid7
from products.mcp_analytics.backend import intent_generation
from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot, MCPSession
@@ -333,6 +338,44 @@ class TestMCPSessionIntentEndpoint(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest
assert not MCPSession.objects.filter(team=self.team, session_id=session_id).exists()
+class TestMCPSessionToolCallsEndpoint(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):
+ """The detail event list is bounded by the session's aggregated session_start. Listing *all*
+ events hinges on that bound surviving the serialize -> query-param -> parse round-trip without
+ dropping the first event (the one at exactly session_start)."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+
+ def test_tool_calls_bounded_by_session_start_returns_every_event(self) -> None:
+ session_id = str(uuid7())
+ now = datetime.now(tz=UTC)
+ events = [(now - timedelta(hours=2), "first_tool"), (now - timedelta(minutes=5), "last_tool")]
+ for timestamp, tool in events:
+ _create_event(
+ team=self.team,
+ event="$mcp_tool_call",
+ distinct_id="seed",
+ timestamp=timestamp,
+ properties={"$session_id": session_id, "$mcp_tool_name": tool},
+ )
+
+ with patch("posthoganalytics.feature_enabled", return_value=True):
+ listed = self.client.get(f"/api/environments/{self.team.id}/mcp_analytics/sessions/", {"date_from": "-7d"})
+ assert listed.status_code == status.HTTP_200_OK
+ session = next(s for s in listed.json()["results"] if s["session_id"] == session_id)
+ # Hand the serialized session_start straight back, exactly as the UI does.
+ response = self.client.get(
+ f"/api/environments/{self.team.id}/mcp_analytics/sessions/{session_id}/tool_calls/",
+ {"date_from": session["session_start"]},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ # The first event sits at exactly session_start; a `timestamp >= session_start` bound must
+ # still include it after the round-trip — otherwise we'd get just ["last_tool"].
+ assert [c["tool_name"] for c in response.json()["results"]] == ["first_tool", "last_tool"]
+
+
class TestMCPAnalyticsCrossTeamIsolation(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):
"""Team A must never reach Team B's submissions. Now that the submission endpoints are
reachable by anyone inside the mcp-analytics flag (no longer staff-only), pin the tenant
diff --git a/products/mcp_analytics/frontend/generated/api.schemas.ts b/products/mcp_analytics/frontend/generated/api.schemas.ts
index dbd4218412c4..48335258234f 100644
--- a/products/mcp_analytics/frontend/generated/api.schemas.ts
+++ b/products/mcp_analytics/frontend/generated/api.schemas.ts
@@ -395,6 +395,14 @@ export type McpAnalyticsMissingCapabilitiesListParams = {
}
export type McpAnalyticsSessionsListParams = {
+ /**
+ * Start of the window to aggregate sessions over. PostHog date string — relative (e.g. '-7d', '-24h') or an absolute ISO timestamp. Defaults to '-7d'.
+ */
+ date_from?: string
+ /**
+ * End of the window. PostHog date string or absolute ISO timestamp. Defaults to now.
+ */
+ date_to?: string
/**
* Number of results to return per page.
*/
@@ -413,7 +421,18 @@ export type McpAnalyticsSessionsListParams = {
search?: string
}
+export type McpAnalyticsSessionsGenerateIntentParams = {
+ /**
+ * Absolute ISO timestamp lower bound for the intent scan — pass the session's start so older sessions resolve. Defaults to a 7-day lookback when omitted.
+ */
+ date_from?: string
+}
+
export type McpAnalyticsSessionsToolCallsParams = {
+ /**
+ * Absolute ISO timestamp lower bound for the event scan — pass the session's start so older sessions resolve. Defaults to a 7-day lookback when omitted.
+ */
+ date_from?: string
/**
* Number of results to return per page.
*/
diff --git a/products/mcp_analytics/frontend/generated/api.ts b/products/mcp_analytics/frontend/generated/api.ts
index 4b0657d97d64..3c81d4750de9 100644
--- a/products/mcp_analytics/frontend/generated/api.ts
+++ b/products/mcp_analytics/frontend/generated/api.ts
@@ -16,6 +16,7 @@ import type {
MCPSessionIntentApi,
McpAnalyticsFeedbackListParams,
McpAnalyticsMissingCapabilitiesListParams,
+ McpAnalyticsSessionsGenerateIntentParams,
McpAnalyticsSessionsListParams,
McpAnalyticsSessionsToolCallsParams,
PaginatedMCPAnalyticsSubmissionListApi,
@@ -193,8 +194,24 @@ export const mcpAnalyticsSessionsList = async (
})
}
-export const getMcpAnalyticsSessionsGenerateIntentUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/mcp_analytics/sessions/${id}/generate_intent/`
+export const getMcpAnalyticsSessionsGenerateIntentUrl = (
+ projectId: string,
+ id: string,
+ params?: McpAnalyticsSessionsGenerateIntentParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/mcp_analytics/sessions/${id}/generate_intent/?${stringifiedParams}`
+ : `/api/projects/${projectId}/mcp_analytics/sessions/${id}/generate_intent/`
}
/**
@@ -203,9 +220,10 @@ export const getMcpAnalyticsSessionsGenerateIntentUrl = (projectId: string, id:
export const mcpAnalyticsSessionsGenerateIntent = async (
projectId: string,
id: string,
+ params?: McpAnalyticsSessionsGenerateIntentParams,
options?: RequestInit
): Promise<MCPSessionIntentApi> => {
- return apiMutator<MCPSessionIntentApi>(getMcpAnalyticsSessionsGenerateIntentUrl(projectId, id), {
+ return apiMutator<MCPSessionIntentApi>(getMcpAnalyticsSessionsGenerateIntentUrl(projectId, id, params), {
...options,
method: 'POST',
})
diff --git a/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsx b/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsx
index d5d290f2beab..94b50d0d1fd6 100644
--- a/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsx
+++ b/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsx
@@ -25,6 +25,7 @@ import { cn } from 'lib/utils/css-classes'
import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
+import { McpDateFilter } from '../components/McpDateFilter'
import type { MCPSessionApi } from '../generated/api.schemas'
import { MCPSessionDetail } from './MCPSessionDetail'
import { type MCPSessionOrderBy, type MCPSessionSorting, mcpSessionsLogic, orderByParam } from './mcpSessionsLogic'
@@ -133,32 +134,50 @@ function SessionDetailPanel({ className }: { className?: string }): JSX.Element
}
function SessionsListPanel(): JSX.Element {
- const { setFilters, loadSessions, loadMoreSessions, setSorting } = useActions(mcpSessionsLogic)
- const { sessions, sessionsLoading, filters, sorting, hasNext } = useValues(mcpSessionsLogic)
+ const { setFilters, setDateFilter, loadSessions, loadMoreSessions, setSorting } = useActions(mcpSessionsLogic)
+ const { sessions, sessionsLoading, filters, dateFilter, sorting, hasNext } = useValues(mcpSessionsLogic)
return (
<div className="flex flex-col h-full min-h-0 overflow-hidden rounded border border-primary bg-surface-primary">
<div className="shrink-0 flex flex-col gap-2 border-b border-primary p-2">
<div className="flex flex-col gap-2" data-quill>
- <InputGroup className="w-full">
- <InputGroupAddon align="inline-start">
- <InputGroupText>
- <IconSearch />
- </InputGroupText>
- </InputGroupAddon>
- <InputGroupInput
- type="search"
- placeholder="Search by session id, client, or tool"
- onChange={(e) => setFilters({ search: e.target.value })}
- value={filters.search}
+ <div className="flex items-center gap-2">
+ <InputGroup className="flex-1">
+ <InputGroupAddon align="inline-start">
+ <InputGroupText>
+ <IconSearch />
+ </InputGroupText>
+ </InputGroupAddon>
+ <InputGroupInput
+ type="search"
+ placeholder="Search by session id, client, or tool"
+ onChange={(e) => setFilters({ search: e.target.value })}
+ value={filters.search}
+ />
+ </InputGroup>
+ <Button
+ variant="outline"
+ size="icon"
+ className="size-8"
+ onClick={() => loadSessions()}
+ disabled={sessionsLoading}
+ title="Reload sessions"
+ >
+ {sessionsLoading ? <Spinner /> : <IconRefresh />}
+ </Button>
+ </div>
+ <div className="flex items-center justify-between gap-1">
+ <McpDateFilter
+ dateFrom={dateFilter.dateFrom}
+ dateTo={dateFilter.dateTo}
+ onChange={(dateFrom, dateTo) => setDateFilter(dateFrom, dateTo)}
+ dataAttr="mcp-sessions-date-filter"
/>
- </InputGroup>
- <div className="flex items-center justify-between gap-2">
<Select
value={sortingToValue(sorting)}
onValueChange={(value) => setSorting(valueToSorting(value as MCPSessionOrderBy))}
>
- <SelectTrigger size="sm" data-attr="mcp-sessions-sort">
+ <SelectTrigger data-attr="mcp-sessions-sort">
<SelectValue>
{(value: MCPSessionOrderBy) =>
SORT_OPTIONS.find((o) => o.value === value)?.label ?? value
@@ -173,15 +192,6 @@ function SessionsListPanel(): JSX.Element {
))}
</SelectContent>
</Select>
- <Button
- variant="outline"
- size="icon-sm"
- onClick={() => loadSessions()}
- disabled={sessionsLoading}
- title="Reload sessions"
- >
- {sessionsLoading ? <Spinner /> : <IconRefresh />}
- </Button>
</div>
</div>
</div>
diff --git a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
index e36e2cb784a9..3f617c08f019 100644
--- a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
+++ b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
@@ -1,8 +1,10 @@
import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { actionToUrl, router, urlToAction } from 'kea-router'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
import {
mcpAnalyticsSessionsGenerateIntent,
@@ -20,6 +22,15 @@ const DEFAULT_FILTERS: MCPSessionsFilters = {
search: '',
}
+export interface MCPSessionsDateFilter {
+ dateFrom: string | null
+ dateTo: string | null
+}
+
+// Matches the dashboard default (mcpDashboardOverviewLogic) so both tabs show the
+// same window out of the box and the shared date_from/date_to URL params line up.
+const DEFAULT_DATE_FILTER: MCPSessionsDateFilter = { dateFrom: '-7d', dateTo: null }
+
const SEARCH_DEBOUNCE_MS = 300
// How many sessions to fetch per request. Each "Load more" appends the next page
@@ -60,6 +71,7 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
loadSessions: true,
loadMoreSessions: true,
setFilters: (filters: Partial<MCPSessionsFilters>) => ({ filters }),
+ setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
setSorting: (sorting: MCPSessionSorting | null) => ({ sorting }),
setHasNext: (hasNext: boolean) => ({ hasNext }),
selectSession: (sessionId: string | null) => ({ sessionId }),
@@ -79,6 +91,8 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
const response = await mcpAnalyticsSessionsList(String(values.currentProjectId), {
search: values.filters.search || undefined,
order_by: orderByParam(values.sorting),
+ date_from: values.dateFilter.dateFrom || undefined,
+ date_to: values.dateFilter.dateTo || undefined,
limit: SESSIONS_PAGE_SIZE,
offset: 0,
})
@@ -98,13 +112,22 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
const baseSessions = values.sessions
const search = values.filters.search
const orderBy = orderByParam(values.sorting)
+ const dateFrom = values.dateFilter.dateFrom
+ const dateTo = values.dateFilter.dateTo
const response = await mcpAnalyticsSessionsList(String(values.currentProjectId), {
search: search || undefined,
order_by: orderBy,
+ date_from: dateFrom || undefined,
+ date_to: dateTo || undefined,
limit: SESSIONS_PAGE_SIZE,
offset: baseSessions.length,
})
- if (search !== values.filters.search || orderBy !== orderByParam(values.sorting)) {
+ if (
+ search !== values.filters.search ||
+ orderBy !== orderByParam(values.sorting) ||
+ dateFrom !== values.dateFilter.dateFrom ||
+ dateTo !== values.dateFilter.dateTo
+ ) {
return values.sessions
}
actions.setHasNext(response.has_next ?? false)
@@ -121,9 +144,13 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
}
// session_id comes from untrusted event properties — encode it so path/query
// delimiters can't redirect this request to another same-origin endpoint.
+ // Pass the session's start as the scan bound so sessions older than the
+ // backend's default lookback still return their tool calls.
+ const session = values.sessions.find((s) => s.session_id === sessionId)
const response = await mcpAnalyticsSessionsToolCalls(
String(values.currentProjectId),
- encodeURIComponent(sessionId)
+ encodeURIComponent(sessionId),
+ { date_from: session?.session_start || undefined }
)
breakpoint()
return [...(response.results ?? [])]
@@ -138,10 +165,13 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
return null
}
// session_id comes from untrusted event properties — encode it so path/query
- // delimiters can't redirect this POST to another same-origin endpoint.
+ // delimiters can't redirect this POST to another same-origin endpoint. Bound the
+ // intent scan by the session's start so older sessions resolve, mirroring loadToolCalls.
+ const session = values.sessions.find((s) => s.session_id === sessionId)
return await mcpAnalyticsSessionsGenerateIntent(
String(values.currentProjectId),
- encodeURIComponent(sessionId)
+ encodeURIComponent(sessionId),
+ { date_from: session?.session_start || undefined }
)
},
},
@@ -154,6 +184,12 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
setFilters: (state, { filters }) => ({ ...state, ...filters }),
},
],
+ dateFilter: [
+ DEFAULT_DATE_FILTER,
+ {
+ setDateFilter: (_, { dateFrom, dateTo }): MCPSessionsDateFilter => ({ dateFrom, dateTo }),
+ },
+ ],
selectedSessionId: [
null as string | null,
{
@@ -225,6 +261,9 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
setFilters: () => {
actions.loadSessions()
},
+ setDateFilter: () => {
+ actions.loadSessions()
+ },
setSorting: () => {
actions.loadSessions()
},
@@ -255,7 +294,52 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
}
},
})),
- afterMount(({ actions }) => {
- actions.loadSessions()
+ // date_from / date_to are shared with the dashboard via the URL: the scene's tab links
+ // carry searchParams across tabs, so a range picked on either tab follows to the other.
+ actionToUrl(({ values }) => {
+ const syncUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => {
+ const { currentLocation } = router.values
+ const searchParams = { ...currentLocation.searchParams }
+ if (values.dateFilter.dateFrom) {
+ searchParams.date_from = values.dateFilter.dateFrom
+ } else {
+ delete searchParams.date_from
+ }
+ if (values.dateFilter.dateTo) {
+ searchParams.date_to = values.dateFilter.dateTo
+ } else {
+ delete searchParams.date_to
+ }
+ return [currentLocation.pathname, searchParams, currentLocation.hashParams, { replace: true }]
+ }
+ return {
+ setDateFilter: syncUrl,
+ }
+ }),
+ urlToAction(({ actions, values, cache }) => ({
+ [urls.mcpAnalyticsSessions()]: (_, searchParams) => {
+ const dateFrom =
+ typeof searchParams.date_from === 'string' ? searchParams.date_from : DEFAULT_DATE_FILTER.dateFrom
+ const dateTo = typeof searchParams.date_to === 'string' ? searchParams.date_to : null
+ const dateChanged = dateFrom !== values.dateFilter.dateFrom || dateTo !== values.dateFilter.dateTo
+ // setDateFilter reloads via its listener; only load directly when nothing changed.
+ if (dateChanged) {
+ actions.setDateFilter(dateFrom, dateTo)
+ } else if (!cache.hasLoaded) {
+ actions.loadSessions()
+ }
+ cache.hasLoaded = true
+ },
+ })),
+ afterMount(({ actions, cache }) => {
+ // urlToAction owns the initial load when the sessions URL carries date params; this is the
+ // fallback for a param-less mount (and off-route mounts in tests, where urlToAction never
+ // fires). The cache.hasLoaded guard keeps a deep-linked load from firing twice.
+ const { searchParams } = router.values
+ const hasUrlDates = typeof searchParams.date_from === 'string' || typeof searchParams.date_to === 'string'
+ if (!hasUrlDates && !cache.hasLoaded) {
+ cache.hasLoaded = true
+ actions.loadSessions()
+ }
}),
])
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 91829a2a5445..09663415b63f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -55799,6 +55799,14 @@ export namespace Schemas {
};
export type EnvironmentsMcpAnalyticsSessionsListParams = {
+ /**
+ * Start of the window to aggregate sessions over. PostHog date string — relative (e.g. '-7d', '-24h') or an absolute ISO timestamp. Defaults to '-7d'.
+ */
+ date_from?: string;
+ /**
+ * End of the window. PostHog date string or absolute ISO timestamp. Defaults to now.
+ */
+ date_to?: string;
/**
* Number of results to return per page.
*/
@@ -55817,7 +55825,18 @@ export namespace Schemas {
search?: string;
};
+ export type EnvironmentsMcpAnalyticsSessionsGenerateIntentParams = {
+ /**
+ * Absolute ISO timestamp lower bound for the intent scan — pass the session's start so older sessions resolve. Defaults to a 7-day lookback when omitted.
+ */
+ date_from?: string;
+ };
+
export type EnvironmentsMcpAnalyticsSessionsToolCallsParams = {
+ /**
+ * Absolute ISO timestamp lower bound for the event scan — pass the session's start so older sessions resolve. Defaults to a 7-day lookback when omitted.
+ */
+ date_from?: string;
/**
* Number of results to return per page.
*/
@@ -62232,6 +62251,14 @@ export namespace Schemas {
};
export type McpAnalyticsSessionsListParams = {
+ /**
+ * Start of the window to aggregate sessions over. PostHog date string — relative (e.g. '-7d', '-24h') or an absolute ISO timestamp. Defaults to '-7d'.
+ */
+ date_from?: string;
+ /**
+ * End of the window. PostHog date string or absolute ISO timestamp. Defaults to now.
+ */
+ date_to?: string;
/**
* Number of results to return per page.
*/
@@ -62250,7 +62277,18 @@ export namespace Schemas {
search?: string;
};
+ export type McpAnalyticsSessionsGenerateIntentParams = {
+ /**
+ * Absolute ISO timestamp lower bound for the intent scan — pass the session's start so older sessions resolve. Defaults to a 7-day lookback when omitted.
+ */
+ date_from?: string;
+ };
+
export type McpAnalyticsSessionsToolCallsParams = {
+ /**
+ * Absolute ISO timestamp lower bound for the event scan — pass the session's start so older sessions resolve. Defaults to a 7-day lookback when omitted.
+ */
+ date_from?: string;
/**
* Number of results to return per page.
*/
diff --git a/services/mcp/src/generated/mcp_analytics/api.ts b/services/mcp/src/generated/mcp_analytics/api.ts
index 8ff45bf79542..37f533ee000b 100644
--- a/services/mcp/src/generated/mcp_analytics/api.ts
+++ b/services/mcp/src/generated/mcp_analytics/api.ts
@@ -220,3 +220,12 @@ export const McpAnalyticsSessionsGenerateIntentParams = /* @__PURE__ */ zod.obje
"Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
),
})
+
+export const McpAnalyticsSessionsGenerateIntentQueryParams = /* @__PURE__ */ zod.object({
+ date_from: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ "Absolute ISO timestamp lower bound for the intent scan — pass the session's start so older sessions resolve. Defaults to a 7-day lookback when omitted."
+ ),
+})
diff --git a/services/mcp/src/tools/generated/mcp_analytics.ts b/services/mcp/src/tools/generated/mcp_analytics.ts
index 514de2024bd2..bfcdb978962a 100644
--- a/services/mcp/src/tools/generated/mcp_analytics.ts
+++ b/services/mcp/src/tools/generated/mcp_analytics.ts
@@ -6,6 +6,7 @@ import {
McpAnalyticsFeedbackCreateBody,
McpAnalyticsMissingCapabilitiesCreateBody,
McpAnalyticsSessionsGenerateIntentParams,
+ McpAnalyticsSessionsGenerateIntentQueryParams,
} from '@/generated/mcp_analytics/api'
import { createQueryWrapper } from '@/tools/query-wrapper-factory'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
@@ -48,7 +49,9 @@ const mcpAnalyticsIntentClustersRetrieve = (): ToolBase<
},
})
-const McpAnalyticsSessionsGenerateIntentSchema = McpAnalyticsSessionsGenerateIntentParams.omit({ project_id: true })
+const McpAnalyticsSessionsGenerateIntentSchema = McpAnalyticsSessionsGenerateIntentParams.omit({
+ project_id: true,
+}).extend(McpAnalyticsSessionsGenerateIntentQueryParams.shape)
const mcpAnalyticsSessionsGenerateIntent = (): ToolBase<
typeof McpAnalyticsSessionsGenerateIntentSchema,
@@ -61,6 +64,9 @@ const mcpAnalyticsSessionsGenerateIntent = (): ToolBase<
const result = await context.api.request<Schemas.MCPSessionIntent>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/mcp_analytics/sessions/${encodeURIComponent(String(params.id))}/generate_intent/`,
+ query: {
+ date_from: params.date_from,
+ },
})
return result
},