: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(workflows): opt-out list import/export via CSV, API and MCP (#76874)
Abheek Basua00ab91023a9
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex f994f361a86d..f07cf9cd1c17 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -235,6 +235,7 @@ import type {GitHubReposResponseApi,} from 'products/integrations/frontend/generated/api.schemas'import type { LogExplanation } from 'products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/ExploreWithAI/types'+import type { BulkAddOptOutsResultApi, BulkOptOutEntryApi } from 'products/messaging/frontend/generated/api.schemas'import type { NotebookCollabCursorApi } from 'products/notebooks/frontend/generated/api.schemas'import type { Task, TaskListParams, TaskRun, TaskUpsertProps } from 'products/posthog_ai/frontend/types/taskTypes'import type {@@ -1999,6 +2000,20 @@ export class ApiRequest {return this.environments().current().addPathComponent('messaging_preferences').addPathComponent('add_opt_out')}+ public messagingPreferencesExportOptOutsCsv(): ApiRequest {+ return this.environments()+ .current()+ .addPathComponent('messaging_preferences')+ .addPathComponent('export_opt_outs_csv')+ }++ public messagingPreferencesBulkAddOptOuts(): ApiRequest {+ return this.environments()+ .current()+ .addPathComponent('messaging_preferences')+ .addPathComponent('bulk_add_opt_outs')+ }+public hogFlows(): ApiRequest {return this.environments().current().addPathComponent('hog_flows')}@@ -6678,6 +6693,18 @@ const api = {data: { identifier, category_key: categoryKey },})},+ async exportOptOutsCsv(categoryKey?: string): Promise<Blob> {+ const response = await new ApiRequest()+ .messagingPreferencesExportOptOutsCsv()+ .withQueryString({ category_key: categoryKey })+ .getResponse()+ return await response.blob()+ },+ async bulkAddOptOuts(optOuts: BulkOptOutEntryApi[], categoryKey?: string): Promise<BulkAddOptOutsResultApi> {+ return await new ApiRequest().messagingPreferencesBulkAddOptOuts().create({+ data: { opt_outs: optOuts, category_key: categoryKey },+ })+ },},hogFlows: {async getHogFlows(params?: {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d855e3c22ad9..de6a8bde926b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4445,6 +4445,9 @@ importers:kea-subscriptions:specifier: 'catalog:'version: 3.0.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ papaparse:+ specifier: ^5.4.1+ version: 5.4.1posthog-js:specifier: 'catalog:'version: 1.410.1@@ -4467,6 +4470,9 @@ importers:'@testing-library/react':specifier: '*'+ '@types/papaparse':+ specifier: '*'+ version: 5.3.8kea-test-utils:specifier: 'catalog:'version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.pyindex ecc568401125..ec45c6341e53 100644--- a/posthog/hogql/database/schema/system.py+++ b/posthog/hogql/database/schema/system.py@@ -1138,6 +1138,64 @@ hog_functions: PostgresTable = PostgresTable(},)+message_categories: PostgresTable = PostgresTable(+ name="message_categories",+ postgres_table_name="posthog_messagecategory",+ access_scope="hog_flow",+ description="Message categories recipients can opt out of; one row per category. Join its id against the keys of message_recipient_preferences.preferences.",+ fields={+ "id": StringDatabaseField(name="id", description="Category UUID, used as the key in recipient preferences."),+ "team_id": IntegerDatabaseField(name="team_id"),+ "key": StringDatabaseField(name="key", description="Stable category key used in the API, e.g. 'newsletter'."),+ "name": StringDatabaseField(name="name", description="Display name of the category."),+ "description": StringDatabaseField(name="description", description="Internal description of the category."),+ "public_description": StringDatabaseField(+ name="public_description", description="Description shown to recipients on the preferences page."+ ),+ "category_type": StringDatabaseField(+ name="category_type", description="'marketing' (opt-out applies) or 'transactional'."+ ),+ "_deleted": BooleanDatabaseField(name="deleted", hidden=True),+ "deleted": ExpressionField(+ name="deleted",+ expr=ast.Call(name="toInt", args=[ast.Field(chain=["_deleted"])]),+ isolate_scope=True,+ description="1 if the category has been deleted, 0 otherwise.",+ ),+ "created_at": DateTimeDatabaseField(name="created_at", description="When the category was created."),+ "updated_at": DateTimeDatabaseField(name="updated_at", description="When the category was last updated."),+ },+)++message_recipient_preferences: PostgresTable = PostgresTable(+ name="message_recipient_preferences",+ postgres_table_name="posthog_messagerecipientpreference",+ access_scope="hog_flow",+ description="Messaging preferences per recipient; one row per recipient. The preferences map records opt-outs and opt-ins per message category.",+ fields={+ "id": StringDatabaseField(name="id", description="Preference row UUID."),+ "team_id": IntegerDatabaseField(name="team_id"),+ "identifier": StringDatabaseField(+ name="identifier", description="Recipient identifier, usually an email address."+ ),+ "preferences": StringJSONDatabaseField(+ name="preferences",+ description="JSON map of message category ID to 'OPTED_OUT' or 'OPTED_IN'. The key '$all' covers all marketing messages; other keys are message_categories ids.",+ ),+ "_deleted": BooleanDatabaseField(name="deleted", hidden=True),+ "deleted": ExpressionField(+ name="deleted",+ expr=ast.Call(name="toInt", args=[ast.Field(chain=["_deleted"])]),+ isolate_scope=True,+ description="1 if the row has been deleted, 0 otherwise.",+ ),+ "created_at": DateTimeDatabaseField(name="created_at", description="When the recipient was first recorded."),+ "updated_at": DateTimeDatabaseField(+ name="updated_at", description="When the recipient's preferences last changed."+ ),+ },+)+def _notebook_content_or_empty_object_expr() -> ast.Expr:return ast.Call(name="ifNull", args=[ast.Field(chain=["content"]), ast.Constant(value="{}")])@@ -2298,6 +2356,10 @@ class SystemTables(TableNode):"hog_functions": TableNode(name="hog_functions", table=hog_functions),"ingestion_warnings": TableNode(name="ingestion_warnings", table=IngestionWarningsTable()),"integrations": TableNode(name="integrations", table=integrations),+ "message_categories": TableNode(name="message_categories", table=message_categories),+ "message_recipient_preferences": TableNode(+ name="message_recipient_preferences", table=message_recipient_preferences+ ),"integration_repository_cache": TableNode(name="integration_repository_cache", table=integration_repository_cache),diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex f7d62bfa7b77..10afbeaa5ee9 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -387,6 +387,20 @@ def _create_hog_flow(team: Team, label: str) -> HogFlow:return HogFlow.objects.create(team=team, name=f"flow_{label}")+def _create_message_category(team: Team, label: str):+ from products.messaging.backend.models.message_category import MessageCategory++ return MessageCategory.objects.create(team=team, key=f"category_{label}", name=f"Category {label}")+++def _create_message_recipient_preference(team: Team, label: str):+ from products.messaging.backend.models.message_preferences import MessageRecipientPreference++ return MessageRecipientPreference.objects.create(+ team=team, identifier=f"{label}@example.com", preferences={"$all": "OPTED_OUT"}+ )++def _create_hog_function(team: Team, label: str) -> HogFunction:return HogFunction.objects.create(team=team,@@ -720,6 +734,8 @@ SYSTEM_TABLE_FACTORIES = [("integration_repository_cache", _create_integration_repository_cache_entry),("logs_alerts", _create_logs_alert),("logs_views", _create_logs_view),+ ("message_categories", _create_message_category),+ ("message_recipient_preferences", _create_message_recipient_preference),("notebooks", _create_notebook),("review_queue_items", _create_review_queue_item),("review_queues", _create_review_queue),diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambrindex 9bfd649257ad..8c91b1292045 100644--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr@@ -6828,6 +6828,174 @@"row_count": null,"type": "system"},+ "system.message_categories": {+ "certification": null,+ "fields": {+ "id": {+ "chain": null,+ "fields": null,+ "hogql_value": "id",+ "id": null,+ "name": "id",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "key": {+ "chain": null,+ "fields": null,+ "hogql_value": "key",+ "id": null,+ "name": "key",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "name": {+ "chain": null,+ "fields": null,+ "hogql_value": "name",+ "id": null,+ "name": "name",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "description": {+ "chain": null,+ "fields": null,+ "hogql_value": "description",+ "id": null,+ "name": "description",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "public_description": {+ "chain": null,+ "fields": null,+ "hogql_value": "public_description",+ "id": null,+ "name": "public_description",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "category_type": {+ "chain": null,+ "fields": null,+ "hogql_value": "category_type",+ "id": null,+ "name": "category_type",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "deleted": {+ "chain": null,+ "fields": null,+ "hogql_value": "deleted",+ "id": null,+ "name": "deleted",+ "schema_valid": true,+ "table": null,+ "type": "integer"+ },+ "created_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "created_at",+ "id": null,+ "name": "created_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ },+ "updated_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "updated_at",+ "id": null,+ "name": "updated_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ }+ },+ "id": "system.message_categories",+ "name": "system.message_categories",+ "row_count": null,+ "type": "system"+ },+ "system.message_recipient_preferences": {+ "certification": null,+ "fields": {+ "id": {+ "chain": null,+ "fields": null,+ "hogql_value": "id",+ "id": null,+ "name": "id",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "identifier": {+ "chain": null,+ "fields": null,+ "hogql_value": "identifier",+ "id": null,+ "name": "identifier",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "preferences": {+ "chain": null,+ "fields": null,+ "hogql_value": "preferences",+ "id": null,+ "name": "preferences",+ "schema_valid": true,+ "table": null,+ "type": "json"+ },+ "deleted": {+ "chain": null,+ "fields": null,+ "hogql_value": "deleted",+ "id": null,+ "name": "deleted",+ "schema_valid": true,+ "table": null,+ "type": "integer"+ },+ "created_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "created_at",+ "id": null,+ "name": "created_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ },+ "updated_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "updated_at",+ "id": null,+ "name": "updated_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ }+ },+ "id": "system.message_recipient_preferences",+ "name": "system.message_recipient_preferences",+ "row_count": null,+ "type": "system"+ },"system.integration_repository_cache": {"certification": null,"fields": {@@ -15719,6 +15887,174 @@"row_count": null,"type": "system"},+ "system.message_categories": {+ "certification": null,+ "fields": {+ "id": {+ "chain": null,+ "fields": null,+ "hogql_value": "id",+ "id": null,+ "name": "id",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "key": {+ "chain": null,+ "fields": null,+ "hogql_value": "key",+ "id": null,+ "name": "key",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "name": {+ "chain": null,+ "fields": null,+ "hogql_value": "name",+ "id": null,+ "name": "name",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "description": {+ "chain": null,+ "fields": null,+ "hogql_value": "description",+ "id": null,+ "name": "description",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "public_description": {+ "chain": null,+ "fields": null,+ "hogql_value": "public_description",+ "id": null,+ "name": "public_description",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "category_type": {+ "chain": null,+ "fields": null,+ "hogql_value": "category_type",+ "id": null,+ "name": "category_type",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "deleted": {+ "chain": null,+ "fields": null,+ "hogql_value": "deleted",+ "id": null,+ "name": "deleted",+ "schema_valid": true,+ "table": null,+ "type": "integer"+ },+ "created_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "created_at",+ "id": null,+ "name": "created_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ },+ "updated_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "updated_at",+ "id": null,+ "name": "updated_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ }+ },+ "id": "system.message_categories",+ "name": "system.message_categories",+ "row_count": null,+ "type": "system"+ },+ "system.message_recipient_preferences": {+ "certification": null,+ "fields": {+ "id": {+ "chain": null,+ "fields": null,+ "hogql_value": "id",+ "id": null,+ "name": "id",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "identifier": {+ "chain": null,+ "fields": null,+ "hogql_value": "identifier",+ "id": null,+ "name": "identifier",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "preferences": {+ "chain": null,+ "fields": null,+ "hogql_value": "preferences",+ "id": null,+ "name": "preferences",+ "schema_valid": true,+ "table": null,+ "type": "json"+ },+ "deleted": {+ "chain": null,+ "fields": null,+ "hogql_value": "deleted",+ "id": null,+ "name": "deleted",+ "schema_valid": true,+ "table": null,+ "type": "integer"+ },+ "created_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "created_at",+ "id": null,+ "name": "created_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ },+ "updated_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "updated_at",+ "id": null,+ "name": "updated_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ }+ },+ "id": "system.message_recipient_preferences",+ "name": "system.message_recipient_preferences",+ "row_count": null,+ "type": "system"+ },"system.integration_repository_cache": {"certification": null,"fields": {diff --git a/posthog/hogql/database/test/test_postgres_table.py b/posthog/hogql/database/test/test_postgres_table.pyindex c3dea2cc6294..c577a4004c50 100644--- a/posthog/hogql/database/test/test_postgres_table.py+++ b/posthog/hogql/database/test/test_postgres_table.py@@ -52,6 +52,10 @@ _SCOPE_GATED_METADATA_TABLES: frozenset[str] = frozenset({"custom_property_definitions","account_relationship_definitions",+ # Team-level messaging data not tied to any single flow; MessagePreferencesViewSet+ # grants the same rows at resource level (hog_flow:read) with no object-level check.+ "message_categories",+ "message_recipient_preferences",})diff --git a/products/messaging/backend/api/message_preferences.py b/products/messaging/backend/api/message_preferences.pyindex f20065bcc0d7..a6581b013419 100644--- a/products/messaging/backend/api/message_preferences.py+++ b/products/messaging/backend/api/message_preferences.py@@ -1,4 +1,7 @@-from drf_spectacular.utils import extend_schema+import re++from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.pagination import PageNumberPagination@@ -6,6 +9,7 @@ from rest_framework.response import Responsefrom posthog.api.documentation import _FallbackSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.streaming import streaming_responsefrom posthog.plugins import plugin_server_apifrom products.messaging.backend.models.message_category import MessageCategory@@ -14,6 +18,10 @@ from products.messaging.backend.models.message_preferences import (MessageRecipientPreference,PreferenceStatus,)+from products.messaging.backend.services.opt_out_service import BulkOptOutEntry, OptOutService, UnknownCategoryError++MAX_BULK_OPT_OUT_ENTRIES = 1000+UNSAFE_FILENAME_CHARACTERS = re.compile(r"[^A-Za-z0-9_-]+")class OptOutsPagination(PageNumberPagination):@@ -55,10 +63,88 @@ class AddOptOutRequestSerializer(serializers.Serializer):)+class MessagingErrorSerializer(serializers.Serializer):+ error = serializers.CharField(help_text="Human-readable description of what went wrong.")+++class PaginatedOptOutsSerializer(serializers.Serializer):+ """OpenAPI shape for the paginated opt-outs response, so the generated clients get the+ {count, next, previous, results} envelope instead of an untyped object."""++ count = serializers.IntegerField(help_text="Total number of opted-out recipients for the category.")+ next = serializers.URLField(allow_null=True, help_text="URL for the next page, or null on the last page.")+ previous = serializers.URLField(allow_null=True, help_text="URL for the previous page, or null on the first page.")+ results = MessagePreferencesSerializer(many=True)+++class BulkOptOutEntrySerializer(serializers.Serializer):+ identifier = serializers.CharField(+ max_length=512,+ help_text="The recipient identifier to opt out (e.g. email address).",+ )+ category_key = serializers.CharField(+ required=False,+ allow_blank=True,+ help_text="Message category key for this recipient. Overrides the request-level category_key.",+ )+++class BulkAddOptOutsRequestSerializer(serializers.Serializer):+ opt_outs = BulkOptOutEntrySerializer(+ many=True,+ allow_empty=False,+ help_text=f"Recipients to opt out, at most {MAX_BULK_OPT_OUT_ENTRIES} per request.",+ )+ category_key = serializers.CharField(+ required=False,+ allow_blank=True,+ help_text="Message category key applied to entries without their own. If omitted, recipients are opted out of all marketing messages.",+ )++ def validate_opt_outs(self, value: list[dict]) -> list[dict]:+ if len(value) > MAX_BULK_OPT_OUT_ENTRIES:+ raise serializers.ValidationError(f"Send at most {MAX_BULK_OPT_OUT_ENTRIES} opt-outs per request.")+ return value+++class BulkAddOptOutsResultSerializer(serializers.Serializer):+ total = serializers.IntegerField(help_text="Number of opt-out entries received.")+ opted_out = serializers.IntegerField(help_text="Number of recipient and category pairs recorded as opted out.")+ skipped = serializers.IntegerField(help_text="Number of entries skipped because their category_key doesn't exist.")+ # The metaclass pops declared fields off the class, so this doesn't actually shadow+ # Serializer.errors at runtime — mypy just can't see that.+ errors = serializers.ListField( # type: ignore[assignment]+ child=serializers.CharField(),+ help_text="The first few entry-level problems, so the caller can fix their list.",+ )++class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):- scope_object = "INTERNAL"+ scope_object = "hog_flow"+ # Only the opt-out list endpoints are reachable with API keys (and therefore MCP);+ # webhook_url and generate_link stay session-only by being listed in neither.+ scope_object_read_actions = ["opt_outs", "export_opt_outs_csv"]+ scope_object_write_actions = ["add_opt_out", "bulk_add_opt_outs"]serializer_class = _FallbackSerializer+ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="category_key",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Message category key to list opt-outs for. If omitted, lists recipients opted out of all marketing messages.",+ ),+ OpenApiParameter(name="page", type=OpenApiTypes.INT, location=OpenApiParameter.QUERY, required=False),+ OpenApiParameter(name="page_size", type=OpenApiTypes.INT, location=OpenApiParameter.QUERY, required=False),+ ],+ responses={+ 200: PaginatedOptOutsSerializer,+ 404: OpenApiResponse(response=MessagingErrorSerializer),+ },+ summary="List recipients opted out of a message category",+ )@action(detail=False, methods=["get"])def opt_outs(self, request, **kwargs):"""Get opt-outs filtered by category or overall opt-outs if no category specified"""@@ -126,6 +212,69 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):response_status = status.HTTP_201_CREATED if created else status.HTTP_200_OKreturn Response(MessagePreferencesSerializer(preference).data, status=response_status)+ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="category_key",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Message category key to export. If omitted, exports recipients opted out of all marketing messages.",+ )+ ],+ responses={+ (200, "text/csv"): OpenApiTypes.STR,+ 404: OpenApiResponse(response=MessagingErrorSerializer),+ },+ summary="Download the opt-out list as a CSV file",+ )+ @action(detail=False, methods=["get"])+ def export_opt_outs_csv(self, request, **kwargs):+ """Stream the opt-out list for a category as a CSV file that can be re-imported as-is."""+ category_key = request.query_params.get("category_key")+ service = OptOutService(team_id=self.team_id, user=request.user)++ try:+ rows = service.export_rows(category_key)+ except UnknownCategoryError as e:+ return Response({"error": str(e)}, status=status.HTTP_404_NOT_FOUND)++ filename_suffix = (+ UNSAFE_FILENAME_CHARACTERS.sub("-", category_key).strip("-") if category_key else "all-marketing"+ )+ return streaming_response(+ rows,+ content_type="text/csv",+ headers={"Content-Disposition": f'attachment; filename="opt-outs-{filename_suffix or "category"}.csv"'},+ )++ @extend_schema(+ request=BulkAddOptOutsRequestSerializer,+ responses={+ 200: BulkAddOptOutsResultSerializer,+ 404: OpenApiResponse(response=MessagingErrorSerializer),+ },+ summary="Add multiple recipients to the opt-out list",+ )+ @action(detail=False, methods=["post"])+ def bulk_add_opt_outs(self, request, **kwargs):+ """Opt every recipient in the list out of the category named on their entry, or a default category."""+ serializer = BulkAddOptOutsRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ entries = [+ BulkOptOutEntry(identifier=entry["identifier"], category_key=entry.get("category_key") or None)+ for entry in serializer.validated_data["opt_outs"]+ ]++ service = OptOutService(team_id=self.team_id, user=request.user)+ try:+ result = service.opt_out_recipients(entries, serializer.validated_data.get("category_key") or None)+ except UnknownCategoryError as e:+ return Response({"error": str(e)}, status=status.HTTP_404_NOT_FOUND)++ return Response(BulkAddOptOutsResultSerializer(result).data, status=status.HTTP_200_OK)+@action(detail=False, methods=["get"])def webhook_url(self, request, **kwargs):"""Return the webhook URL for Customer.io integration setup."""diff --git a/products/messaging/backend/services/opt_out_service.py b/products/messaging/backend/services/opt_out_service.pynew file mode 100644index 000000000000..05151d95ed6a--- /dev/null+++ b/products/messaging/backend/services/opt_out_service.py@@ -0,0 +1,208 @@+import csv+import logging+from collections.abc import Iterator, Sequence+from dataclasses import dataclass+from typing import Any, Optional++from django.db import connections, transaction+from django.db.models import Q++from posthog.security.spreadsheet_safety import sanitize_formula_injection++from products.messaging.backend.models.message_category import MessageCategory+from products.messaging.backend.models.message_preferences import (+ ALL_MESSAGE_PREFERENCE_CATEGORY_ID,+ MessageRecipientPreference,+ PreferenceStatus,+)++logger = logging.getLogger(__name__)++EXPORT_HEADER = ["identifier", "category_key", "updated_at"]++BATCH_SIZE = 1000+MAX_REPORTED_ERRORS = 10+++class UnknownCategoryError(Exception):+ def __init__(self, category_key: str):+ self.category_key = category_key+ super().__init__(f"Message category '{category_key}' not found")+++@dataclass(frozen=True, kw_only=True)+class BulkOptOutEntry:+ identifier: str+ category_key: Optional[str] = None+++@dataclass(frozen=True, kw_only=True)+class BulkOptOutResult:+ total: int+ opted_out: int+ skipped: int+ errors: list[str]+++class _Echo:+ """File-like sink so csv.writer can hand rows straight to a streaming response."""++ def write(self, value: str) -> str:+ return value+++class OptOutService:+ """Reads and writes opt-out lists in bulk, so recipients can be moved in and out of PostHog."""++ def __init__(self, team_id: int, user: Optional[Any] = None):+ self.team_id = team_id+ self.user = user++ def _category_key_to_id(self) -> dict[str, str]:+ """Map every usable category key to the ID stored in a recipient's preferences blob."""+ mapping = {+ key: str(category_id)+ for key, category_id in MessageCategory.objects.filter(team_id=self.team_id, deleted=False).values_list(+ "key", "id"+ )+ }+ mapping[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = ALL_MESSAGE_PREFERENCE_CATEGORY_ID+ return mapping++ def resolve_category_id(self, category_key: Optional[str]) -> str:+ """Turn a category key into its preferences-blob ID, defaulting to the all-marketing opt-out."""+ if not category_key or category_key == ALL_MESSAGE_PREFERENCE_CATEGORY_ID:+ return ALL_MESSAGE_PREFERENCE_CATEGORY_ID++ category_id = self._category_key_to_id().get(category_key)+ if category_id is None:+ raise UnknownCategoryError(category_key)+ return category_id++ def export_rows(self, category_key: Optional[str] = None) -> Iterator[str]:+ """Return the opt-out list for one category as CSV lines, ready to stream.++ The category is resolved eagerly so an unknown key surfaces as a normal+ error rather than half way through a response that already sent a 200.++ Rows are fetched in keyset-paginated batches with the DB connection closed+ after each fetch: streaming_response() releases the request connections+ before the body runs, so anything the generator opens would otherwise stay+ pinned to a pgbouncer slot for as long as the client takes to download.+ """+ category_id = self.resolve_category_id(category_key)+ export_key = category_key or ALL_MESSAGE_PREFERENCE_CATEGORY_ID++ def fetch_batch(after: Optional[tuple[Any, Any]]) -> list[tuple[str, Any, Any]]:+ queryset = MessageRecipientPreference.objects.filter(+ team_id=self.team_id,+ **{f"preferences__{category_id}": PreferenceStatus.OPTED_OUT.value},+ ).order_by("-updated_at", "-id")+ if after is not None:+ queryset = queryset.filter(Q(updated_at__lt=after[0]) | Q(updated_at=after[0], id__lt=after[1]))+ batch = list(queryset.values_list("identifier", "updated_at", "id")[:BATCH_SIZE])+ # Same guard as _release_request_connections: severing an open transaction+ # corrupts it (only tests stream inside one).+ connection = connections[MessageRecipientPreference.objects.db]+ if not connection.in_atomic_block:+ connection.close()+ return batch++ def rows() -> Iterator[str]:+ writer = csv.writer(_Echo())+ yield writer.writerow(EXPORT_HEADER)+ after: Optional[tuple[Any, Any]] = None+ while True:+ batch = fetch_batch(after)+ if not batch:+ return+ for identifier, updated_at, _ in batch:+ yield writer.writerow(+ [+ sanitize_formula_injection(identifier),+ sanitize_formula_injection(export_key),+ updated_at.isoformat(),+ ]+ )+ after = (batch[-1][1], batch[-1][2])++ return rows()++ def opt_out_recipients(+ self, entries: Sequence[BulkOptOutEntry], default_category_key: Optional[str] = None+ ) -> BulkOptOutResult:+ """Opt every recipient out of the category named on their entry, or the default one.++ An entry naming a category that doesn't exist is skipped and reported rather+ than failing the request, so one bad entry can't block the rest of the list.+ """+ default_category_id = self.resolve_category_id(default_category_key)+ key_to_id = self._category_key_to_id()++ opted_out = 0+ skipped = 0+ errors: list[str] = []+ pending: dict[str, set[str]] = {}++ for entry_number, entry in enumerate(entries, start=1):+ category_id = default_category_id+ if entry.category_key:+ resolved = key_to_id.get(entry.category_key)+ if resolved is None:+ skipped += 1+ _record_error(errors, f"Entry {entry_number}: no message category with key '{entry.category_key}'")+ continue+ category_id = resolved++ categories = pending.setdefault(entry.identifier, set())+ if category_id not in categories:+ categories.add(category_id)+ opted_out += 1++ if len(pending) >= BATCH_SIZE:+ self._save_batch(pending)+ pending = {}++ if pending:+ self._save_batch(pending)++ return BulkOptOutResult(total=len(entries), opted_out=opted_out, skipped=skipped, errors=errors)++ def _save_batch(self, batch: dict[str, set[str]]) -> None:+ with transaction.atomic():+ existing = {+ preference.identifier: preference+ for preference in MessageRecipientPreference.objects.filter(+ team_id=self.team_id, identifier__in=list(batch.keys())+ )+ }++ to_create = []+ to_update = []++ for identifier, category_ids in batch.items():+ preference = existing.get(identifier)+ if preference is None:+ to_create.append(+ MessageRecipientPreference(+ team_id=self.team_id,+ identifier=identifier,+ created_by=self.user,+ preferences=dict.fromkeys(category_ids, PreferenceStatus.OPTED_OUT.value),+ )+ )+ continue++ for category_id in category_ids:+ preference.preferences[category_id] = PreferenceStatus.OPTED_OUT.value+ to_update.append(preference)++ if to_create:+ MessageRecipientPreference.objects.bulk_create(to_create, batch_size=500)+ if to_update:+ MessageRecipientPreference.objects.bulk_update(to_update, ["preferences", "updated_at"], batch_size=500)+++def _record_error(errors: list[str], message: str) -> None:+ if len(errors) < MAX_REPORTED_ERRORS:+ errors.append(message)diff --git a/products/messaging/backend/tests/test_opt_outs.py b/products/messaging/backend/tests/test_opt_outs.pynew file mode 100644index 000000000000..b04ddc2bd08d--- /dev/null+++ b/products/messaging/backend/tests/test_opt_outs.py@@ -0,0 +1,162 @@+from collections.abc import Iterator+from typing import Any, cast++from posthog.test.base import APIBaseTest++from django.http import StreamingHttpResponse++from products.messaging.backend.models.message_category import MessageCategory+from products.messaging.backend.models.message_preferences import (+ ALL_MESSAGE_PREFERENCE_CATEGORY_ID,+ MessageRecipientPreference,+ PreferenceStatus,+)+++class TestOptOuts(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.category = MessageCategory.objects.create(+ team=self.team, key="newsletter", name="Newsletter", description="Weekly updates"+ )+ self.base_url = f"/api/environments/{self.team.id}/messaging_preferences"++ def _bulk(self, opt_outs: list[dict[str, Any]], **data):+ return self.client.post(+ f"{self.base_url}/bulk_add_opt_outs/",+ {"opt_outs": opt_outs, **data},+ format="json",+ )++ def _export(self, **params) -> str:+ response = self.client.get(f"{self.base_url}/export_opt_outs_csv/", params)+ self.assertEqual(response.status_code, 200)+ streamed = cast(StreamingHttpResponse, response).streaming_content+ return b"".join(cast(Iterator[bytes], streamed)).decode("utf-8")++ def test_bulk_opts_recipients_out_of_all_marketing_by_default(self):+ response = self._bulk([{"identifier": "[email protected]"}, {"identifier": "[email protected]"}])++ self.assertEqual(response.status_code, 200)+ result = response.json()+ self.assertEqual(result["total"], 2)+ self.assertEqual(result["opted_out"], 2)+ self.assertEqual(result["skipped"], 0)+ for identifier in ("[email protected]", "[email protected]"):+ preference = MessageRecipientPreference.objects.get(team=self.team, identifier=identifier)+ self.assertEqual(preference.get_preference(ALL_MESSAGE_PREFERENCE_CATEGORY_ID), PreferenceStatus.OPTED_OUT)++ def test_bulk_entry_category_overrides_the_request_default(self):+ other = MessageCategory.objects.create(team=self.team, key="product_updates", name="Product updates")++ response = self._bulk(+ [+ {"identifier": "[email protected]"},+ {"identifier": "[email protected]", "category_key": "product_updates"},+ ],+ category_key="newsletter",+ )++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json()["opted_out"], 2)+ ally = MessageRecipientPreference.objects.get(team=self.team, identifier="[email protected]")+ sam = MessageRecipientPreference.objects.get(team=self.team, identifier="[email protected]")+ self.assertEqual(ally.get_preference(str(self.category.id)), PreferenceStatus.OPTED_OUT)+ self.assertEqual(sam.get_preference(str(other.id)), PreferenceStatus.OPTED_OUT)++ def test_bulk_keeps_preferences_the_request_does_not_mention(self):+ MessageRecipientPreference.objects.create(+ team=self.team,+ identifier="[email protected]",+ preferences={str(self.category.id): PreferenceStatus.OPTED_IN.value},+ )++ self._bulk([{"identifier": "[email protected]"}])++ preference = MessageRecipientPreference.objects.get(team=self.team, identifier="[email protected]")+ self.assertEqual(preference.get_preference(str(self.category.id)), PreferenceStatus.OPTED_IN)+ self.assertEqual(preference.get_preference(ALL_MESSAGE_PREFERENCE_CATEGORY_ID), PreferenceStatus.OPTED_OUT)++ def test_bulk_skips_unknown_entry_categories_without_failing_the_request(self):+ response = self._bulk(+ [+ {"identifier": "[email protected]", "category_key": "nope"},+ {"identifier": "[email protected]", "category_key": "newsletter"},+ ]+ )++ self.assertEqual(response.status_code, 200)+ result = response.json()+ self.assertEqual(result["total"], 2)+ self.assertEqual(result["opted_out"], 1)+ self.assertEqual(result["skipped"], 1)+ self.assertEqual(len(result["errors"]), 1)+ self.assertIn("nope", result["errors"][0])+ self.assertTrue(+ MessageRecipientPreference.objects.filter(team=self.team, identifier="[email protected]").exists()+ )+ self.assertFalse(+ MessageRecipientPreference.objects.filter(team=self.team, identifier="[email protected]").exists()+ )++ def test_bulk_rejects_an_unknown_default_category(self):+ response = self._bulk([{"identifier": "[email protected]"}], category_key="nope")++ self.assertEqual(response.status_code, 404)+ self.assertFalse(MessageRecipientPreference.objects.filter(team=self.team).exists())++ def test_bulk_counts_a_repeated_recipient_and_category_pair_once(self):+ response = self._bulk([{"identifier": "[email protected]"}, {"identifier": "[email protected]"}])++ self.assertEqual(response.status_code, 200)+ result = response.json()+ self.assertEqual(result["total"], 2)+ self.assertEqual(result["opted_out"], 1)+ self.assertEqual(MessageRecipientPreference.objects.filter(team=self.team).count(), 1)++ def test_bulk_rejects_an_empty_list(self):+ response = self._bulk([])++ self.assertEqual(response.status_code, 400)++ def test_bulk_rejects_more_entries_than_the_per_request_limit(self):+ response = self._bulk([{"identifier": f"user{i}@example.com"} for i in range(1001)])++ self.assertEqual(response.status_code, 400)+ self.assertFalse(MessageRecipientPreference.objects.filter(team=self.team).exists())++ def test_export_returns_importable_header_and_only_the_requested_category(self):+ self._bulk([{"identifier": "[email protected]"}], category_key="newsletter")+ self._bulk([{"identifier": "[email protected]"}])++ newsletter_csv = self._export(category_key="newsletter")+ marketing_csv = self._export()++ self.assertTrue(newsletter_csv.startswith("identifier,category_key,updated_at"))+ self.assertIn("[email protected]", newsletter_csv)+ self.assertNotIn("[email protected]", newsletter_csv)+ self.assertIn("[email protected]", marketing_csv)+ self.assertNotIn("[email protected]", marketing_csv)++ def test_export_neutralizes_formula_leading_identifiers(self):+ self._bulk([{"identifier": "=SUM(A1:B1)"}, {"identifier": "[email protected]"}])++ exported = self._export()++ self.assertIn("'=SUM(A1:B1)", exported)+ self.assertIn("\[email protected],", exported)++ def test_export_does_not_leak_opt_outs_from_another_team(self):+ other_team = self.create_team_with_organization(self.organization)+ MessageRecipientPreference.objects.create(+ team=other_team,+ identifier="[email protected]",+ preferences={ALL_MESSAGE_PREFERENCE_CATEGORY_ID: PreferenceStatus.OPTED_OUT.value},+ )++ self.assertNotIn("[email protected]", self._export())++ def test_export_rejects_an_unknown_category(self):+ response = self.client.get(f"{self.base_url}/export_opt_outs_csv/", {"category_key": "nope"})++ self.assertEqual(response.status_code, 404)diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.tsindex 0a50a18d05bb..d17a8839a2b3 100644--- a/products/messaging/frontend/generated/api.schemas.ts+++ b/products/messaging/frontend/generated/api.schemas.ts@@ -79,6 +79,59 @@ export interface MessagePreferencesApi {preferences: unknown}+export interface BulkOptOutEntryApi {+ /**+ * The recipient identifier to opt out (e.g. email address).+ * @maxLength 512+ */+ identifier: string+ /** Message category key for this recipient. Overrides the request-level category_key. */+ category_key?: string+}++export interface BulkAddOptOutsRequestApi {+ /** Recipients to opt out, at most 1000 per request. */+ opt_outs: BulkOptOutEntryApi[]+ /** Message category key applied to entries without their own. If omitted, recipients are opted out of all marketing messages. */+ category_key?: string+}++export interface BulkAddOptOutsResultApi {+ /** Number of opt-out entries received. */+ total: number+ /** Number of recipient and category pairs recorded as opted out. */+ opted_out: number+ /** Number of entries skipped because their category_key doesn't exist. */+ skipped: number+ /** The first few entry-level problems, so the caller can fix their list. */+ errors: string[]+}++export interface MessagingErrorApi {+ /** Human-readable description of what went wrong. */+ error: string+}++/**+ * OpenAPI shape for the paginated opt-outs response, so the generated clients get the+ * {count, next, previous, results} envelope instead of an untyped object.+ */+export interface PaginatedOptOutsApi {+ /** Total number of opted-out recipients for the category. */+ count: number+ /**+ * URL for the next page, or null on the last page.+ * @nullable+ */+ next: string | null+ /**+ * URL for the previous page, or null on the first page.+ * @nullable+ */+ previous: string | null+ results: MessagePreferencesApi[]+}+export interface AddSuppressionRequestApi {/*** The email address to suppress. Will not receive any messages until removed.@@ -419,6 +472,22 @@ export type MessagingCategoriesListParams = {offset?: number}+export type MessagingPreferencesExportOptOutsCsvRetrieveParams = {+ /**+ * Message category key to export. If omitted, exports recipients opted out of all marketing messages.+ */+ category_key?: string+}++export type MessagingPreferencesOptOutsRetrieveParams = {+ /**+ * Message category key to list opt-outs for. If omitted, lists recipients opted out of all marketing messages.+ */+ category_key?: string+ page?: number+ page_size?: number+}+export type MessagingSuppressionsSuppressionsRetrieveParams = {page?: numberpage_size?: numberdiff --git a/products/messaging/frontend/generated/api.ts b/products/messaging/frontend/generated/api.tsindex 57e527549352..76360a3d740f 100644--- a/products/messaging/frontend/generated/api.ts+++ b/products/messaging/frontend/generated/api.ts@@ -11,16 +11,21 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'import type {AddOptOutRequestApi,AddSuppressionRequestApi,+ BulkAddOptOutsRequestApi,+ BulkAddOptOutsResultApi,MessageCategoryApi,MessagePreferencesApi,MessageSuppressionApi,MessageTemplateApi,MessagingCategoriesListParams,+ MessagingPreferencesExportOptOutsCsvRetrieveParams,+ MessagingPreferencesOptOutsRetrieveParams,MessagingSuppressionsSuppressionsRetrieveParams,MessagingTemplatesListParams,PaginatedMessageCategoryListApi,PaginatedMessageSuppressionApi,PaginatedMessageTemplateListApi,+ PaginatedOptOutsApi,PatchedDesignPatchApi,PatchedMessageCategoryApi,PatchedMessageTemplateApi,@@ -354,6 +359,61 @@ export const messagingPreferencesAddOptOutCreate = async (})}+export const getMessagingPreferencesBulkAddOptOutsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/messaging_preferences/bulk_add_opt_outs/`+}++/**+ * Opt every recipient in the list out of the category named on their entry, or a default category.+ * @summary Add multiple recipients to the opt-out list+ */+export const messagingPreferencesBulkAddOptOutsCreate = async (+ projectId: string,+ bulkAddOptOutsRequestApi: BulkAddOptOutsRequestApi,+ options?: RequestInit+): Promise<BulkAddOptOutsResultApi> => {+ return apiMutator<BulkAddOptOutsResultApi>(getMessagingPreferencesBulkAddOptOutsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(bulkAddOptOutsRequestApi),+ })+}++export const getMessagingPreferencesExportOptOutsCsvRetrieveUrl = (+ projectId: string,+ params?: MessagingPreferencesExportOptOutsCsvRetrieveParams+) => {+ 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}/messaging_preferences/export_opt_outs_csv/?${stringifiedParams}`+ : `/api/projects/${projectId}/messaging_preferences/export_opt_outs_csv/`+}++/**+ * Stream the opt-out list for a category as a CSV file that can be re-imported as-is.+ * @summary Download the opt-out list as a CSV file+ */+export const messagingPreferencesExportOptOutsCsvRetrieve = async (+ projectId: string,+ params?: MessagingPreferencesExportOptOutsCsvRetrieveParams,+ options?: RequestInit+): Promise<string> => {+ return apiMutator<string>(getMessagingPreferencesExportOptOutsCsvRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getMessagingPreferencesGenerateLinkCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/messaging_preferences/generate_link/`}@@ -371,15 +431,35 @@ export const messagingPreferencesGenerateLinkCreate = async (})}-export const getMessagingPreferencesOptOutsRetrieveUrl = (projectId: string) => {- return `/api/projects/${projectId}/messaging_preferences/opt_outs/`+export const getMessagingPreferencesOptOutsRetrieveUrl = (+ projectId: string,+ params?: MessagingPreferencesOptOutsRetrieveParams+) => {+ 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}/messaging_preferences/opt_outs/?${stringifiedParams}`+ : `/api/projects/${projectId}/messaging_preferences/opt_outs/`}/*** Get opt-outs filtered by category or overall opt-outs if no category specified+ * @summary List recipients opted out of a message category*/-export const messagingPreferencesOptOutsRetrieve = async (projectId: string, options?: RequestInit): Promise<void> => {- return apiMutator<void>(getMessagingPreferencesOptOutsRetrieveUrl(projectId), {+export const messagingPreferencesOptOutsRetrieve = async (+ projectId: string,+ params?: MessagingPreferencesOptOutsRetrieveParams,+ options?: RequestInit+): Promise<PaginatedOptOutsApi> => {+ return apiMutator<PaginatedOptOutsApi>(getMessagingPreferencesOptOutsRetrieveUrl(projectId, params), {...options,method: 'GET',})diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.tsindex c95172d2b53e..51d956bd05b8 100644--- a/products/messaging/frontend/generated/api.zod.ts+++ b/products/messaging/frontend/generated/api.zod.ts@@ -163,6 +163,35 @@ export const MessagingPreferencesAddOptOutCreateBody = /* @__PURE__ */ zod.objec.describe('Optional message category key. If omitted, the recipient is opted out of all marketing messages.'),})+/**+ * Opt every recipient in the list out of the category named on their entry, or a default category.+ * @summary Add multiple recipients to the opt-out list+ */+export const messagingPreferencesBulkAddOptOutsCreateBodyOptOutsItemIdentifierMax = 512++export const MessagingPreferencesBulkAddOptOutsCreateBody = /* @__PURE__ */ zod.object({+ opt_outs: zod+ .array(+ zod.object({+ identifier: zod+ .string()+ .max(messagingPreferencesBulkAddOptOutsCreateBodyOptOutsItemIdentifierMax)+ .describe('The recipient identifier to opt out (e.g. email address).'),+ category_key: zod+ .string()+ .optional()+ .describe('Message category key for this recipient. Overrides the request-level category_key.'),+ })+ )+ .describe('Recipients to opt out, at most 1000 per request.'),+ category_key: zod+ .string()+ .optional()+ .describe(+ 'Message category key applied to entries without their own. If omitted, recipients are opted out of all marketing messages.'+ ),+})+/*** Manually suppress an email address so no workflow sends to it.* @summary Manually add an email address to the suppression listdiff --git a/products/messaging/mcp/tools.yaml b/products/messaging/mcp/tools.yamlnew file mode 100644index 000000000000..2a65519145c8--- /dev/null+++ b/products/messaging/mcp/tools.yaml@@ -0,0 +1,122 @@+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.+# The tool list and operation IDs are kept in sync automatically:+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all+#+# To enable a tool, set enabled: true and add required scopes + annotations.+# All other fields (title, description, enrich_url, etc.) are yours to configure.+category: Messaging+feature: messaging+url_prefix: /workflows+ui_apps: {}+tools:+ messaging-categories-create:+ operation: messaging_categories_create+ enabled: false+ messaging-categories-destroy:+ operation: messaging_categories_destroy+ enabled: false+ messaging-categories-import-from-customerio-create:+ operation: messaging_categories_import_from_customerio_create+ enabled: false+ messaging-categories-import-preferences-csv-create:+ operation: messaging_categories_import_preferences_csv_create+ enabled: false+ messaging-categories-list:+ operation: messaging_categories_list+ enabled: false+ messaging-categories-optout-sync-config-retrieve:+ operation: messaging_categories_optout_sync_config_retrieve+ enabled: false+ messaging-categories-partial-update:+ operation: messaging_categories_partial_update+ enabled: false+ messaging-categories-remove-customerio-app-config-destroy:+ operation: messaging_categories_remove_customerio_app_config_destroy+ enabled: false+ messaging-categories-remove-track-config-destroy:+ operation: messaging_categories_remove_track_config_destroy+ enabled: false+ messaging-categories-remove-webhook-config-destroy:+ operation: messaging_categories_remove_webhook_config_destroy+ enabled: false+ messaging-categories-retrieve:+ operation: messaging_categories_retrieve+ enabled: false+ messaging-categories-save-track-config-create:+ operation: messaging_categories_save_track_config_create+ enabled: false+ messaging-categories-save-webhook-config-create:+ operation: messaging_categories_save_webhook_config_create+ enabled: false+ messaging-categories-update:+ operation: messaging_categories_update+ enabled: false+ messaging-preferences-add-opt-out-create:+ operation: messaging_preferences_add_opt_out_create+ enabled: false+ messaging-preferences-export-opt-outs-csv-retrieve:+ operation: messaging_preferences_export_opt_outs_csv_retrieve+ enabled: false+ messaging-preferences-generate-link-create:+ operation: messaging_preferences_generate_link_create+ enabled: false+ messaging-preferences-webhook-url-retrieve:+ operation: messaging_preferences_webhook_url_retrieve+ enabled: false+ messaging-suppressions-add-suppression-create:+ operation: messaging_suppressions_add_suppression_create+ enabled: false+ messaging-suppressions-remove-suppression-create:+ operation: messaging_suppressions_remove_suppression_create+ enabled: false+ messaging-suppressions-suppressions-retrieve:+ operation: messaging_suppressions_suppressions_retrieve+ enabled: false+ messaging-templates-create:+ operation: messaging_templates_create+ enabled: false+ messaging-templates-design-partial-update:+ operation: messaging_templates_design_partial_update+ enabled: false+ messaging-templates-destroy:+ operation: messaging_templates_destroy+ enabled: false+ messaging-templates-list:+ operation: messaging_templates_list+ enabled: false+ messaging-templates-partial-update:+ operation: messaging_templates_partial_update+ enabled: false+ messaging-templates-retrieve:+ operation: messaging_templates_retrieve+ enabled: false+ messaging-templates-update:+ operation: messaging_templates_update+ enabled: false+ opt-outs-add:+ operation: messaging_preferences_bulk_add_opt_outs_create+ enabled: true+ scopes:+ - hog_flow:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Add recipients to the opt-out list+ description: >+ Opt one or more recipients (up to 1000 per call) out of marketing messages. Each entry can name its own+ message category via category_key; entries without one use the request-level category_key, or all marketing+ messages if omitted. Importing only ever opts recipients out, so repeating a call is safe.+ opt-outs-list:+ operation: messaging_preferences_opt_outs_retrieve+ enabled: true+ scopes:+ - hog_flow:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List opt-outs+ description: >+ List recipients opted out of a message category, most recently updated first. Omit category_key to list+ recipients opted out of all marketing messages.diff --git a/products/posthog_ai/frontend/policy/toolPolicy.ts b/products/posthog_ai/frontend/policy/toolPolicy.tsindex 5e61fbf6ecb7..a45ecbeb5ad6 100644--- a/products/posthog_ai/frontend/policy/toolPolicy.ts+++ b/products/posthog_ai/frontend/policy/toolPolicy.ts@@ -51,6 +51,7 @@ const POSTHOG_DESTRUCTIVE_SUB_TOOLS = new Set(['inbox-reports-bulk-set-state','inbox-reports-set-state','llma-prompt-label-set',+ 'opt-outs-add','organization-enforce-2fa','organization-enforce-2fa-execute','scout-scratchpad-forget',diff --git a/products/posthog_ai/skills/querying-posthog-data/SKILL.md b/products/posthog_ai/skills/querying-posthog-data/SKILL.mdindex 23bd45e53055..8c626d1563e1 100644--- a/products/posthog_ai/skills/querying-posthog-data/SKILL.md+++ b/products/posthog_ai/skills/querying-posthog-data/SKILL.md@@ -70,6 +70,7 @@ Schema reference for PostHog's core system models, organized by domain:- [AI observability reviews](./references/models-ai-observability-reviews.md)- [Logs (`logs` data plane + saved views and alerts)](./references/models-logs.md)- [MCP analytics (`$mcp_tool_call` events)](./references/models-mcp.md)+- [Messaging opt-outs (`system.message_recipient_preferences`, `system.message_categories`)](./references/models-messaging-opt-outs.md)- [Metrics (`posthog.metrics`)](./references/models-metrics.md)- [Notebooks](./references/models-notebooks.md)- [Session Recording Playlists](./references/models-session-recording-playlists.md)diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-messaging-opt-outs.md b/products/posthog_ai/skills/querying-posthog-data/references/models-messaging-opt-outs.mdnew file mode 100644index 000000000000..963221ce4133--- /dev/null+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-messaging-opt-outs.md@@ -0,0 +1,59 @@+# Messaging opt-outs++## Message recipient preferences (`system.message_recipient_preferences`)++Messaging preferences per recipient, one row per recipient. The `preferences` map records opt-outs and opt-ins per message category.++### Columns++Column | Type | Nullable | Description+`id` | string (UUID) | NOT NULL | Primary key+`team_id` | integer | NOT NULL | Owning team+`identifier` | varchar(512) | NOT NULL | Recipient identifier, usually an email address+`preferences` | jsonb | NOT NULL | Map of message category ID to `OPTED_OUT` or `OPTED_IN`. The key `$all` covers all marketing messages; other keys are `message_categories` ids+`deleted` | integer (0/1) | NOT NULL | 1 if soft-deleted; filter with `deleted = 0`+`created_at` | timestamp with tz | NOT NULL | When the recipient was first recorded+`updated_at` | timestamp with tz | NOT NULL | When preferences last changed++## Message categories (`system.message_categories`)++Message categories recipients can opt out of, one row per category. Category IDs are the keys in `message_recipient_preferences.preferences`.++### Columns++Column | Type | Nullable | Description+`id` | string (UUID) | NOT NULL | Primary key, used as the key in recipient preferences+`team_id` | integer | NOT NULL | Owning team+`key` | varchar(64) | NOT NULL | Stable category key used in the API, e.g. `newsletter`+`name` | varchar(128) | NOT NULL | Display name+`description` | text | NOT NULL | Internal description+`public_description` | text | NOT NULL | Description shown to recipients on the preferences page+`category_type` | varchar | NOT NULL | `marketing` (opt-out applies) or `transactional`+`deleted` | integer (0/1) | NOT NULL | 1 if soft-deleted; filter with `deleted = 0`+`created_at` | timestamp with tz | NOT NULL | Creation timestamp+`updated_at` | timestamp with tz | NOT NULL | Last update timestamp++### Query Examples++```sql+-- Recipients opted out of all marketing messages+SELECT identifier, updated_at+FROM system.message_recipient_preferences+WHERE deleted = 0 AND JSONExtractString(preferences, '$all') = 'OPTED_OUT'+ORDER BY updated_at DESC++-- Opt-out counts per category+SELECT c.key, c.name, count() AS opted_out+FROM system.message_recipient_preferences AS p+JOIN system.message_categories AS c ON JSONExtractString(p.preferences, toString(c.id)) = 'OPTED_OUT'+WHERE p.deleted = 0 AND c.deleted = 0+GROUP BY c.key, c.name+ORDER BY opted_out DESC++-- Is a specific recipient opted out of a category (falling back to the all-marketing flag)?+SELECT identifier,+ JSONExtractString(preferences, (SELECT toString(id) FROM system.message_categories WHERE key = 'newsletter')) AS category_status,+ JSONExtractString(preferences, '$all') AS all_marketing_status+FROM system.message_recipient_preferences+WHERE deleted = 0 AND identifier = '[email protected]'+```diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex ea4fb8a85c4a..42dac07e1bc9 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -156,6 +156,7 @@ POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS: tuple[str, ...] = ("inbox-reports-bulk-set-state","inbox-reports-set-state","llma-prompt-label-set",+ "opt-outs-add","organization-enforce-2fa","organization-enforce-2fa-execute","scout-scratchpad-forget",diff --git a/products/workflows/frontend/OptOuts/OptOutList.tsx b/products/workflows/frontend/OptOuts/OptOutList.tsxindex 49353a1a5328..1c351fe61780 100644--- a/products/workflows/frontend/OptOuts/OptOutList.tsx+++ b/products/workflows/frontend/OptOuts/OptOutList.tsx@@ -1,10 +1,19 @@import { useActions, useValues } from 'kea'-import { IconChevronLeft, IconChevronRight, IconExternal, IconPlus, IconRefresh } from '@posthog/icons'-import { LemonButton, LemonInput, LemonModal, LemonTable, LemonTableColumns } from '@posthog/lemon-ui'+import {+ IconChevronLeft,+ IconChevronRight,+ IconDownload,+ IconExternal,+ IconPlus,+ IconRefresh,+ IconUpload,+} from '@posthog/icons'+import { LemonBanner, LemonButton, LemonInput, LemonModal, LemonTable, LemonTableColumns } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { More } from 'lib/lemon-ui/LemonButton/More'+import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput'import { DataTable } from '~/queries/nodes/DataTable/DataTable'import { ActorsQuery, DataTableNode, NodeKind } from '~/queries/schema/schema-general'@@ -24,6 +33,11 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.ElsetShowAddOptOutModal,setNewOptOutIdentifier,addOptOut,+ setShowImportCsvModal,+ setCsvFile,+ importCsv,+ exportCsv,+ clearCsvImportResult,} = useActions(logic)const {selectedIdentifier,@@ -34,6 +48,12 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.ElshowAddOptOutModal,addOptOutLoading,newOptOutIdentifier,+ showImportCsvModal,+ csvFile,+ csvImportProgress,+ csvImportResult,+ csvImportResultLoading,+ csvExportLoading,} = useValues(logic)const handleShowPersons = (identifier: string): void => {@@ -110,6 +130,28 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.El>Add opt-out</LemonButton>+ <LemonButton+ icon={<IconUpload />}+ size="small"+ type="secondary"+ onClick={() => {+ clearCsvImportResult()+ setShowImportCsvModal(true)+ }}+ tooltip="Upload a CSV of recipients to opt out"+ >+ Import CSV+ </LemonButton>+ <LemonButton+ icon={<IconDownload />}+ size="small"+ type="secondary"+ onClick={exportCsv}+ loading={csvExportLoading}+ tooltip="Download this opt-out list as a CSV"+ >+ Export CSV+ </LemonButton><LemonButtonicon={<IconRefresh />}size="small"@@ -219,6 +261,88 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.El/></div></LemonModal>++ <LemonModal+ isOpen={showImportCsvModal}+ onClose={() => setShowImportCsvModal(false)}+ title={`Import opt-outs${category?.name ? ` for ${category.name}` : ''}`}+ description="Bring an opt-out list over from another email tool, or bulk add recipients."+ footer={+ <>+ <LemonButton type="secondary" onClick={() => setShowImportCsvModal(false)}>+ Close+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={importCsv}+ loading={csvImportResultLoading}+ disabledReason={!csvFile ? 'Choose a CSV file first' : undefined}+ >+ Import+ </LemonButton>+ </>+ }+ >+ <div className="space-y-3 max-w-160">+ <p className="mb-0">+ Upload a CSV with one recipient per row and a column named <code>identifier</code> or{' '}+ <code>email</code>. Everyone in the file is opted out of{' '}+ {category?.name ? <b>{category.name}</b> : 'all marketing messages'}, unless the row names a+ different category in a <code>category_key</code> column.+ </p>+ <p className="mb-0 text-muted">+ Importing never opts anyone back in, so it's safe to upload the same file twice. A file exported+ from here imports back as-is.+ </p>+ {csvFile ? (+ <div className="flex items-center justify-between border rounded p-3">+ <div>+ <div className="font-medium text-sm">{csvFile.name}</div>+ <div className="text-xs text-muted">{(csvFile.size / 1024).toFixed(1)} KB</div>+ </div>+ <LemonButton size="small" type="secondary" onClick={() => setCsvFile(null)}>+ Remove+ </LemonButton>+ </div>+ ) : (+ <LemonFileInput+ accept=".csv"+ multiple={false}+ value={[]}+ onChange={(files) => setCsvFile(files[0] || null)}+ showUploadedFiles={false}+ callToAction={+ <div className="border-2 border-dashed border-border rounded-lg p-4 text-center hover:border-primary-light transition-colors cursor-pointer w-full">+ <div className="text-sm text-muted">Drop a CSV file here or click to browse</div>+ </div>+ }+ />+ )}+ {csvImportResultLoading && csvImportProgress && csvImportProgress.total > 1000 && (+ <div className="text-sm text-muted">+ Processed {csvImportProgress.processed.toLocaleString()} of{' '}+ {csvImportProgress.total.toLocaleString()} recipients+ </div>+ )}+ {csvImportResult && (+ <LemonBanner type={csvImportResult.errors.length > 0 ? 'warning' : 'success'}>+ <div>+ Added {csvImportResult.opted_out.toLocaleString()} opt-outs from{' '}+ {csvImportResult.total.toLocaleString()} rows.+ {csvImportResult.skipped > 0 &&+ ` Skipped ${csvImportResult.skipped.toLocaleString()} rows.`}+ </div>+ {csvImportResult.errors.length > 0 && (+ <ul className="mt-2 mb-0 text-xs">+ {csvImportResult.errors.map((error) => (+ <li key={error}>{error}</li>+ ))}+ </ul>+ )}+ </LemonBanner>+ )}+ </div>+ </LemonModal></>)}diff --git a/products/workflows/frontend/OptOuts/optOutCsvImport.test.ts b/products/workflows/frontend/OptOuts/optOutCsvImport.test.tsnew file mode 100644index 000000000000..0514f255b025--- /dev/null+++ b/products/workflows/frontend/OptOuts/optOutCsvImport.test.ts@@ -0,0 +1,67 @@+import { parseOptOutRows, remapEntryErrors } from './optOutCsvImport'++describe('optOutCsvImport', () => {+ describe('parseOptOutRows', () => {+ it.each(['identifier', 'email', 'recipient', 'email_address', ' Email '])(+ 'accepts "%s" as the recipient column',+ (column) => {+ const parsed = parseOptOutRows([[column], ['[email protected]']])++ expect(parsed.entries).toEqual([{ identifier: '[email protected]', category_key: undefined, row: 2 }])+ expect(parsed.total).toBe(1)+ }+ )++ it('reports a missing recipient column instead of importing nothing silently', () => {+ const parsed = parseOptOutRows([['name'], ['Ally']])++ expect(parsed.entries).toEqual([])+ expect(parsed.errors).toHaveLength(1)+ expect(parsed.errors[0]).toContain('No recipient column found')+ })++ // The export quote-prefixes formula-leading identifiers so spreadsheets don't evaluate+ // them; the round trip only works if parsing strips that escape back off. A quote not+ // followed by a formula trigger is a real identifier and must survive.+ it.each([+ { value: "'=SUM(A1:B1)", expected: '=SUM(A1:B1)' },+ { value: "'+15551234567", expected: '+15551234567' },+ { value: "'[email protected]", expected: "'[email protected]" },+ ])('unescapes the formula-neutralizing quote prefix in "$value"', ({ value, expected }) => {+ const parsed = parseOptOutRows([['identifier'], [value]])++ expect(parsed.entries).toEqual([{ identifier: expected, category_key: undefined, row: 2 }])+ })++ it('reads the category column and skips rows missing a recipient, keeping file row numbers', () => {+ const parsed = parseOptOutRows([+ ['email', 'category_key'],+ ['[email protected]', 'newsletter'],+ ['', 'newsletter'],+ [' ', ''],+ ['[email protected]', ''],+ ])++ expect(parsed.entries).toEqual([+ { identifier: '[email protected]', category_key: 'newsletter', row: 2 },+ { identifier: '[email protected]', category_key: undefined, row: 5 },+ ])+ expect(parsed.total).toBe(3)+ expect(parsed.skipped).toBe(1)+ expect(parsed.errors).toEqual(['Row 3: missing a recipient'])+ })+ })++ describe('remapEntryErrors', () => {+ it('rewrites entry numbers to the file rows the entries came from', () => {+ const chunk = [+ { identifier: '[email protected]', row: 1002 },+ { identifier: '[email protected]', row: 1003 },+ ]++ expect(+ remapEntryErrors(["Entry 2: no message category with key 'nope'", 'Unrelated error'], chunk)+ ).toEqual(["Row 1003: no message category with key 'nope'", 'Unrelated error'])+ })+ })+})diff --git a/products/workflows/frontend/OptOuts/optOutCsvImport.ts b/products/workflows/frontend/OptOuts/optOutCsvImport.tsnew file mode 100644index 000000000000..96ce8e6aa365--- /dev/null+++ b/products/workflows/frontend/OptOuts/optOutCsvImport.ts@@ -0,0 +1,87 @@+// Mirrors the column aliases the old server-side CSV import accepted, so a list+// exported from another messaging tool still imports without being reshaped.+export const RECIPIENT_COLUMNS = ['identifier', 'email', 'recipient', 'email_address']+export const CATEGORY_COLUMNS = ['category_key', 'category']++export const BULK_OPT_OUT_CHUNK_SIZE = 1000+export const MAX_REPORTED_ERRORS = 10++export interface ParsedOptOutEntry {+ identifier: string+ category_key?: string+ /** 1-based row number in the source file, header included, for error messages. */+ row: number+}++export interface ParsedOptOutCsv {+ entries: ParsedOptOutEntry[]+ /** Non-empty data rows in the file. */+ total: number+ skipped: number+ errors: string[]+}++// The export quote-prefixes cells starting with these so spreadsheets don't evaluate them+// as formulas (see posthog/security/spreadsheet_safety.py). Reversed here so a file+// exported from PostHog imports back with the original identifiers.+const FORMULA_TRIGGER_CHARS = ['=', '+', '-', '@', '\t', '\r']++function unescapeFormulaPrefix(value: string): string {+ return value.startsWith("'") && FORMULA_TRIGGER_CHARS.includes(value[1]) ? value.slice(1) : value+}++/** Turn parsed CSV rows (header first) into opt-out entries, mirroring the old server-side rules. */+export function parseOptOutRows(rows: string[][]): ParsedOptOutCsv {+ if (rows.length === 0) {+ return { entries: [], total: 0, skipped: 0, errors: ['The file is empty'] }+ }+ const header = rows[0].map((column) => column.trim().toLowerCase())+ const identifierIndex = RECIPIENT_COLUMNS.map((column) => header.indexOf(column)).find((index) => index >= 0)+ if (identifierIndex === undefined) {+ return {+ entries: [],+ total: 0,+ skipped: 0,+ errors: [`No recipient column found. Add a column named one of: ${RECIPIENT_COLUMNS.join(', ')}`],+ }+ }+ const categoryIndex = CATEGORY_COLUMNS.map((column) => header.indexOf(column)).find((index) => index >= 0)++ const entries: ParsedOptOutEntry[] = []+ let total = 0+ let skipped = 0+ const errors: string[] = []++ for (let i = 1; i < rows.length; i++) {+ const row = rows[i]+ if (!row.some((cell) => cell.trim())) {+ continue+ }+ total += 1+ const rowNumber = i + 1++ const identifier = unescapeFormulaPrefix(row[identifierIndex]?.trim() ?? '')+ if (!identifier) {+ skipped += 1+ if (errors.length < MAX_REPORTED_ERRORS) {+ errors.push(`Row ${rowNumber}: missing a recipient`)+ }+ continue+ }++ const categoryKey = categoryIndex !== undefined ? row[categoryIndex]?.trim() : undefined+ entries.push({ identifier, category_key: categoryKey || undefined, row: rowNumber })+ }++ return { entries, total, skipped, errors }+}++/** Rewrite the API's "Entry N" errors to name the file row the entry came from. */+export function remapEntryErrors(errors: string[], chunk: ParsedOptOutEntry[]): string[] {+ return errors.map((error) =>+ error.replace(/^Entry (\d+)/, (match, entryNumber) => {+ const entry = chunk[Number(entryNumber) - 1]+ return entry ? `Row ${entry.row}` : match+ })+ )+}diff --git a/products/workflows/frontend/OptOuts/optOutListLogic.ts b/products/workflows/frontend/OptOuts/optOutListLogic.tsindex b9f76024a6f1..44da14e766bc 100644--- a/products/workflows/frontend/OptOuts/optOutListLogic.ts+++ b/products/workflows/frontend/OptOuts/optOutListLogic.ts@@ -1,14 +1,29 @@import { MakeLogicType, actions, afterMount, connect, kea, key, path, props, reducers } from 'kea'import { loaders } from 'kea-loaders'+import Papa from 'papaparse'import { lemonToast } from '@posthog/lemon-ui'import api, { CountedPaginatedResponse } from 'lib/api'+import { downloadFile } from 'lib/utils/dom'++import type { BulkAddOptOutsResultApi } from 'products/messaging/frontend/generated/api.schemas'import { MessageCategory } from './optOutCategoriesLogic'+import { BULK_OPT_OUT_CHUNK_SIZE, MAX_REPORTED_ERRORS, parseOptOutRows, remapEntryErrors } from './optOutCsvImport'import { optOutSceneLogic } from './optOutSceneLogic'import type { OptOutEntry, OptOutPersonPreference } from './types'+async function parseCsvFile(file: File): Promise<string[][]> {+ return new Promise((resolve, reject) => {+ Papa.parse<string[]>(file, {+ skipEmptyLines: 'greedy',+ complete: (results) => resolve(results.data),+ error: (error: Error) => reject(error),+ })+ })+}+export type { OptOutEntry, OptOutPersonPreference }export type PaginatedOptOuts = CountedPaginatedResponse<OptOutEntry>@@ -22,6 +37,12 @@ export interface optOutListLogicValues {preferencesUrlLoading: boolean // optOutSceneLogicaddOptOut: OptOutEntry | nulladdOptOutLoading: boolean+ csvExport: null+ csvExportLoading: boolean+ csvFile: File | null+ csvImportProgress: { processed: number; total: number } | null+ csvImportResult: BulkAddOptOutsResultApi | null+ csvImportResultLoading: booleancurrentPage: numbermanagePreferencesModalOpen: booleannewOptOutIdentifier: string@@ -30,6 +51,7 @@ export interface optOutListLogicValues {personsModalOpen: booleanselectedIdentifier: string | nullshowAddOptOutModal: boolean+ showImportCsvModal: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -50,6 +72,51 @@ export interface optOutListLogicActions {addOptOut: OptOutEntrypayload?: string}+ clearCsvImportResult: () => any+ clearCsvImportResultFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ clearCsvImportResultSuccess: (+ csvImportResult: BulkAddOptOutsResultApi | null,+ payload?: any+ ) => {+ csvImportResult: BulkAddOptOutsResultApi | null+ payload?: any+ }+ exportCsv: () => any+ exportCsvFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ exportCsvSuccess: (+ csvExport: null,+ payload?: any+ ) => {+ csvExport: null+ payload?: any+ }+ importCsv: () => any+ importCsvFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ importCsvSuccess: (+ csvImportResult: BulkAddOptOutsResultApi | null,+ payload?: any+ ) => {+ csvImportResult: BulkAddOptOutsResultApi | null+ payload?: any+ }loadNextPage: () => {value: true}@@ -110,6 +177,12 @@ export interface optOutListLogicActions {loadUnsubscribeLink: () => {value: true}+ setCsvFile: (file: File | null) => {+ file: File | null+ }+ setCsvImportProgress: (progress: { processed: number; total: number } | null) => {+ progress: { processed: number; total: number } | null+ }setCurrentPage: (page: number) => {page: number}@@ -128,6 +201,9 @@ export interface optOutListLogicActions {setShowAddOptOutModal: (show: boolean) => {show: boolean}+ setShowImportCsvModal: (show: boolean) => {+ show: boolean+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -160,6 +236,9 @@ export const optOutListLogic = kea<optOutListLogicType>([loadPreviousPage: true,setShowAddOptOutModal: (show: boolean) => ({ show }),setNewOptOutIdentifier: (identifier: string) => ({ identifier }),+ setShowImportCsvModal: (show: boolean) => ({ show }),+ setCsvFile: (file: File | null) => ({ file }),+ setCsvImportProgress: (progress: { processed: number; total: number } | null) => ({ progress }),}),reducers({personsModalOpen: [@@ -216,6 +295,31 @@ export const optOutListLogic = kea<optOutListLogicType>([setShowAddOptOutModal: (state, { show }) => (show ? state : ''),},],+ showImportCsvModal: [+ false,+ {+ setShowImportCsvModal: (_, { show }) => show,+ },+ ],+ csvFile: [+ null as File | null,+ {+ setCsvFile: (_, { file }) => file,+ setShowImportCsvModal: () => null,+ // Clear the picked file once an import produced a result, so the drop zone+ // is ready for the next file; keep it when the file couldn't be read at all.+ importCsvSuccess: (state, { csvImportResult }) => (csvImportResult ? null : state),+ },+ ],+ csvImportProgress: [+ null as { processed: number; total: number } | null,+ {+ setCsvImportProgress: (_, { progress }) => progress,+ importCsvSuccess: () => null,+ importCsvFailure: () => null,+ clearCsvImportResult: () => null,+ },+ ],}),loaders(({ props, values, actions }) => ({addOptOut: {@@ -263,6 +367,86 @@ export const optOutListLogic = kea<optOutListLogicType>([}},},+ csvExport: {+ __default: null as null,+ exportCsv: async (): Promise<null> => {+ try {+ const blob = await api.messaging.exportOptOutsCsv(props.category?.key)+ downloadFile(new File([blob], `opt-outs-${props.category?.key ?? 'all-marketing'}.csv`))+ } catch {+ lemonToast.error('Failed to export opt-outs')+ }+ return null+ },+ },+ csvImportResult: {+ __default: null as BulkAddOptOutsResultApi | null,+ clearCsvImportResult: (): BulkAddOptOutsResultApi | null => null,+ importCsv: async (): Promise<BulkAddOptOutsResultApi | null> => {+ const file = values.csvFile+ if (!file) {+ return null+ }++ let rows: string[][]+ try {+ rows = await parseCsvFile(file)+ } catch {+ lemonToast.error("Couldn't read the file. Check that it's a valid CSV and try again.")+ return null+ }++ const parsed = parseOptOutRows(rows)+ const result: BulkAddOptOutsResultApi = {+ total: parsed.total,+ opted_out: 0,+ skipped: parsed.skipped,+ errors: [...parsed.errors],+ }++ if (parsed.entries.length > 0) {+ actions.setCsvImportProgress({ processed: 0, total: parsed.entries.length })+ }+ for (let start = 0; start < parsed.entries.length; start += BULK_OPT_OUT_CHUNK_SIZE) {+ const chunk = parsed.entries.slice(start, start + BULK_OPT_OUT_CHUNK_SIZE)+ try {+ const chunkResult = await api.messaging.bulkAddOptOuts(+ chunk.map(({ identifier, category_key }) => ({ identifier, category_key })),+ props.category?.key+ )+ result.opted_out += chunkResult.opted_out+ result.skipped += chunkResult.skipped+ for (const error of remapEntryErrors(chunkResult.errors, chunk)) {+ if (result.errors.length < MAX_REPORTED_ERRORS) {+ result.errors.push(error)+ }+ }+ } catch (e: any) {+ // Already-applied chunks stay applied; re-uploading is safe because+ // importing only ever opts recipients out.+ const remaining = parsed.entries.length - start+ result.errors.push(+ e?.error ||+ e?.detail ||+ `The import stopped with ${remaining.toLocaleString()} recipients left. Upload the same file again to finish. Recipients that were already imported stay opted out.`+ )+ break+ }+ actions.setCsvImportProgress({+ processed: Math.min(start + BULK_OPT_OUT_CHUNK_SIZE, parsed.entries.length),+ total: parsed.entries.length,+ })+ }++ if (result.opted_out > 0) {+ lemonToast.success(`Added ${result.opted_out.toLocaleString()} opt-outs`)+ actions.loadOptOutPersons()+ } else {+ lemonToast.warning('No opt-outs were added. Check the file and try again.')+ }+ return result+ },+ },})),afterMount(({ props, actions }) => {// If no category is provided or it's a marketing category, load opt-out personsdiff --git a/products/workflows/package.json b/products/workflows/package.jsonindex 810a32fe4937..e250226db894 100644--- a/products/workflows/package.json+++ b/products/workflows/package.json@@ -12,6 +12,7 @@"kea-loaders": "catalog:","kea-router": "catalog:","kea-subscriptions": "catalog:",+ "papaparse": "^5.4.1","posthog-js": "catalog:","use-debounce": "catalog:","zod": "^4.0.0"@@ -19,6 +20,7 @@"devDependencies": {"@storybook/react": "catalog:","@testing-library/react": "*",+ "@types/papaparse": "*","kea-test-utils": "catalog:"},"peerDependencies": {diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 921ee3620e9d..7fa0d4de01d4 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -6752,6 +6752,34 @@},"feature_flag": "revamped-py-notebooks"},+ "opt-outs-add": {+ "description": "Opt one or more recipients (up to 1000 per call) out of marketing messages. Each entry can name its own message category via category_key; entries without one use the request-level category_key, or all marketing messages if omitted. Importing only ever opts recipients out, so repeating a call is safe.",+ "category": "Messaging",+ "feature": "messaging",+ "summary": "Add recipients to the opt-out list",+ "title": "Add recipients to the opt-out list",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "opt-outs-list": {+ "description": "List recipients opted out of a message category, most recently updated first. Omit category_key to list recipients opted out of all marketing messages.",+ "category": "Messaging",+ "feature": "messaging",+ "summary": "List opt-outs",+ "title": "List opt-outs",+ "required_scopes": ["hog_flow:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"org-member-get-github-login": {"description": "Resolve the GitHub username (login) for a single organization member, given their PostHog user UUID (obtainable from org-members-list, or \"@me\" for the current user). Returns null if the member has no GitHub identity linked. Use this when you know which member you want and need their GitHub handle — for example to set suggested reviewers.","category": "Platform Features",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 75b512385f3b..c3ba80995550 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -7278,6 +7278,34 @@"readOnlyHint": false}},+ "opt-outs-add": {+ "description": "Opt one or more recipients (up to 1000 per call) out of marketing messages. Each entry can name its own message category via category_key; entries without one use the request-level category_key, or all marketing messages if omitted. Importing only ever opts recipients out, so repeating a call is safe.",+ "category": "Messaging",+ "feature": "messaging",+ "summary": "Add recipients to the opt-out list",+ "title": "Add recipients to the opt-out list",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "opt-outs-list": {+ "description": "List recipients opted out of a message category, most recently updated first. Omit category_key to list recipients opted out of all marketing messages.",+ "category": "Messaging",+ "feature": "messaging",+ "summary": "List opt-outs",+ "title": "List opt-outs",+ "required_scopes": ["hog_flow:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"org-member-get-github-login": {"description": "Resolve the GitHub username (login) for a single organization member, given their PostHog user UUID (obtainable from org-members-list, or \"@me\" for the current user). Returns null if the member has no GitHub identity linked. Use this when you know which member you want and need their GitHub handle — for example to set suggested reviewers.","category": "Platform Features",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 629f29d6e26f..bc75cf799e1a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -12515,6 +12515,34 @@ export namespace Schemas {Failed: 'failed',} as const;+ export interface BulkOptOutEntry {+ /**+ * The recipient identifier to opt out (e.g. email address).+ * @maxLength 512+ */+ identifier: string;+ /** Message category key for this recipient. Overrides the request-level category_key. */+ category_key?: string;+ }++ export interface BulkAddOptOutsRequest {+ /** Recipients to opt out, at most 1000 per request. */+ opt_outs: BulkOptOutEntry[];+ /** Message category key applied to entries without their own. If omitted, recipients are opted out of all marketing messages. */+ category_key?: string;+ }++ export interface BulkAddOptOutsResult {+ /** Number of opt-out entries received. */+ total: number;+ /** Number of recipient and category pairs recorded as opted out. */+ opted_out: number;+ /** Number of entries skipped because their category_key doesn't exist. */+ skipped: number;+ /** The first few entry-level problems, so the caller can fix their list. */+ errors: string[];+ }+/*** * `fully_rolled_out` - fully_rolled_out* * `not_rolled_out` - not_rolled_out@@ -42587,6 +42615,11 @@ export namespace Schemas {deleted?: boolean;}+ export interface MessagingError {+ /** Human-readable description of what went wrong. */+ error: string;+ }+/*** * `viewed` - viewed*/@@ -45569,6 +45602,26 @@ export namespace Schemas {results: ObjectMediaPreview[];}+ /**+ * OpenAPI shape for the paginated opt-outs response, so the generated clients get the+ * {count, next, previous, results} envelope instead of an untyped object.+ */+ export interface PaginatedOptOuts {+ /** Total number of opted-out recipients for the category. */+ count: number;+ /**+ * URL for the next page, or null on the last page.+ * @nullable+ */+ next: string | null;+ /**+ * URL for the previous page, or null on the first page.+ * @nullable+ */+ previous: string | null;+ results: MessagePreferences[];+ }+export interface PaginatedOrganizationDomainList {count: number;/** @nullable */@@ -83233,6 +83286,22 @@ export namespace Schemas {offset?: number;};+ export type MessagingPreferencesExportOptOutsCsvRetrieveParams = {+ /**+ * Message category key to export. If omitted, exports recipients opted out of all marketing messages.+ */+ category_key?: string;+ };++ export type MessagingPreferencesOptOutsRetrieveParams = {+ /**+ * Message category key to list opt-outs for. If omitted, lists recipients opted out of all marketing messages.+ */+ category_key?: string;+ page?: number;+ page_size?: number;+ };+export type MessagingSuppressionsSuppressionsRetrieveParams = {page?: number;page_size?: number;diff --git a/services/mcp/src/generated/messaging/api.ts b/services/mcp/src/generated/messaging/api.tsnew file mode 100644index 000000000000..b6612af0f2cd--- /dev/null+++ b/services/mcp/src/generated/messaging/api.ts@@ -0,0 +1,69 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * MCP service uses these Zod schemas for generated tool handlers.+ * To regenerate: hogli build:openapi+ *+ * PostHog API - MCP 2 enabled ops+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++/**+ * Opt every recipient in the list out of the category named on their entry, or a default category.+ * @summary Add multiple recipients to the opt-out list+ */+export const MessagingPreferencesBulkAddOptOutsCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "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 messagingPreferencesBulkAddOptOutsCreateBodyOptOutsItemIdentifierMax = 512++export const MessagingPreferencesBulkAddOptOutsCreateBody = /* @__PURE__ */ zod.object({+ opt_outs: zod+ .array(+ zod.object({+ identifier: zod+ .string()+ .max(messagingPreferencesBulkAddOptOutsCreateBodyOptOutsItemIdentifierMax)+ .describe('The recipient identifier to opt out (e.g. email address).'),+ category_key: zod+ .string()+ .optional()+ .describe('Message category key for this recipient. Overrides the request-level category_key.'),+ })+ )+ .describe('Recipients to opt out, at most 1000 per request.'),+ category_key: zod+ .string()+ .optional()+ .describe(+ 'Message category key applied to entries without their own. If omitted, recipients are opted out of all marketing messages.'+ ),+})++/**+ * Get opt-outs filtered by category or overall opt-outs if no category specified+ * @summary List recipients opted out of a message category+ */+export const MessagingPreferencesOptOutsRetrieveParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "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 MessagingPreferencesOptOutsRetrieveQueryParams = /* @__PURE__ */ zod.object({+ category_key: zod+ .string()+ .optional()+ .describe(+ 'Message category key to list opt-outs for. If omitted, lists recipients opted out of all marketing messages.'+ ),+ page: zod.number().optional(),+ page_size: zod.number().optional(),+})diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.tsindex dcb9e9bb8852..4cf8c8c494c5 100644--- a/services/mcp/src/tools/generated/index.ts+++ b/services/mcp/src/tools/generated/index.ts@@ -34,6 +34,7 @@ import { GENERATED_TOOLS as managed_migrations } from './managed_migrations'import { GENERATED_TOOLS as marketing_analytics } from './marketing_analytics'import { GENERATED_TOOLS as mcp_analytics } from './mcp_analytics'import { GENERATED_TOOLS as mcp_store } from './mcp_store'+import { GENERATED_TOOLS as messaging } from './messaging'import { GENERATED_TOOLS as metrics } from './metrics'import { GENERATED_TOOLS as notebooks } from './notebooks'import { GENERATED_TOOLS as persons } from './persons'@@ -93,6 +94,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =...marketing_analytics,...mcp_analytics,...mcp_store,+ ...messaging,...metrics,...notebooks,...persons,diff --git a/services/mcp/src/tools/generated/messaging.ts b/services/mcp/src/tools/generated/messaging.tsnew file mode 100644index 000000000000..00ecbd63311f--- /dev/null+++ b/services/mcp/src/tools/generated/messaging.ts@@ -0,0 +1,57 @@+// AUTO-GENERATED from products/messaging/mcp/tools.yaml + OpenAPI — do not edit+import { z } from 'zod'++import type { Schemas } from '@/api/generated'+import {+ MessagingPreferencesBulkAddOptOutsCreateBody,+ MessagingPreferencesOptOutsRetrieveQueryParams,+} from '@/generated/messaging/api'+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'++const OptOutsAddSchema = MessagingPreferencesBulkAddOptOutsCreateBody++const optOutsAdd = (): ToolBase<typeof OptOutsAddSchema, Schemas.BulkAddOptOutsResult> => ({+ name: 'opt-outs-add',+ schema: OptOutsAddSchema,+ handler: async (context: Context, params: z.infer<typeof OptOutsAddSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.opt_outs !== undefined) {+ body['opt_outs'] = params.opt_outs+ }+ if (params.category_key !== undefined) {+ body['category_key'] = params.category_key+ }+ const result = await context.api.request<Schemas.BulkAddOptOutsResult>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_preferences/bulk_add_opt_outs/`,+ body,+ })+ return result+ },+})++const OptOutsListSchema = MessagingPreferencesOptOutsRetrieveQueryParams++const optOutsList = (): ToolBase<typeof OptOutsListSchema, Schemas.PaginatedOptOuts> => ({+ name: 'opt-outs-list',+ schema: OptOutsListSchema,+ handler: async (context: Context, params: z.infer<typeof OptOutsListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedOptOuts>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_preferences/opt_outs/`,+ query: {+ category_key: params.category_key,+ page: params.page,+ page_size: params.page_size,+ },+ })+ return result+ },+})++export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'opt-outs-add': optOutsAdd,+ 'opt-outs-list': optOutsList,+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/opt-outs-add.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/opt-outs-add.jsonnew file mode 100644index 000000000000..ef383a5faefd--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/opt-outs-add.json@@ -0,0 +1,30 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "category_key": {+ "description": "Message category key applied to entries without their own. If omitted, recipients are opted out of all marketing messages.",+ "type": "string"+ },+ "opt_outs": {+ "description": "Recipients to opt out, at most 1000 per request.",+ "items": {+ "properties": {+ "category_key": {+ "description": "Message category key for this recipient. Overrides the request-level category_key.",+ "type": "string"+ },+ "identifier": {+ "description": "The recipient identifier to opt out (e.g. email address).",+ "maxLength": 512,+ "type": "string"+ }+ },+ "required": ["identifier"],+ "type": "object"+ },+ "type": "array"+ }+ },+ "required": ["opt_outs"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/opt-outs-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/opt-outs-list.jsonnew file mode 100644index 000000000000..5ff56fd25f14--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/opt-outs-list.json@@ -0,0 +1,16 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "category_key": {+ "description": "Message category key to list opt-outs for. If omitted, lists recipients opted out of all marketing messages.",+ "type": "string"+ },+ "page": {+ "type": "number"+ },+ "page_size": {+ "type": "number"+ }+ },+ "type": "object"+}