: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(activity-logs): make the list API pollable and add an OCSF format (#78172)
Yasenf12a76f55773
diff --git a/posthog/api/advanced_activity_logs/ocsf.py b/posthog/api/advanced_activity_logs/ocsf.pynew file mode 100644index 000000000000..18122710751c--- /dev/null+++ b/posthog/api/advanced_activity_logs/ocsf.py@@ -0,0 +1,145 @@+"""OCSF 1.5.0 representation of activity log entries, for ingestion into a SIEM.++Values of changed fields are omitted unless the caller opts in: `detail` is a free-form diff, so+any activity type can carry the content of the changed object (notebook rejections embed whole+documents, group property writes embedded property values). Which fields changed is enough to+answer who did what and when, which is what an audit trail is for.+"""++from typing import Any++from rest_framework import serializers++from posthog.models.activity_logging.activity_log import ActivityLog++OCSF_VERSION = "1.5.0"++CLASS_UID_ACCOUNT_CHANGE = 3001+CLASS_UID_AUTHENTICATION = 3002+CLASS_UID_ENTITY_MANAGEMENT = 3004++CATEGORY_UID_IAM = 3++ACTIVITY_ID_OTHER = 99+STATUS_ID_SUCCESS = 1+STATUS_ID_FAILURE = 2++# `activity` is an unconstrained CharField with no enum and ~57 distinct values in production, so+# only the ones carrying real volume are mapped. Everything else falls through to activity_id 99+# plus activity_name, which is OCSF's documented mechanism for an unmapped source activity.+_AUTHENTICATION_ACTIVITIES = {+ "logged_in": 1,+ "logged_out": 2,+ "share_login_success": 1,+ "share_login_failed": 1,+}++_ACCOUNT_CHANGE_ACTIVITIES = {+ "scim_provisioned": 1,+ "scim_updated": 3,+ "scim_replaced": 3,+ "scim_deprovisioned": 4,+}++_ENTITY_MANAGEMENT_ACTIVITIES = {+ "created": 1,+ "create_property": 1,+ "updated": 3,+ "changed": 3,+ "config_updated": 3,+ "update_property": 3,+ "upsert_properties": 3,+ "deleted": 4,+ "bulk_deleted": 4,+ "delete_property": 4,+ "enabled": 8,+ "materialization_enabled": 8,+ "disabled": 9,+ "materialization_disabled": 9,+}++# Rejected writes, failed exports, and failed share logins are attempts, not completed changes.+_FAILURE_ACTIVITIES = {"share_login_failed", "save_rejected_conflict", "save_rejected_stale", "export_fail"}+++def _classify(activity: str) -> tuple[int, int]:+ if activity in _AUTHENTICATION_ACTIVITIES:+ return CLASS_UID_AUTHENTICATION, _AUTHENTICATION_ACTIVITIES[activity]+ if activity in _ACCOUNT_CHANGE_ACTIVITIES:+ return CLASS_UID_ACCOUNT_CHANGE, _ACCOUNT_CHANGE_ACTIVITIES[activity]+ return CLASS_UID_ENTITY_MANAGEMENT, _ENTITY_MANAGEMENT_ACTIVITIES.get(activity, ACTIVITY_ID_OTHER)+++def _changes(instance: ActivityLog) -> list[dict[str, Any]]:+ detail = instance.detail or {}+ return [change for change in (detail.get("changes") or []) if isinstance(change, dict)]+++class ActivityLogOCSFSerializer(serializers.ModelSerializer):+ class Meta:+ model = ActivityLog+ fields: list[str] = []++ def to_representation(self, instance: ActivityLog) -> dict[str, Any]:+ class_uid, activity_id = _classify(instance.activity)+ detail = instance.detail or {}+ changes = _changes(instance)+ changed_fields = [change["field"] for change in changes if change.get("field")]++ event: dict[str, Any] = {+ "metadata": {+ "version": OCSF_VERSION,+ "product": {"name": "PostHog", "vendor_name": "PostHog"},+ "uid": str(instance.id),+ },+ # OCSF `time` is timestamp_t: epoch milliseconds as an integer. The RFC-3339 string is a+ # separate datetime_t attribute, so both are emitted rather than one in the other's place.+ "time": int(instance.created_at.timestamp() * 1000),+ "time_dt": instance.created_at.isoformat(),+ "class_uid": class_uid,+ "category_uid": CATEGORY_UID_IAM,+ "type_uid": class_uid * 100 + activity_id,+ "activity_id": activity_id,+ "status_id": STATUS_ID_FAILURE if instance.activity in _FAILURE_ACTIVITIES else STATUS_ID_SUCCESS,+ "entity": {+ "type": instance.scope,+ "uid": instance.item_id,+ "name": detail.get("name"),+ },+ "unmapped": {+ "activity": instance.activity,+ "changed_fields": changed_fields,+ "team_id": instance.team_id,+ "organization_id": str(instance.organization_id) if instance.organization_id else None,+ "was_impersonated": instance.was_impersonated,+ "is_system": instance.is_system,+ "client": instance.client,+ },+ }++ if activity_id == ACTIVITY_ID_OTHER:+ event["activity_name"] = instance.activity++ if instance.user is not None:+ event["actor"] = {+ "user": {+ "uid": str(instance.user.uuid),+ "email_addr": instance.user.email,+ "name": instance.user.first_name,+ }+ }++ if instance.ip_address:+ event["src_endpoint"] = {"ip": instance.ip_address}++ if self.context.get("include_values") and changes:+ event["entity"]["data"] = {+ change["field"]: change.get("before") for change in changes if change.get("field")+ }+ event["entity_result"] = {+ "type": instance.scope,+ "uid": instance.item_id,+ "data": {change["field"]: change.get("after") for change in changes if change.get("field")},+ }++ return eventdiff --git a/posthog/api/advanced_activity_logs/test_ocsf.py b/posthog/api/advanced_activity_logs/test_ocsf.pynew file mode 100644index 000000000000..85f2b671e9dd--- /dev/null+++ b/posthog/api/advanced_activity_logs/test_ocsf.py@@ -0,0 +1,118 @@+from typing import Optional++from posthog.test.base import APIBaseTest++from parameterized import parameterized++from posthog.api.advanced_activity_logs.ocsf import ActivityLogOCSFSerializer+from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail+++class TestActivityLogOCSF(APIBaseTest):+ def _log(self, activity: str = "updated", detail: Optional[Detail] = None) -> ActivityLog:+ log = ActivityLog.objects.create(+ team_id=self.team.id,+ organization_id=self.organization.id,+ scope="FeatureFlag",+ activity=activity,+ item_id="flag-1",+ user=self.user,+ ip_address="203.0.113.4",+ detail=detail,+ )+ # Read it back so `detail` is the JSON dict the list endpoint serializes, not the dataclass+ # the freshly built instance holds.+ log.refresh_from_db()+ return log++ def _detail_with_values(self) -> Detail:+ return Detail(+ name="beta-checkout",+ changes=[Change(type="FeatureFlag", action="changed", field="filters", before={"a": 1}, after={"a": 2})],+ )++ @parameterized.expand(+ [+ ("created", 3004, 1, None),+ ("updated", 3004, 3, None),+ ("deleted", 3004, 4, None),+ ("logged_in", 3002, 1, None),+ ("scim_provisioned", 3001, 1, None),+ ("exported for opengraph image", 3004, 99, "exported for opengraph image"),+ ]+ )+ def test_activity_maps_to_class_and_activity_id(+ self, activity: str, class_uid: int, activity_id: int, activity_name: Optional[str]+ ):+ event = ActivityLogOCSFSerializer(self._log(activity=activity)).data++ assert event["class_uid"] == class_uid+ assert event["activity_id"] == activity_id+ if activity_name is None:+ assert "activity_name" not in event+ else:+ assert event["activity_name"] == activity_name++ def test_values_are_excluded_by_default_but_field_names_are_kept(self):+ event = ActivityLogOCSFSerializer(self._log(detail=self._detail_with_values())).data++ assert event["unmapped"]["changed_fields"] == ["filters"]+ assert "data" not in event["entity"]+ assert "entity_result" not in event++ def test_include_values_maps_before_and_after_onto_entity_and_entity_result(self):+ event = ActivityLogOCSFSerializer(+ self._log(detail=self._detail_with_values()), context={"include_values": True}+ ).data++ assert event["entity"]["data"] == {"filters": {"a": 1}}+ assert event["entity_result"]["data"] == {"filters": {"a": 2}}++ def test_time_is_epoch_milliseconds_and_time_dt_is_rfc3339(self):+ log = self._log()++ event = ActivityLogOCSFSerializer(log).data++ assert isinstance(event["time"], int)+ assert event["time"] == int(log.created_at.timestamp() * 1000)+ assert event["time_dt"] == log.created_at.isoformat()++ def test_actor_entity_and_source_endpoint_are_mapped(self):+ event = ActivityLogOCSFSerializer(self._log(detail=self._detail_with_values())).data++ assert event["actor"]["user"]["email_addr"] == self.user.email+ assert event["src_endpoint"]["ip"] == "203.0.113.4"+ assert event["entity"] == {"type": "FeatureFlag", "uid": "flag-1", "name": "beta-checkout"}+ assert event["metadata"]["version"] == "1.5.0"+ assert event["category_uid"] == 3++ @parameterized.expand([("save_rejected_conflict", 2), ("share_login_failed", 2), ("updated", 1)])+ def test_rejected_writes_are_reported_as_failures(self, activity: str, status_id: int):+ assert ActivityLogOCSFSerializer(self._log(activity=activity)).data["status_id"] == status_id++ def test_endpoint_returns_ocsf_when_requested(self):+ self._log()++ response = self.client.get(f"/api/projects/{self.team.id}/advanced_activity_logs/?schema=ocsf")++ assert response.status_code == 200, response.json()+ assert response.json()["results"][0]["class_uid"] == 3004++ def test_endpoint_include_values_is_opt_in(self):+ self._log(detail=self._detail_with_values())+ base = f"/api/projects/{self.team.id}/advanced_activity_logs/?schema=ocsf"++ without = self.client.get(base).json()["results"][0]+ assert "entity_result" not in without++ with_values = self.client.get(f"{base}&include_values=true").json()["results"][0]+ assert with_values["entity_result"]["data"] == {"filters": {"a": 2}}++ def test_endpoint_default_shape_is_unchanged(self):+ self._log()++ response = self.client.get(f"/api/projects/{self.team.id}/advanced_activity_logs/")++ row = response.json()["results"][0]+ assert row["activity"] == "updated"+ assert "class_uid" not in rowdiff --git a/posthog/api/advanced_activity_logs/test_pagination_ordering.py b/posthog/api/advanced_activity_logs/test_pagination_ordering.pynew file mode 100644index 000000000000..9f4efcff5194--- /dev/null+++ b/posthog/api/advanced_activity_logs/test_pagination_ordering.py@@ -0,0 +1,135 @@+from datetime import timedelta++from freezegun import freeze_time+from posthog.test.base import APIBaseTest++from django.utils import timezone++from parameterized import parameterized+from rest_framework.request import Request+from rest_framework.test import APIRequestFactory++from posthog.api.advanced_activity_logs.viewset import activity_log_ordering+from posthog.models.activity_logging.activity_log import ActivityLog+++@freeze_time("2024-01-01T12:00:00Z")+class TestActivityLogCursorOrdering(APIBaseTest):+ def _create_logs(self, count: int, same_timestamp: bool = False) -> None:+ stamp = timezone.now()+ for index in range(count):+ ActivityLog.objects.create(+ team_id=self.team.id,+ organization_id=self.organization.id,+ scope="FeatureFlag",+ activity="updated",+ item_id=str(index),+ created_at=stamp if same_timestamp else stamp + timedelta(minutes=index),+ )++ def test_cursor_page_size_is_honored(self):+ self._create_logs(12)++ response = self.client.get(f"/api/projects/{self.team.id}/advanced_activity_logs/?page_size=5")++ assert response.status_code == 200, response.json()+ assert len(response.json()["results"]) == 5+ assert response.json()["next"] is not None++ def test_page_size_above_the_maximum_is_rejected(self):+ response = self.client.get(f"/api/projects/{self.team.id}/advanced_activity_logs/?page_size=99999")++ assert response.status_code == 400+ assert response.json()["attr"] == "page_size"++ def test_follow_keeps_the_cursor_usable_and_picks_up_new_entries(self):+ self._create_logs(3)+ base = f"/api/projects/{self.team.id}/advanced_activity_logs/?ordering=created_at&page_size=10&follow=true"++ exhausted = self.client.get(base).json()+ assert len(exhausted["results"]) == 3+ tail = exhausted["next"]+ assert tail is not None, "following stream must hand back a resumable cursor"++ # Re-polling the tail returns nothing but keeps a usable cursor, as a poller expects.+ idle = self.client.get(tail).json()+ assert idle["results"] == []+ assert idle["next"] is not None++ ActivityLog.objects.create(+ team_id=self.team.id,+ organization_id=self.organization.id,+ scope="FeatureFlag",+ activity="updated",+ item_id="brand-new",+ created_at=timezone.now() + timedelta(hours=1),+ )++ assert [row["item_id"] for row in self.client.get(tail).json()["results"]] == ["brand-new"]++ @parameterized.expand(+ [+ ("descending_default", ""),+ ("ascending_default", "&ordering=created_at"),+ ("descending_even_when_following", "&follow=true"),+ ]+ )+ def test_streams_that_should_terminate_end_with_a_null_next(self, _name: str, extra: str):+ self._create_logs(3)++ body = self.client.get(f"/api/projects/{self.team.id}/advanced_activity_logs/?page_size=10{extra}").json()++ assert len(body["results"]) == 3+ assert body["next"] is None++ def test_ordering_always_carries_a_unique_tiebreak(self):+ factory = APIRequestFactory()++ assert activity_log_ordering(Request(factory.get("/"))) == ("-created_at", "-id")+ assert activity_log_ordering(Request(factory.get("/?ordering=created_at"))) == ("created_at", "id")++ def test_ascending_ordering_is_opt_in_and_descending_is_the_default(self):+ self._create_logs(3)++ base = f"/api/projects/{self.team.id}/advanced_activity_logs/"++ ascending = self.client.get(f"{base}?ordering=created_at")+ assert ascending.status_code == 200, ascending.json()+ assert [row["item_id"] for row in ascending.json()["results"]] == ["0", "1", "2"]++ default = self.client.get(base)+ assert [row["item_id"] for row in default.json()["results"]] == ["2", "1", "0"]++ def test_unknown_ordering_value_is_rejected(self):+ response = self.client.get(f"/api/projects/{self.team.id}/advanced_activity_logs/?ordering=scope")++ assert response.status_code == 400+ assert response.json()["attr"] == "ordering"++ def test_ascending_cursor_walk_covers_every_row(self):+ self._create_logs(25, same_timestamp=True)++ seen: list[str] = []+ url = f"/api/projects/{self.team.id}/advanced_activity_logs/?ordering=created_at&page_size=10"+ while url:+ response = self.client.get(url)+ assert response.status_code == 200, response.json()+ body = response.json()+ seen.extend(row["item_id"] for row in body["results"])+ url = body["next"]++ assert sorted(seen) == sorted(str(index) for index in range(25))++ def test_tied_timestamps_paginate_without_loss_or_repeats(self):+ self._create_logs(25, same_timestamp=True)++ seen: list[str] = []+ url = f"/api/projects/{self.team.id}/advanced_activity_logs/?page_size=10"+ while url:+ response = self.client.get(url)+ assert response.status_code == 200, response.json()+ body = response.json()+ seen.extend(row["item_id"] for row in body["results"])+ url = body["next"]++ assert sorted(seen) == sorted(str(index) for index in range(25))diff --git a/posthog/api/advanced_activity_logs/test_pagination_schema.py b/posthog/api/advanced_activity_logs/test_pagination_schema.pynew file mode 100644index 000000000000..30803f3dc09c--- /dev/null+++ b/posthog/api/advanced_activity_logs/test_pagination_schema.py@@ -0,0 +1,24 @@+from django.test import SimpleTestCase++from rest_framework.request import Request+from rest_framework.test import APIRequestFactory++from posthog.api.advanced_activity_logs.viewset import ActivityLogPagination+++class TestActivityLogPaginationSchema(SimpleTestCase):+ def test_count_is_not_required_because_cursor_responses_omit_it(self):+ schema = ActivityLogPagination().get_paginated_response_schema({"type": "array"})++ assert "count" not in schema["required"]+ assert "results" in schema["required"]+ assert "count" in schema["properties"]++ def test_cursor_response_body_has_no_count(self):+ pagination = ActivityLogPagination()+ pagination.request = Request(APIRequestFactory().get("/"))+ pagination.cursor_pagination.page = []+ pagination.cursor_pagination.has_next = False+ pagination.cursor_pagination.has_previous = False++ assert "count" not in pagination.get_paginated_response([]).datadiff --git a/posthog/api/advanced_activity_logs/viewset.py b/posthog/api/advanced_activity_logs/viewset.pyindex fc973441e145..787e71acfda6 100644--- a/posthog/api/advanced_activity_logs/viewset.py+++ b/posthog/api/advanced_activity_logs/viewset.py@@ -11,7 +11,7 @@ from django.db.models import Q, QuerySetfrom drf_spectacular.utils import extend_schemafrom rest_framework import mixins, serializers, viewsetsfrom rest_framework.decorators import action-from rest_framework.pagination import BasePagination, CursorPagination, PageNumberPagination+from rest_framework.pagination import BasePagination, Cursor, CursorPagination, PageNumberPaginationfrom rest_framework.permissions import BasePermissionfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -36,8 +36,27 @@ from products.exports.backend.models.exported_asset import ExportedAssetfrom .field_discovery import AdvancedActivityLogFieldDiscoveryfrom .filters import AdvancedActivityLogFilterManager, validate_detail_filters+from .ocsf import ActivityLogOCSFSerializerfrom .utils import get_activity_log_lookback_restriction+ACTIVITY_LOG_ORDERING_DESCENDING = "-created_at"+ACTIVITY_LOG_ORDERING_ASCENDING = "created_at"+ACTIVITY_LOG_ORDERING_CHOICES = [ACTIVITY_LOG_ORDERING_DESCENDING, ACTIVITY_LOG_ORDERING_ASCENDING]++ACTIVITY_LOG_SCHEMA_OCSF = "ocsf"+++def activity_log_ordering(request: Request) -> tuple[str, str]:+ """Ordering tuple for the list endpoints, with `id` appended so ties break deterministically.++ Ascending exists so a polling client can persist a cursor and resume forward; descending can't+ advance because new rows always land at position 0. Values follow DRF's `OrderingFilter`+ grammar: a bare field name is ascending, a `-` prefix descending.+ """+ if request.query_params.get("ordering") == ACTIVITY_LOG_ORDERING_ASCENDING:+ return ("created_at", "id")+ return ("-created_at", "-id")+def restrict_loop_activity(queryset: QuerySet[ActivityLog], team_id: int, user) -> QuerySet[ActivityLog]:"""Keep personal loops' config out of the team-wide activity feed.@@ -123,21 +142,64 @@ class ActivityLogSerializer(serializers.ModelSerializer):return bookmark_date < obj.created_at.replace(microsecond=obj.created_at.microsecond // 1000 * 1000)+class TailFollowingCursorPagination(CursorPagination):+ """Cursor pagination that can keep a forward cursor alive after the stream is exhausted.++ Stock DRF returns `next: null` on the final page, which leaves a polling client nothing to+ resume from: a saved "last page" URL just replays that page, so the client has to fall back+ to a date filter plus deduplication. With `follow=true` the link stays valid, so a caller can+ store one cursor and re-poll it as new entries arrive - the pattern Okta's System Log API+ documents.++ Opt-in rather than implied by ascending order, because a live cursor changes the termination+ condition: a follower stops when `results` is empty, not when `next` is null. Leaving that on+ by default would make the obvious `while next: ...` loop run forever.++ Known gap: the cursor encodes `created_at` and filters strictly past it, so an entry written+ later but sharing the last-seen timestamp is not returned. That is inherent to a+ timestamp-positioned cursor and matches DRF's behavior mid-stream.+ """++ follow = False++ def get_next_link(self) -> Optional[str]:+ link = super().get_next_link()+ if link is not None or not self.follow:+ return link+ if self.ordering and str(self.ordering[0]).startswith("-"):+ # Descending walks into history and has a real end; there is no tail to follow.+ return None+ if not self.page:+ # Nothing new since the caller's position, so hand the same cursor back.+ return self.encode_cursor(self.cursor) if self.cursor else None+ position = self._get_position_from_instance(self.page[-1], self.ordering)+ # DRF's stub types Cursor.position as int, but at runtime it holds the string that+ # _get_position_from_instance returns.+ return self.encode_cursor(Cursor(offset=0, reverse=False, position=position)) # type: ignore[arg-type]++class ActivityLogPagination(BasePagination):def __init__(self):self.page_number_pagination = PageNumberPagination()- self.cursor_pagination = CursorPagination()+ self.cursor_pagination = TailFollowingCursorPagination()self.page_number_pagination.page_size = 100self.page_number_pagination.page_size_query_param = "page_size"self.page_number_pagination.max_page_size = 1000self.cursor_pagination.page_size = 100- self.cursor_pagination.ordering = "-created_at"+ self.cursor_pagination.page_size_query_param = "page_size"+ self.cursor_pagination.max_page_size = 1000+ # `created_at` is not unique, and DRF encodes only the first ordering field in the cursor,+ # resolving ties with an offset. That offset is reproducible only when rows sharing a+ # timestamp come back in a stable order, which Postgres does not otherwise guarantee.+ self.cursor_pagination.ordering = ("-created_at", "-id")def paginate_queryset(self, queryset, request, view=None):self.request = requestif request.query_params.get("page"):return self.page_number_pagination.paginate_queryset(queryset, request, view)else:+ self.cursor_pagination.ordering = activity_log_ordering(request)+ self.cursor_pagination.follow = request.query_params.get("follow") == "true"return self.cursor_pagination.paginate_queryset(queryset, request, view)def get_paginated_response(self, data):@@ -147,7 +209,13 @@ class ActivityLogPagination(BasePagination):return self.cursor_pagination.get_paginated_response(data)def get_paginated_response_schema(self, schema):- return self.page_number_pagination.get_paginated_response_schema(schema)+ # The paginator picks cursor or page-number mode per request, so the schema has to describe+ # both. Cursor responses (the default) carry no `count`, so it is documented as an optional+ # property rather than a required one.+ cursor_schema = self.cursor_pagination.get_paginated_response_schema(schema)+ page_number_schema = self.page_number_pagination.get_paginated_response_schema(schema)+ cursor_schema["properties"]["count"] = page_number_schema["properties"]["count"]+ return cursor_schemaclass ActivityLogScopeField(serializers.ChoiceField):@@ -174,6 +242,15 @@ class ActivityLogQueryParamsSerializer(serializers.Serializer):required=False,help_text="Filter by the ID of the affected resource.",)+ ordering = serializers.ChoiceField(+ choices=ACTIVITY_LOG_ORDERING_CHOICES,+ required=False,+ default=ACTIVITY_LOG_ORDERING_DESCENDING,+ help_text=(+ "Sort by when the entry was created. Defaults to newest first. Use created_at for oldest "+ "first when polling for new entries, so a saved cursor picks up where the last request stopped."+ ),+ )page = serializers.IntegerField(required=False,min_value=1,@@ -184,7 +261,7 @@ class ActivityLogQueryParamsSerializer(serializers.Serializer):min_value=1,max_value=1000,default=100,- help_text="Number of results per page (default: 100, max: 1000). Only used with page-based pagination.",+ help_text="Number of results per page (default: 100, max: 1000).",)@@ -227,7 +304,7 @@ class ActivityLogViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet, mixinsqueryset = queryset.filter(item_id=params.get("item_id"))if params.get("page"):- queryset = queryset.order_by("-created_at")+ queryset = queryset.order_by(*activity_log_ordering(self.request))lookback_date = get_activity_log_lookback_restriction(self.organization)if lookback_date:@@ -345,6 +422,41 @@ class AdvancedActivityLogFiltersSerializer(serializers.Serializer):default=[],help_text="Filter by the `item_id` of the affected resource(s).",)+ ordering = serializers.ChoiceField(+ choices=ACTIVITY_LOG_ORDERING_CHOICES,+ required=False,+ default=ACTIVITY_LOG_ORDERING_DESCENDING,+ help_text=(+ "Sort by when the entry was created. Defaults to newest first. Use created_at for oldest "+ "first when polling for new entries, so a saved cursor picks up where the last request stopped."+ ),+ )+ follow = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "Keep the next link valid after the last entry, so the same cursor can be re-polled as "+ "new entries arrive. Only applies with oldest-first ordering. When following, stop on an "+ "empty results list rather than on a null next link."+ ),+ )+ schema = serializers.ChoiceField(+ choices=[ACTIVITY_LOG_SCHEMA_OCSF],+ required=False,+ help_text=(+ "Response format. Set to ocsf to return Open Cybersecurity Schema Framework events for "+ "ingestion into a security tool. Omit for the default PostHog format."+ ),+ )+ include_values = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "Include the previous and new values of changed fields. Only applies when schema is ocsf. "+ "Values can contain the content of the changed object, which makes responses larger and "+ "sends that content to your security tool."+ ),+ )page = serializers.IntegerField(required=False,min_value=1,@@ -355,7 +467,7 @@ class AdvancedActivityLogFiltersSerializer(serializers.Serializer):min_value=1,max_value=1000,default=100,- help_text="Number of results per page (default: 100, max: 1000). Only used with page-based pagination.",+ help_text="Number of results per page (default: 100, max: 1000).",)def validate_detail_filters(self, value: Any) -> dict[str, Any]:@@ -486,20 +598,36 @@ class AdvancedActivityLogsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSequeryset = apply_activity_visibility_restrictions(queryset, self.request.user)queryset = restrict_loop_activity(queryset, self.team_id, self.request.user)- return queryset.order_by("-created_at")+ return queryset.order_by(*activity_log_ordering(self.request))++ def _validated_query_params(self) -> dict[str, Any]:+ # Validate once so serializer selection and context read the same coerced values the+ # filters serializer produces, instead of re-parsing the raw query string.+ validated = getattr(self, "_validated_query_params_cache", None)+ if validated is None:+ serializer = AdvancedActivityLogFiltersSerializer(data=self.request.query_params)+ serializer.is_valid(raise_exception=True)+ validated = self._validated_query_params_cache = serializer.validated_data+ return validateddef get_serializer_class(self):# This query param is set by the CSV exporter to indicate that the response should be serialized in a flat formatif self.request.query_params.get("is_csv_export") == "1":return ActivityLogFlatExportSerializer+ if self._validated_query_params().get("schema") == ACTIVITY_LOG_SCHEMA_OCSF:+ return ActivityLogOCSFSerializer+return super().get_serializer_class()+ def get_serializer_context(self):+ context = super().get_serializer_context()+ context["include_values"] = bool(self._validated_query_params().get("include_values"))+ return context+@extend_schema(parameters=[AdvancedActivityLogFiltersSerializer])def list(self, request, *args, **kwargs):- filters_serializer = AdvancedActivityLogFiltersSerializer(data=request.query_params)- filters_serializer.is_valid(raise_exception=True)- filters = filters_serializer.validated_data+ filters = self._validated_query_params()queryset = self.get_queryset()queryset = self.filter_manager.apply_filters(queryset, filters)@@ -634,7 +762,7 @@ class OrganizationAdvancedActivityLogsViewSet(AdvancedActivityLogsViewSet):# Org route: no single team_id (this endpoint is org-nested), so use the org-wide variant.queryset = restrict_loop_activity_for_org(queryset, self.organization.id, self.request.user)- return queryset.order_by("-created_at")+ return queryset.order_by(*activity_log_ordering(self.request))@action(detail=False, methods=["POST"])def export(self, request, **kwargs): # type: ignore[override]diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 2fcc77ae80f1..0a750fb452eb 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -574,12 +574,12 @@ export interface ActivityLogApi {}export interface PaginatedActivityLogListApi {- count: number/** @nullable */next?: string | null/** @nullable */previous?: string | nullresults: ActivityLogApi[]+ count?: number}/**@@ -951,13 +951,21 @@ export type ActivityLogListParams = {* @minLength 1*/item_id?: string+ /**+ * Sort by when the entry was created. Defaults to newest first. Use created_at for oldest first when polling for new entries, so a saved cursor picks up where the last request stopped.+ *+ * * `-created_at` - -created_at+ * * `created_at` - created_at+ * @minLength 1+ */+ ordering?: string/*** Page number for pagination. When provided, uses page-based pagination ordered by most recent first.* @minimum 1*/page?: number/**- * Number of results per page (default: 100, max: 1000). Only used with page-based pagination.+ * Number of results per page (default: 100, max: 1000).* @minimum 1* @maximum 1000*/@@ -1311,10 +1319,18 @@ export type AdvancedActivityLogsListParams = {* Upper bound on `created_at` (inclusive), ISO-8601.*/end_date?: string+ /**+ * Keep the next link valid after the last entry, so the same cursor can be re-polled as new entries arrive. Only applies with oldest-first ordering. When following, stop on an empty results list rather than on a null next link.+ */+ follow?: boolean/*** Reserved for future HogQL-based filtering.*/hogql_filter?: string+ /**+ * Include the previous and new values of changed fields. Only applies when schema is ocsf. Values can contain the content of the changed object, which makes responses larger and sends that content to your security tool.+ */+ include_values?: boolean/*** Filter by client IP addresses. Accepts exact IPv4/IPv6 values or wildcard patterns using `*` (e.g. `203.0.113.*`). Multiple entries are OR-combined.*/@@ -1328,17 +1344,32 @@ export type AdvancedActivityLogsListParams = {* Filter by the `item_id` of the affected resource(s).*/item_ids?: string[]+ /**+ * Sort by when the entry was created. Defaults to newest first. Use created_at for oldest first when polling for new entries, so a saved cursor picks up where the last request stopped.+ *+ * * `-created_at` - -created_at+ * * `created_at` - created_at+ * @minLength 1+ */+ ordering?: string/*** Page number for pagination. When provided, uses page-based pagination ordered by most recent first.* @minimum 1*/page?: number/**- * Number of results per page (default: 100, max: 1000). Only used with page-based pagination.+ * Number of results per page (default: 100, max: 1000).* @minimum 1* @maximum 1000*/page_size?: number+ /**+ * Response format. Set to ocsf to return Open Cybersecurity Schema Framework events for ingestion into a security tool. Omit for the default PostHog format.+ *+ * * `ocsf` - ocsf+ * @minLength 1+ */+ schema?: AdvancedActivityLogsListSchema/*** Filter by activity scopes (e.g. "FeatureFlag", "Insight").*/@@ -1366,6 +1397,13 @@ export type AdvancedActivityLogsListParams = {was_impersonated?: boolean | null}+export type AdvancedActivityLogsListSchema =+ (typeof AdvancedActivityLogsListSchema)[keyof typeof AdvancedActivityLogsListSchema]++export const AdvancedActivityLogsListSchema = {+ Ocsf: 'ocsf',+} as const+export type ApprovalPoliciesListParams = {/*** Number of results to return per page.diff --git a/products/platform_features/mcp/tools.yaml b/products/platform_features/mcp/tools.yamlindex a35e2991c552..83166f2bbef7 100644--- a/products/platform_features/mcp/tools.yaml+++ b/products/platform_features/mcp/tools.yaml@@ -48,6 +48,9 @@ tools:across the project. Responses can be large — pass `fields` to return only what your task needs (e.g.`["user.email", "activity", "scope", "created_at"]` to see who changed what), and only request`detail.changes` when you actually need the field-level diffs.+ exclude_params:+ - schema+ - include_valuesparam_overrides:page_size:default: 10diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6650fcb78925..3d3b98a7dbc1 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -45162,12 +45162,12 @@ export namespace Schemas {}export interface PaginatedActivityLogList {- count: number;/** @nullable */next?: string | null;/** @nullable */previous?: string | null;results: ActivityLog[];+ count?: number;}export interface PaginatedAlertList {@@ -77745,10 +77745,18 @@ export namespace Schemas {* Upper bound on `created_at` (inclusive), ISO-8601.*/end_date?: string;+ /**+ * Keep the next link valid after the last entry, so the same cursor can be re-polled as new entries arrive. Only applies with oldest-first ordering. When following, stop on an empty results list rather than on a null next link.+ */+ follow?: boolean;/*** Reserved for future HogQL-based filtering.*/hogql_filter?: string;+ /**+ * Include the previous and new values of changed fields. Only applies when schema is ocsf. Values can contain the content of the changed object, which makes responses larger and sends that content to your security tool.+ */+ include_values?: boolean;/*** Filter by client IP addresses. Accepts exact IPv4/IPv6 values or wildcard patterns using `*` (e.g. `203.0.113.*`). Multiple entries are OR-combined.*/@@ -77762,17 +77770,32 @@ export namespace Schemas {* Filter by the `item_id` of the affected resource(s).*/item_ids?: string[];+ /**+ * Sort by when the entry was created. Defaults to newest first. Use created_at for oldest first when polling for new entries, so a saved cursor picks up where the last request stopped.+ *+ * * `-created_at` - -created_at+ * * `created_at` - created_at+ * @minLength 1+ */+ ordering?: string;/*** Page number for pagination. When provided, uses page-based pagination ordered by most recent first.* @minimum 1*/page?: number;/**- * Number of results per page (default: 100, max: 1000). Only used with page-based pagination.+ * Number of results per page (default: 100, max: 1000).* @minimum 1* @maximum 1000*/page_size?: number;+ /**+ * Response format. Set to ocsf to return Open Cybersecurity Schema Framework events for ingestion into a security tool. Omit for the default PostHog format.+ *+ * * `ocsf` - ocsf+ * @minLength 1+ */+ schema?: OrgOrganizationsAdvancedActivityLogsListSchema;/*** Filter by activity scopes (e.g. "FeatureFlag", "Insight").*/@@ -77800,6 +77823,13 @@ export namespace Schemas {was_impersonated?: boolean | null;};+ export type OrgOrganizationsAdvancedActivityLogsListSchema = typeof OrgOrganizationsAdvancedActivityLogsListSchema[keyof typeof OrgOrganizationsAdvancedActivityLogsListSchema];+++ export const OrgOrganizationsAdvancedActivityLogsListSchema = {+ Ocsf: 'ocsf',+ } as const;+export type OrgOrganizationsBatchExportsListParams = {/*** Number of results to return per page.@@ -78282,13 +78312,21 @@ export namespace Schemas {* @minLength 1*/item_id?: string;+ /**+ * Sort by when the entry was created. Defaults to newest first. Use created_at for oldest first when polling for new entries, so a saved cursor picks up where the last request stopped.+ *+ * * `-created_at` - -created_at+ * * `created_at` - created_at+ * @minLength 1+ */+ ordering?: string;/*** Page number for pagination. When provided, uses page-based pagination ordered by most recent first.* @minimum 1*/page?: number;/**- * Number of results per page (default: 100, max: 1000). Only used with page-based pagination.+ * Number of results per page (default: 100, max: 1000).* @minimum 1* @maximum 1000*/@@ -78644,10 +78682,18 @@ export namespace Schemas {* Upper bound on `created_at` (inclusive), ISO-8601.*/end_date?: string;+ /**+ * Keep the next link valid after the last entry, so the same cursor can be re-polled as new entries arrive. Only applies with oldest-first ordering. When following, stop on an empty results list rather than on a null next link.+ */+ follow?: boolean;/*** Reserved for future HogQL-based filtering.*/hogql_filter?: string;+ /**+ * Include the previous and new values of changed fields. Only applies when schema is ocsf. Values can contain the content of the changed object, which makes responses larger and sends that content to your security tool.+ */+ include_values?: boolean;/*** Filter by client IP addresses. Accepts exact IPv4/IPv6 values or wildcard patterns using `*` (e.g. `203.0.113.*`). Multiple entries are OR-combined.*/@@ -78661,17 +78707,32 @@ export namespace Schemas {* Filter by the `item_id` of the affected resource(s).*/item_ids?: string[];+ /**+ * Sort by when the entry was created. Defaults to newest first. Use created_at for oldest first when polling for new entries, so a saved cursor picks up where the last request stopped.+ *+ * * `-created_at` - -created_at+ * * `created_at` - created_at+ * @minLength 1+ */+ ordering?: string;/*** Page number for pagination. When provided, uses page-based pagination ordered by most recent first.* @minimum 1*/page?: number;/**- * Number of results per page (default: 100, max: 1000). Only used with page-based pagination.+ * Number of results per page (default: 100, max: 1000).* @minimum 1* @maximum 1000*/page_size?: number;+ /**+ * Response format. Set to ocsf to return Open Cybersecurity Schema Framework events for ingestion into a security tool. Omit for the default PostHog format.+ *+ * * `ocsf` - ocsf+ * @minLength 1+ */+ schema?: AdvancedActivityLogsListSchema;/*** Filter by activity scopes (e.g. "FeatureFlag", "Insight").*/@@ -78699,6 +78760,13 @@ export namespace Schemas {was_impersonated?: boolean | null;};+ export type AdvancedActivityLogsListSchema = typeof AdvancedActivityLogsListSchema[keyof typeof AdvancedActivityLogsListSchema];+++ export const AdvancedActivityLogsListSchema = {+ Ocsf: 'ocsf',+ } as const;+export type AlertsListParams = {/*** Optional. Restrict results to alerts created by the user with this UUID.diff --git a/services/mcp/src/generated/platform_features/api.ts b/services/mcp/src/generated/platform_features/api.tsindex ba43bdb76b71..00d1a018dfb1 100644--- a/services/mcp/src/generated/platform_features/api.ts+++ b/services/mcp/src/generated/platform_features/api.ts@@ -160,8 +160,12 @@ export const AdvancedActivityLogsListParams = /* @__PURE__ */ zod.object({export const advancedActivityLogsListQueryActivitiesDefault = []export const advancedActivityLogsListQueryClientsDefault = []+export const advancedActivityLogsListQueryFollowDefault = false+export const advancedActivityLogsListQueryIncludeValuesDefault = falseexport const advancedActivityLogsListQueryIpAddressesDefault = []export const advancedActivityLogsListQueryItemIdsDefault = []+export const advancedActivityLogsListQueryOrderingDefault = `-created_at`+export const advancedActivityLogsListQueryPageSizeDefault = 100export const advancedActivityLogsListQueryPageSizeMax = 1000@@ -188,7 +192,19 @@ export const AdvancedActivityLogsListQueryParams = /* @__PURE__ */ zod.object({.datetime({ offset: true }).optional().describe('Upper bound on `created_at` (inclusive), ISO-8601.'),+ follow: zod+ .boolean()+ .default(advancedActivityLogsListQueryFollowDefault)+ .describe(+ 'Keep the next link valid after the last entry, so the same cursor can be re-polled as new entries arrive. Only applies with oldest-first ordering. When following, stop on an empty results list rather than on a null next link.'+ ),hogql_filter: zod.string().optional().describe('Reserved for future HogQL-based filtering.'),+ include_values: zod+ .boolean()+ .default(advancedActivityLogsListQueryIncludeValuesDefault)+ .describe(+ 'Include the previous and new values of changed fields. Only applies when schema is ocsf. Values can contain the content of the changed object, which makes responses larger and sends that content to your security tool.'+ ),ip_addresses: zod.array(zod.string()).default(advancedActivityLogsListQueryIpAddressesDefault)@@ -200,6 +216,13 @@ export const AdvancedActivityLogsListQueryParams = /* @__PURE__ */ zod.object({.array(zod.string()).default(advancedActivityLogsListQueryItemIdsDefault).describe('Filter by the `item_id` of the affected resource(s).'),+ ordering: zod+ .string()+ .min(1)+ .default(advancedActivityLogsListQueryOrderingDefault)+ .describe(+ 'Sort by when the entry was created. Defaults to newest first. Use created_at for oldest first when polling for new entries, so a saved cursor picks up where the last request stopped.\n\n\* `-created_at` - -created_at\n\* `created_at` - created_at'+ ),page: zod.number().min(1)@@ -212,7 +235,13 @@ export const AdvancedActivityLogsListQueryParams = /* @__PURE__ */ zod.object({.min(1).max(advancedActivityLogsListQueryPageSizeMax).default(advancedActivityLogsListQueryPageSizeDefault)- .describe('Number of results per page (default: 100, max: 1000). Only used with page-based pagination.'),+ .describe('Number of results per page (default: 100, max: 1000).'),+ schema: zod+ .enum(['ocsf'])+ .optional()+ .describe(+ 'Response format. Set to ocsf to return Open Cybersecurity Schema Framework events for ingestion into a security tool. Omit for the default PostHog format.\n\n\* `ocsf` - ocsf'+ ),scopes: zod.array(zod.string()).default(advancedActivityLogsListQueryScopesDefault)diff --git a/services/mcp/src/tools/generated/platform_features.ts b/services/mcp/src/tools/generated/platform_features.tsindex 0b56b007d734..2fe9be722565 100644--- a/services/mcp/src/tools/generated/platform_features.ts+++ b/services/mcp/src/tools/generated/platform_features.ts@@ -63,33 +63,33 @@ const advancedActivityLogsFilters = (): ToolBase<},})-const AdvancedActivityLogsListSchema = AdvancedActivityLogsListQueryParams.extend({- page_size: AdvancedActivityLogsListQueryParams.shape['page_size'].default(10).optional(),-}).extend({- fields: z- .array(- z.enum([- 'id',- 'user.id',- 'user.first_name',- 'user.last_name',- 'user.email',- 'activity',- 'scope',- 'item_id',- 'detail.name',- 'detail.short_id',- 'detail.type',- 'detail.changes',- 'created_at',- ])- )- .min(1)- .optional()- .describe(- 'Optional subset of response fields to return, each a dot-path from the allowlist. Omit to return all fields. Request only the fields your task needs to keep responses small.'- ),-})+const AdvancedActivityLogsListSchema = AdvancedActivityLogsListQueryParams.omit({ include_values: true, schema: true })+ .extend({ page_size: AdvancedActivityLogsListQueryParams.shape['page_size'].default(10).optional() })+ .extend({+ fields: z+ .array(+ z.enum([+ 'id',+ 'user.id',+ 'user.first_name',+ 'user.last_name',+ 'user.email',+ 'activity',+ 'scope',+ 'item_id',+ 'detail.name',+ 'detail.short_id',+ 'detail.type',+ 'detail.changes',+ 'created_at',+ ])+ )+ .min(1)+ .optional()+ .describe(+ 'Optional subset of response fields to return, each a dot-path from the allowlist. Omit to return all fields. Request only the fields your task needs to keep responses small.'+ ),+ })const advancedActivityLogsList = (): ToolBase<typeof AdvancedActivityLogsListSchema,@@ -107,10 +107,12 @@ const advancedActivityLogsList = (): ToolBase<clients: params.clients,detail_filters: params.detail_filters,end_date: params.end_date,+ follow: params.follow,hogql_filter: params.hogql_filter,ip_addresses: params.ip_addresses,is_system: params.is_system,item_ids: params.item_ids,+ ordering: params.ordering,page: params.page,page_size: params.page_size,scopes: params.scopes,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/advanced-activity-logs-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/advanced-activity-logs-list.jsonindex a747cf863d53..88c4c9e30358 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/advanced-activity-logs-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/advanced-activity-logs-list.json@@ -50,6 +50,11 @@"minItems": 1,"type": "array"},+ "follow": {+ "default": false,+ "description": "Keep the next link valid after the last entry, so the same cursor can be re-polled as new entries arrive. Only applies with oldest-first ordering. When following, stop on an empty results list rather than on a null next link.",+ "type": "boolean"+ },"hogql_filter": {"description": "Reserved for future HogQL-based filtering.","type": "string"@@ -81,6 +86,12 @@},"type": "array"},+ "ordering": {+ "default": "-created_at",+ "description": "Sort by when the entry was created. Defaults to newest first. Use created_at for oldest first when polling for new entries, so a saved cursor picks up where the last request stopped.\n\n* `-created_at` - -created_at\n* `created_at` - created_at",+ "minLength": 1,+ "type": "string"+ },"page": {"description": "Page number for pagination. When provided, uses page-based pagination ordered by most recent first.","minimum": 1,@@ -88,7 +99,7 @@},"page_size": {"default": 10,- "description": "Number of results per page (default: 100, max: 1000). Only used with page-based pagination.",+ "description": "Number of results per page (default: 100, max: 1000).","maximum": 1000,"minimum": 1,"type": "number"