: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
fix(actions): honor limit/offset and add name search on actions list (#62071)
Sam Penningtone3ec7ace787f
diff --git a/products/actions/backend/api/action.py b/products/actions/backend/api/action.pyindex e93a7242e5ce..c6336f0f3cf7 100644--- a/products/actions/backend/api/action.py+++ b/products/actions/backend/api/action.py@@ -6,7 +6,8 @@ from typing import Any, castfrom django.db import connectionfrom django.db.models import Count-from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema, extend_schema_field+from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, PolymorphicProxySerializer, extend_schema, extend_schema_fieldfrom rest_framework import request, serializers, viewsetsfrom rest_framework.decorators import action as drf_actionfrom rest_framework.renderers import BaseRenderer@@ -559,10 +560,51 @@ class ActionViewSet(refs = find_action_references(action_obj.id, action_obj.team)return Response(ActionReferenceSerializer(refs, many=True).data)+ @staticmethod+ def _parse_non_negative_int(raw: str | None) -> int | None:+ if raw is None:+ return None+ try:+ value = int(raw)+ except (TypeError, ValueError):+ return None+ return value if value >= 0 else None++ @extend_schema(+ parameters=[+ OpenApiParameter(+ "limit", OpenApiTypes.INT, description="Maximum number of actions to return. Omit to return all."+ ),+ OpenApiParameter(+ "offset", OpenApiTypes.INT, description="Number of actions to skip before returning results."+ ),+ OpenApiParameter(+ "search", OpenApiTypes.STR, description="Case-insensitive substring match on the action name."+ ),+ ]+ )def list(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:# :HACKY: we need to override this viewset method until actions support- # better pagination in the taxonomic filter and on the actions page+ # better pagination in the taxonomic filter and on the actions page.+ #+ # `limit`/`offset`/`search` are opt-in: with no params we still return the+ # full, ordered list so the actions page and taxonomic filter keep working+ # unchanged. API/MCP consumers can pass them to avoid pulling every action+ # at once (a project can have thousands), which otherwise overflows the+ # context window of LLM clients calling the `actions-get-all` MCP tool.actions = self.filter_queryset(self.get_queryset())++ search = request.query_params.get("search")+ if search:+ actions = actions.filter(name__icontains=search)++ offset = self._parse_non_negative_int(request.query_params.get("offset")) or 0+ limit = self._parse_non_negative_int(request.query_params.get("limit"))+ if limit is not None:+ actions = actions[offset : offset + limit]+ elif offset:+ actions = actions[offset:]+actions_list: list[dict[Any, Any]] = self.serializer_class(actions, many=True, context={"request": request, "view": self}).data # type: ignorediff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/api/test/test_action.pyindex b8420ee68704..9a087d19572f 100644--- a/products/actions/backend/api/test/test_action.py+++ b/products/actions/backend/api/test/test_action.py@@ -1,3 +1,5 @@+from datetime import UTC, datetime, timedelta+from freezegun import freeze_timefrom posthog.test.base import (APIBaseTest,@@ -8,6 +10,7 @@ from posthog.test.base import ()from unittest.mock import ANY, patch+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.models import Cohort, Tag, User@@ -342,6 +345,30 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):with self.assertNumQueries(10), snapshot_postgres_queries_context(self):self.client.get(f"/api/projects/{self.team.id}/actions/")+ @parameterized.expand(+ [+ # No params returns every action (the unchanged default the actions page relies on).+ ("no_params", "", ["alpha", "beta", "gamma", "delta"]),+ ("limit", "?limit=2", ["alpha", "beta"]),+ # offset pages past earlier results without overlapping the first page.+ ("limit_and_offset", "?limit=2&offset=2", ["gamma", "delta"]),+ # search filters by case-insensitive name substring.+ ("search", "?search=ALph", ["alpha"]),+ ]+ )+ def test_listing_actions_supports_limit_offset_and_search(+ self, _name: str, params: str, expected_names: list[str]+ ) -> None:+ # Results are ordered by -last_calculated_at, so pin it (descending with creation+ # order) to make the display order match the alphabetical names deterministically.+ base = datetime(2021, 1, 1, tzinfo=UTC)+ for index, name in enumerate(["alpha", "beta", "gamma", "delta"]):+ Action.objects.create(team=self.team, name=name, last_calculated_at=base - timedelta(minutes=index))++ response = self.client.get(f"/api/projects/{self.team.id}/actions/{params}")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([action["name"] for action in response.json()["results"]], expected_names)+def test_get_tags_returns_list(self):action = Action.objects.create(team=self.team, name="bla")tag = Tag.objects.create(name="random", team_id=self.team.id)diff --git a/products/actions/frontend/generated/api.schemas.ts b/products/actions/frontend/generated/api.schemas.tsindex 0e3e76042636..c9c1eac1078d 100644--- a/products/actions/frontend/generated/api.schemas.ts+++ b/products/actions/frontend/generated/api.schemas.ts@@ -682,13 +682,17 @@ export interface BulkUpdateTagsResponseApi {export type ActionsListParams = {format?: ActionsListFormat/**- * Number of results to return per page.+ * Maximum number of actions to return. Omit to return all.*/limit?: number/**- * The initial index from which to return the results.+ * Number of actions to skip before returning results.*/offset?: number+ /**+ * Case-insensitive substring match on the action name.+ */+ search?: string}export type ActionsListFormat = (typeof ActionsListFormat)[keyof typeof ActionsListFormat]diff --git a/products/actions/mcp/tools.yaml b/products/actions/mcp/tools.yamlindex 9d5d304ce6f1..71564bef00f8 100644--- a/products/actions/mcp/tools.yaml+++ b/products/actions/mcp/tools.yaml@@ -109,10 +109,11 @@ tools:list: truetitle: Get all actionsdescription: >- Get all actions in the project. Actions are reusable event definitions that can combine multiple trigger+ Get actions in the project. Actions are reusable event definitions that can combine multiple triggerconditions (page views, clicks, form submissions) into a single trackable event for use in insights and- funnels. Supports pagination with limit and offset parameters. Note: Search/filtering by name is not- supported on this endpoint.+ funnels. Supports pagination with `limit` and `offset`, and case-insensitive name filtering with `search`.+ Projects can have thousands of actions, so pass `limit` (and `search` when looking for a specific action by+ name) rather than fetching every action at once.ui_app: action-listactions-references-list:operation: actions_references_listdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex b2acc6a909b0..b0079730bc89 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -191,7 +191,7 @@}},"actions-get-all": {- "description": "Get all actions in the project. Actions are reusable event definitions that can combine multiple trigger conditions (page views, clicks, form submissions) into a single trackable event for use in insights and funnels. Supports pagination with limit and offset parameters. Note: Search/filtering by name is not supported on this endpoint.",+ "description": "Get actions in the project. Actions are reusable event definitions that can combine multiple trigger conditions (page views, clicks, form submissions) into a single trackable event for use in insights and funnels. Supports pagination with `limit` and `offset`, and case-insensitive name filtering with `search`. Projects can have thousands of actions, so pass `limit` (and `search` when looking for a specific action by name) rather than fetching every action at once.","category": "Actions","feature": "actions","summary": "Get all actions",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex d1951b1085b2..4fa787854a77 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -191,7 +191,7 @@}},"actions-get-all": {- "description": "Get all actions in the project. Actions are reusable event definitions that can combine multiple trigger conditions (page views, clicks, form submissions) into a single trackable event for use in insights and funnels. Supports pagination with limit and offset parameters. Note: Search/filtering by name is not supported on this endpoint.",+ "description": "Get actions in the project. Actions are reusable event definitions that can combine multiple trigger conditions (page views, clicks, form submissions) into a single trackable event for use in insights and funnels. Supports pagination with `limit` and `offset`, and case-insensitive name filtering with `search`. Projects can have thousands of actions, so pass `limit` (and `search` when looking for a specific action by name) rather than fetching every action at once.","category": "Actions","feature": "actions","summary": "Get all actions",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ec89c05290aa..848876c7ffc6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -46372,13 +46372,17 @@ export namespace Schemas {export type ActionsListParams = {format?: ActionsListFormat;/**- * Number of results to return per page.+ * Maximum number of actions to return. Omit to return all.*/limit?: number;/**- * The initial index from which to return the results.+ * Number of actions to skip before returning results.*/offset?: number;+ /**+ * Case-insensitive substring match on the action name.+ */+ search?: string;};export type ActionsListFormat = typeof ActionsListFormat[keyof typeof ActionsListFormat];diff --git a/services/mcp/src/generated/actions/api.ts b/services/mcp/src/generated/actions/api.tsindex 571d063c60ef..5ae51e46c340 100644--- a/services/mcp/src/generated/actions/api.ts+++ b/services/mcp/src/generated/actions/api.ts@@ -18,8 +18,9 @@ export const ActionsListParams = /* @__PURE__ */ zod.object({export const ActionsListQueryParams = /* @__PURE__ */ zod.object({format: zod.enum(['csv', 'json']).optional(),- limit: zod.number().optional().describe('Number of results to return per page.'),- offset: zod.number().optional().describe('The initial index from which to return the results.'),+ limit: zod.number().optional().describe('Maximum number of actions to return. Omit to return all.'),+ offset: zod.number().optional().describe('Number of actions to skip before returning results.'),+ search: zod.string().optional().describe('Case-insensitive substring match on the action name.'),})export const ActionsCreateParams = /* @__PURE__ */ zod.object({diff --git a/services/mcp/src/tools/generated/actions.ts b/services/mcp/src/tools/generated/actions.tsindex 52081b3bba73..7f567ac82eca 100644--- a/services/mcp/src/tools/generated/actions.ts+++ b/services/mcp/src/tools/generated/actions.ts@@ -145,6 +145,7 @@ const actionsGetAll = (): ToolBase<typeof ActionsGetAllSchema, WithPostHogUrl<Scquery: {limit: params.limit,offset: params.offset,+ search: params.search,},})return await withPostHogUrl(diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/actions-get-all.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/actions-get-all.jsonindex 8331b796ac73..cd0e9e22a7fa 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/actions-get-all.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/actions-get-all.json@@ -2,12 +2,16 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"limit": {- "description": "Number of results to return per page.",+ "description": "Maximum number of actions to return. Omit to return all.","type": "number"},"offset": {- "description": "The initial index from which to return the results.",+ "description": "Number of actions to skip before returning results.","type": "number"+ },+ "search": {+ "description": "Case-insensitive substring match on the action name.",+ "type": "string"}},"type": "object"