: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): enforce sessions-list pagination bounds (#67350)
Georgis Andonis03372dd69f49
diff --git a/products/mcp_analytics/backend/presentation/serializers.py b/products/mcp_analytics/backend/presentation/serializers.pyindex da76aba9a643..ba981b55a06c 100644--- a/products/mcp_analytics/backend/presentation/serializers.py+++ b/products/mcp_analytics/backend/presentation/serializers.py@@ -5,6 +5,12 @@ from products.mcp_analytics.backend.models import MCPAnalyticsSubmissionMAX_GOAL_LENGTH = 500MAX_SUMMARY_LENGTH = 5_000+# Single source of truth for session-list pagination bounds. Referenced by the query serializer+# (which enforces + advertises them in the OpenAPI spec, so the MCP Zod schema inherits the same+# limits) and by MCPSessionPagination for its response envelope.+MCP_SESSION_LIST_DEFAULT_LIMIT = 100+MCP_SESSION_LIST_MAX_LIMIT = 500+class MCPAnalyticsSubmissionSerializer(serializers.Serializer):id = serializers.UUIDField(read_only=True, help_text="Unique identifier for this submission.")@@ -139,6 +145,57 @@ class MCPToolCallSerializer(serializers.Serializer):)+class MCPSessionListQuerySerializer(serializers.Serializer):+ search = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ help_text="Case-insensitive substring filter matched against session_id, distinct_id, mcp_client_name, and tools_used.",+ )+ order_by = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ help_text=(+ "Sort column. Allowed: session_id, session_start, session_end, duration_seconds, "+ "tool_call_count, mcp_client_name, distinct_id. Prefix with '-' for descending. "+ "Defaults to '-session_start' (newest sessions first)."+ ),+ )+ date_from = serializers.CharField(+ required=False,+ allow_blank=True,+ help_text=(+ "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_to = serializers.CharField(+ required=False,+ allow_blank=True,+ help_text="End of the window. PostHog date string or absolute ISO timestamp. Defaults to now.",+ )+ limit = serializers.IntegerField(+ required=False,+ default=MCP_SESSION_LIST_DEFAULT_LIMIT,+ min_value=1,+ max_value=MCP_SESSION_LIST_MAX_LIMIT,+ help_text=(+ f"Maximum number of sessions to return per page. Defaults to {MCP_SESSION_LIST_DEFAULT_LIMIT}; "+ f"values above {MCP_SESSION_LIST_MAX_LIMIT} are rejected."+ ),+ )+ offset = serializers.IntegerField(+ required=False,+ default=0,+ min_value=0,+ help_text=(+ "Number of sessions to skip before returning results. Combine with limit to page through "+ "sessions; 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 5f943e7b57eb..7c7c0242495a 100644--- a/products/mcp_analytics/backend/presentation/views.py+++ b/products/mcp_analytics/backend/presentation/views.py@@ -23,11 +23,14 @@ from products.mcp_analytics.backend.facade import api, contracts, enumsfrom products.mcp_analytics.backend.models import MCPAnalyticsSubmissionfrom .serializers import (+ MCP_SESSION_LIST_DEFAULT_LIMIT,+ MCP_SESSION_LIST_MAX_LIMIT,MCPAnalyticsSubmissionSerializer,MCPFeedbackCreateSerializer,MCPIntentClusterSnapshotSerializer,MCPMissingCapabilityCreateSerializer,MCPSessionIntentSerializer,+ MCPSessionListQuerySerializer,MCPSessionSerializer,MCPToolCallSerializer,)@@ -53,8 +56,8 @@ class MCPSessionPagination(LimitOffsetPagination):logic layer over-fetching one row rather than a count query."""- default_limit = 100- max_limit = 500+ default_limit = MCP_SESSION_LIST_DEFAULT_LIMIT+ max_limit = MCP_SESSION_LIST_MAX_LIMITdef get_paginated_response(self, data: Any, *, has_next: bool = False) -> Response:return Response({"results": data, "has_next": has_next})@@ -168,69 +171,27 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# (a plain manager) so .none() can't trip a team-scoped manager's guard.return MCPAnalyticsSubmission.objects.none()- @extend_schema(+ @validated_request(+ query_serializer=MCPSessionListQuerySerializer,+ responses={200: OpenApiResponse(response=MCPSessionSerializer(many=True))},operation_id="mcp_analytics_sessions_list",description="List MCP sessions for the current project, derived by grouping $mcp_tool_call events by $mcp_session_id. Ordered by newest session start first by default.",- parameters=[- OpenApiParameter(- name="search",- type=OpenApiTypes.STR,- location=OpenApiParameter.QUERY,- required=False,- description="Case-insensitive substring filter matched against session_id, distinct_id, mcp_client_name, and tools_used.",- ),- OpenApiParameter(- name="order_by",- type=OpenApiTypes.STR,- location=OpenApiParameter.QUERY,- required=False,- description=(- "Sort column. Allowed: session_id, session_start, session_end, "- "duration_seconds, tool_call_count, mcp_client_name, distinct_id. "- "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)},)- def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:- # Instantiate the concrete class (not self.pagination_class()) so the typed- # get_paginated_response(has_next=...) is visible to the type checker.- paginator = MCPSessionPagination()- limit = paginator.get_limit(request) or paginator.default_limit- offset = paginator.get_offset(request)- search = request.query_params.get("search", "")- order_by = request.query_params.get("order_by", "")- date_from = request.query_params.get("date_from") or None- date_to = request.query_params.get("date_to") or None+ def list(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:+ params = request.validated_query_datapage = api.list_mcp_sessions(self.team,- limit=limit,- offset=offset,- search=search,- order_by=order_by,- date_from=date_from,- date_to=date_to,+ limit=params["limit"],+ offset=params["offset"],+ search=params["search"],+ order_by=params["order_by"],+ date_from=params.get("date_from") or None,+ date_to=params.get("date_to") or None,)serializer = self.get_serializer(page.results, many=True)- return paginator.get_paginated_response(serializer.data, has_next=page.has_next)+ # Instantiate the concrete class (not self.pagination_class()) so the typed+ # 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(operation_id="mcp_analytics_sessions_tool_calls",diff --git a/products/mcp_analytics/backend/tests/test_presentation.py b/products/mcp_analytics/backend/tests/test_presentation.pyindex 5661b6991cf3..45f11433a5ef 100644--- a/products/mcp_analytics/backend/tests/test_presentation.py+++ b/products/mcp_analytics/backend/tests/test_presentation.py@@ -4,6 +4,7 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_eventfrom unittest.mock import patchfrom django.core.cache import cache+from django.test import SimpleTestCasefrom parameterized import parameterizedfrom rest_framework import status@@ -13,6 +14,11 @@ from posthog.models.utils import uuid7from products.mcp_analytics.backend import intent_generationfrom products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot, MCPSession+from products.mcp_analytics.backend.presentation.serializers import (+ MCP_SESSION_LIST_DEFAULT_LIMIT,+ MCP_SESSION_LIST_MAX_LIMIT,+ MCPSessionListQuerySerializer,+)from products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin@@ -376,6 +382,31 @@ class TestMCPSessionToolCallsEndpoint(_MCPAnalyticsTeamScopedTestMixin, Clickhouassert [c["tool_name"] for c in response.json()["results"]] == ["first_tool", "last_tool"]+class TestMCPSessionListQuerySerializer(SimpleTestCase):+ def test_defaults_when_pagination_params_omitted(self) -> None:+ serializer = MCPSessionListQuerySerializer(data={})+ assert serializer.is_valid(), serializer.errors+ assert serializer.validated_data["limit"] == MCP_SESSION_LIST_DEFAULT_LIMIT+ assert serializer.validated_data["offset"] == 0++ @parameterized.expand(+ [+ ("limit_at_cap", {"limit": MCP_SESSION_LIST_MAX_LIMIT}, True, None),+ ("limit_over_cap", {"limit": MCP_SESSION_LIST_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 = MCPSessionListQuerySerializer(data=data)+ assert serializer.is_valid() is expected_valid, serializer.errors+ if error_field is not None:+ assert error_field in serializer.errors++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 48335258234f..5cbea3fdfd65 100644--- a/products/mcp_analytics/frontend/generated/api.schemas.ts+++ b/products/mcp_analytics/frontend/generated/api.schemas.ts@@ -404,11 +404,14 @@ export type McpAnalyticsSessionsListParams = {*/date_to?: string/**- * Number of results to return per page.+ * Maximum number of sessions to return per page. Defaults to 100; values above 500 are rejected.+ * @minimum 1+ * @maximum 500*/limit?: number/**- * The initial index from which to return the results.+ * Number of sessions to skip before returning results. Combine with limit to page through sessions; the response's has_next flag indicates whether more remain.+ * @minimum 0*/offset?: number/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a5f53b782fe3..3f5fc98821b8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -58102,11 +58102,14 @@ export namespace Schemas {*/date_to?: string;/**- * Number of results to return per page.+ * Maximum number of sessions to return per page. Defaults to 100; values above 500 are rejected.+ * @minimum 1+ * @maximum 500*/limit?: number;/**- * The initial index from which to return the results.+ * Number of sessions to skip before returning results. Combine with limit to page through sessions; the response's has_next flag indicates whether more remain.+ * @minimum 0*/offset?: number;/**@@ -64737,11 +64740,14 @@ export namespace Schemas {*/date_to?: string;/**- * Number of results to return per page.+ * Maximum number of sessions to return per page. Defaults to 100; values above 500 are rejected.+ * @minimum 1+ * @maximum 500*/limit?: number;/**- * The initial index from which to return the results.+ * Number of sessions to skip before returning results. Combine with limit to page through sessions; the response's has_next flag indicates whether more remain.+ * @minimum 0*/offset?: number;/**