: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): paginate and validate session tool-calls endpoint (#68154)
Georgis Andonisad102b694fe2
diff --git a/products/mcp_analytics/backend/facade/api.py b/products/mcp_analytics/backend/facade/api.pyindex 9c096397c651..86034cdbac96 100644--- a/products/mcp_analytics/backend/facade/api.py+++ b/products/mcp_analytics/backend/facade/api.py@@ -66,8 +66,14 @@ def list_mcp_sessions()-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 list_mcp_tool_calls(+ team: Team,+ session_id: str,+ limit: int,+ offset: int,+ date_from: datetime | None = None,+) -> contracts.MCPToolCallsPage:+ return logic.list_mcp_tool_calls(team, session_id=session_id, limit=limit, offset=offset, date_from=date_from)def generate_session_intent(team: Team, session_id: str, date_from: datetime | None = None) -> str:diff --git a/products/mcp_analytics/backend/facade/contracts.py b/products/mcp_analytics/backend/facade/contracts.pyindex 73245d14bfdf..d60525246260 100644--- a/products/mcp_analytics/backend/facade/contracts.py+++ b/products/mcp_analytics/backend/facade/contracts.py@@ -91,6 +91,12 @@ class MCPToolCall:duration_ms: int | None+@dataclass(frozen=True)+class MCPToolCallsPage:+ results: list[MCPToolCall]+ has_next: bool++@dataclass(frozen=True)class IntentClusterToolEntry:tool: strdiff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.pyindex dae8b1a04848..7aa1aaabbb70 100644--- a/products/mcp_analytics/backend/logic.py+++ b/products/mcp_analytics/backend/logic.py@@ -44,7 +44,8 @@ WHERE event = {event}AND timestamp >= {date_from}AND $session_id = {session_id}ORDER BY timestamp ASC-LIMIT 500+LIMIT {limit}+OFFSET {offset}"""@@ -370,13 +371,22 @@ def _to_session_contract()-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.+def list_mcp_tool_calls(+ team: Team,+ session_id: str,+ limit: int,+ offset: int,+ date_from: datetime | None = None,+) -> contracts.MCPToolCallsPage:+ """List a page of 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 thedetail 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.++ ``limit`` / ``offset`` page through the session's calls; over-fetch one row to report+ ``has_next`` without a separate count query."""query = parse_select(_MCP_TOOL_CALLS_SQL,@@ -384,13 +394,17 @@ def list_mcp_tool_calls(team: Team, session_id: str, date_from: datetime | None"event": ast.Constant(value=MCP_TOOL_CALL_EVENT),"date_from": ast.Constant(value=date_from or (timezone.now() - intent_generation.SESSION_EVENTS_LOOKBACK)),"session_id": ast.Constant(value=session_id),+ "limit": ast.Constant(value=limit + 1),+ "offset": ast.Constant(value=offset),},)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 [+ rows = response.results or []+ has_next = len(rows) > limit+ results = [contracts.MCPToolCall(event_id=str(row[0]) if row[0] else "",timestamp=row[1],@@ -400,8 +414,9 @@ def list_mcp_tool_calls(team: Team, session_id: str, date_from: datetime | Noneerror_message=row[5] or "",duration_ms=_parse_int(row[6]),)- for row in (response.results or [])+ for row in rows[:limit]]+ return contracts.MCPToolCallsPage(results=results, has_next=has_next)def _parse_int(value: str | int | None) -> int | None:diff --git a/products/mcp_analytics/backend/presentation/serializers.py b/products/mcp_analytics/backend/presentation/serializers.pyindex ba981b55a06c..0dd43601b127 100644--- a/products/mcp_analytics/backend/presentation/serializers.py+++ b/products/mcp_analytics/backend/presentation/serializers.py@@ -1,3 +1,6 @@+from datetime import datetime+from typing import Any+from rest_framework import serializersfrom products.mcp_analytics.backend.models import MCPAnalyticsSubmission@@ -11,6 +14,13 @@ MAX_SUMMARY_LENGTH = 5_000MCP_SESSION_LIST_DEFAULT_LIMIT = 100MCP_SESSION_LIST_MAX_LIMIT = 500+# Same, for a single session's tool-call list. Default == max: this endpoint returns a+# session's whole call list by default (sessions rarely exceed the cap), so callers that+# omit limit get everything; the max doubles as the safety cap on the ClickHouse scan+# (previously a hardcoded LIMIT in the query).+MCP_TOOL_CALLS_DEFAULT_LIMIT = 500+MCP_TOOL_CALLS_MAX_LIMIT = 500+class MCPAnalyticsSubmissionSerializer(serializers.Serializer):id = serializers.UUIDField(read_only=True, help_text="Unique identifier for this submission.")@@ -196,6 +206,51 @@ class MCPSessionListQuerySerializer(serializers.Serializer):)+class LenientDateTimeField(serializers.DateTimeField):+ """A DateTimeField that treats an unparseable value as absent (None) rather than raising.++ ``date_from`` on the tool-calls endpoint is only a scan-pruning hint, never a filter — a+ bad value should fall back to the default lookback instead of 400-ing the request. Keeps+ the ``date-time`` OpenAPI type (drf-spectacular reads the DateTimeField base class).+ """++ def run_validation(self, *args: Any, **kwargs: Any) -> datetime | None:+ try:+ return super().run_validation(*args, **kwargs)+ except serializers.ValidationError:+ return None+++class MCPSessionToolCallsQuerySerializer(serializers.Serializer):+ date_from = LenientDateTimeField(+ required=False,+ help_text=(+ "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 or unparseable."+ ),+ )+ limit = serializers.IntegerField(+ required=False,+ default=MCP_TOOL_CALLS_DEFAULT_LIMIT,+ min_value=1,+ max_value=MCP_TOOL_CALLS_MAX_LIMIT,+ help_text=(+ f"Maximum tool calls to return per page (1–{MCP_TOOL_CALLS_MAX_LIMIT}). Defaults to "+ f"{MCP_TOOL_CALLS_DEFAULT_LIMIT} — the whole page — so a session's calls come back in one "+ f"request; pass a smaller value for a lighter response. Values above the cap are rejected."+ ),+ )+ offset = serializers.IntegerField(+ required=False,+ default=0,+ min_value=0,+ help_text=(+ "Number of tool calls to skip before returning results. Combine with limit to page through "+ "a session's calls; the response's has_next flag indicates whether more remain."+ ),+ )++class MCPSessionSerializer(serializers.Serializer):session_id = serializers.CharField(read_only=True, help_text="$mcp_session_id grouping all $mcp_tool_call events in the session."diff --git a/products/mcp_analytics/backend/presentation/views.py b/products/mcp_analytics/backend/presentation/views.pyindex 7c7c0242495a..8ce741c9b895 100644--- a/products/mcp_analytics/backend/presentation/views.py+++ b/products/mcp_analytics/backend/presentation/views.py@@ -32,6 +32,7 @@ from .serializers import (MCPSessionIntentSerializer,MCPSessionListQuerySerializer,MCPSessionSerializer,+ MCPSessionToolCallsQuerySerializer,MCPToolCallSerializer,)@@ -193,31 +194,24 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# get_paginated_response(has_next=...) is visible to the type checker.return MCPSessionPagination().get_paginated_response(serializer.data, has_next=page.has_next)- @extend_schema(+ @validated_request(+ query_serializer=MCPSessionToolCallsQuerySerializer,+ responses={200: OpenApiResponse(response=MCPToolCallSerializer(many=True))},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)},+ description="List a page of the $mcp_tool_call events that belong to a given $session_id, in chronological order.",)@action(detail=True, methods=["get"], url_path="tool_calls")- def tool_calls(self, request: Request, pk: str | None = None, *args: Any, **kwargs: Any) -> Response:- 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.- return Response({"results": serializer.data, "has_next": False})+ def tool_calls(self, request: ValidatedRequest, pk: str | None = None, *args: Any, **kwargs: Any) -> Response:+ params = request.validated_query_data+ page = api.list_mcp_tool_calls(+ self.team,+ session_id=str(pk or ""),+ limit=params["limit"],+ offset=params["offset"],+ date_from=params.get("date_from"),+ )+ serializer = MCPToolCallSerializer(page.results, many=True)+ return MCPSessionPagination().get_paginated_response(serializer.data, has_next=page.has_next)@extend_schema(operation_id="mcp_analytics_sessions_generate_intent",diff --git a/products/mcp_analytics/backend/tests/test_api.py b/products/mcp_analytics/backend/tests/test_api.pyindex 9219f0e459b2..c637844f9433 100644--- a/products/mcp_analytics/backend/tests/test_api.py+++ b/products/mcp_analytics/backend/tests/test_api.py@@ -434,9 +434,11 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin,for s in api.list_mcp_sessions(self.team, limit=50, offset=0, date_from=one_hour_ago).resultsif s.session_id == session_id)- calls = api.list_mcp_tool_calls(self.team, session_id=session_id, date_from=session.session_start)+ page = api.list_mcp_tool_calls(+ self.team, session_id=session_id, limit=500, offset=0, date_from=session.session_start+ )- assert [c.tool_name for c in calls] == ["before_window", "in_window"]+ assert [c.tool_name for c in page.results] == ["before_window", "in_window"]class TestGenerateSessionIntent(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):@@ -523,6 +525,33 @@ class TestGenerateSessionIntent(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestassert sessions[0].intent == "Persisted summary."+class TestListMCPToolCalls(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):+ def _seed_tool_call(self, session_id: str, *, timestamp: datetime, tool: str) -> None:+ _create_event(+ team=self.team,+ event="$mcp_tool_call",+ distinct_id="seed",+ timestamp=timestamp,+ properties={"$session_id": session_id, "$mcp_tool_name": tool},+ )++ def test_has_next_signals_more_pages(self) -> None:+ session_id = str(uuid7())+ start = datetime.now(tz=UTC) - timedelta(minutes=5)+ for i, tool in enumerate(["first", "second", "third"]):+ self._seed_tool_call(session_id, timestamp=start + timedelta(seconds=i), tool=tool)++ # Over-fetch (limit+1) lets the first page know more exists without a count query;+ # calls come back in chronological order, so the two pages cover all three with no skips.+ first = api.list_mcp_tool_calls(self.team, session_id=session_id, limit=2, offset=0, date_from=start)+ assert [c.tool_name for c in first.results] == ["first", "second"]+ assert first.has_next is True++ second = api.list_mcp_tool_calls(self.team, session_id=session_id, limit=2, offset=2, date_from=start)+ assert [c.tool_name for c in second.results] == ["third"]+ assert second.has_next is False++class TestSessionEventsLookbackBound(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):"""The session-detail queries (tool calls and intents alike) bound their scan toSESSION_EVENTS_LOOKBACK by default, or to an explicit date_from, so the events sort key can@@ -541,7 +570,9 @@ class TestSessionEventsLookbackBound(_MCPAnalyticsTeamScopedTestMixin, Clickhous[("tool_calls",- lambda self, sid: [c.tool_name for c in api.list_mcp_tool_calls(self.team, session_id=sid)],+ lambda self, sid: [+ c.tool_name for c in api.list_mcp_tool_calls(self.team, session_id=sid, limit=500, offset=0).results+ ],["recent_tool"],),(@@ -571,7 +602,10 @@ class TestSessionEventsLookbackBound(_MCPAnalyticsTeamScopedTestMixin, Clickhous("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)+ c.tool_name+ for c in api.list_mcp_tool_calls(+ self.team, session_id=sid, limit=500, offset=0, date_from=df+ ).results],["ancient_tool"],),diff --git a/products/mcp_analytics/backend/tests/test_presentation.py b/products/mcp_analytics/backend/tests/test_presentation.pyindex b4069c6811db..f7adfcca56c6 100644--- a/products/mcp_analytics/backend/tests/test_presentation.py+++ b/products/mcp_analytics/backend/tests/test_presentation.py@@ -18,7 +18,10 @@ from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntfrom products.mcp_analytics.backend.presentation.serializers import (MCP_SESSION_LIST_DEFAULT_LIMIT,MCP_SESSION_LIST_MAX_LIMIT,+ MCP_TOOL_CALLS_DEFAULT_LIMIT,+ MCP_TOOL_CALLS_MAX_LIMIT,MCPSessionListQuerySerializer,+ MCPSessionToolCallsQuerySerializer,)from products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin@@ -436,6 +439,47 @@ class TestMCPSessionListQuerySerializer(SimpleTestCase):assert error_field in serializer.errors+class TestMCPSessionToolCallsQuerySerializer(SimpleTestCase):+ def test_defaults_when_pagination_params_omitted(self) -> None:+ serializer = MCPSessionToolCallsQuerySerializer(data={})+ assert serializer.is_valid(), serializer.errors+ assert serializer.validated_data["limit"] == MCP_TOOL_CALLS_DEFAULT_LIMIT+ assert serializer.validated_data["offset"] == 0++ @parameterized.expand(+ [+ ("limit_at_cap", {"limit": MCP_TOOL_CALLS_MAX_LIMIT}, True, None),+ ("limit_over_cap", {"limit": MCP_TOOL_CALLS_MAX_LIMIT + 1}, False, "limit"),+ ("limit_below_min", {"limit": 0}, False, "limit"),+ ("offset_at_min", {"offset": 0}, True, None),+ ("offset_negative", {"offset": -1}, False, "offset"),+ ]+ )+ def test_pagination_bounds(+ self, _name: str, data: dict[str, int], expected_valid: bool, error_field: str | None+ ) -> None:+ serializer = MCPSessionToolCallsQuerySerializer(data=data)+ assert serializer.is_valid() is expected_valid, serializer.errors+ if error_field is not None:+ assert error_field in serializer.errors++ @parameterized.expand(+ [+ ("valid_iso", "2026-01-02T03:04:05Z", True),+ ("unparseable", "not-a-date", None),+ ]+ )+ def test_date_from_is_lenient(self, _name: str, raw: str, expect_datetime: bool | None) -> None:+ # date_from is a scan-pruning hint: a bad value must fall back to None, not 400 the request.+ serializer = MCPSessionToolCallsQuerySerializer(data={"date_from": raw})+ assert serializer.is_valid(), serializer.errors+ resolved = serializer.validated_data["date_from"]+ if expect_datetime:+ assert isinstance(resolved, datetime)+ else:+ assert resolved is None++class TestMCPAnalyticsCrossTeamIsolation(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):"""Team A must never reach Team B's submissions. Now that the submission endpoints arereachable by anyone inside the mcp-analytics flag (no longer staff-only), pin the tenantdiff --git a/products/mcp_analytics/frontend/generated/api.schemas.ts b/products/mcp_analytics/frontend/generated/api.schemas.tsindex 5cbea3fdfd65..950cb8d8b90f 100644--- a/products/mcp_analytics/frontend/generated/api.schemas.ts+++ b/products/mcp_analytics/frontend/generated/api.schemas.ts@@ -433,15 +433,18 @@ export type McpAnalyticsSessionsGenerateIntentParams = {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.+ * 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 or unparseable.*/date_from?: string/**- * Number of results to return per page.+ * Maximum tool calls to return per page (1–500). Defaults to 500 — the whole page — so a session's calls come back in one request; pass a smaller value for a lighter response. Values above the cap are rejected.+ * @minimum 1+ * @maximum 500*/limit?: number/**- * The initial index from which to return the results.+ * Number of tool calls to skip before returning results. Combine with limit to page through a session's calls; the response's has_next flag indicates whether more remain.+ * @minimum 0*/offset?: number}diff --git a/products/mcp_analytics/frontend/generated/api.ts b/products/mcp_analytics/frontend/generated/api.tsindex 3c81d4750de9..7aef539a5424 100644--- a/products/mcp_analytics/frontend/generated/api.ts+++ b/products/mcp_analytics/frontend/generated/api.ts@@ -250,7 +250,7 @@ export const getMcpAnalyticsSessionsToolCallsUrl = (}/**- * List all $mcp_tool_call events that belong to a given $session_id, in chronological order.+ * List a page of the $mcp_tool_call events that belong to a given $session_id, in chronological order.*/export const mcpAnalyticsSessionsToolCalls = async (projectId: string,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ed8384dfdb02..9e0dc26d87e8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -58698,15 +58698,18 @@ export namespace Schemas {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.+ * 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 or unparseable.*/date_from?: string;/**- * Number of results to return per page.+ * Maximum tool calls to return per page (1–500). Defaults to 500 — the whole page — so a session's calls come back in one request; pass a smaller value for a lighter response. Values above the cap are rejected.+ * @minimum 1+ * @maximum 500*/limit?: number;/**- * The initial index from which to return the results.+ * Number of tool calls to skip before returning results. Combine with limit to page through a session's calls; the response's has_next flag indicates whether more remain.+ * @minimum 0*/offset?: number;};@@ -65428,15 +65431,18 @@ export namespace Schemas {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.+ * 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 or unparseable.*/date_from?: string;/**- * Number of results to return per page.+ * Maximum tool calls to return per page (1–500). Defaults to 500 — the whole page — so a session's calls come back in one request; pass a smaller value for a lighter response. Values above the cap are rejected.+ * @minimum 1+ * @maximum 500*/limit?: number;/**- * The initial index from which to return the results.+ * Number of tool calls to skip before returning results. Combine with limit to page through a session's calls; the response's has_next flag indicates whether more remain.+ * @minimum 0*/offset?: number;};