: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(customer-analytics): Implement account tagging (#59465)
Arthur Moreira de Deusd0670f2c9ec2
diff --git a/posthog/api/tagged_item.py b/posthog/api/tagged_item.pyindex 9ff40445ea83..bb22ab30383a 100644--- a/posthog/api/tagged_item.py+++ b/posthog/api/tagged_item.py@@ -384,3 +384,29 @@ def handle_tagged_item_change(],),)++ if related_object_type == "account" and related_object_id:+ account_tag_action: Literal["created", "deleted"] = "created" if activity == "created" else "deleted"+ log_activity(+ organization_id=tagged_item.tag.team.organization_id+ if tagged_item.tag and tagged_item.tag.team+ else None,+ team_id=tagged_item.tag.team_id if tagged_item.tag else None,+ user=user,+ was_impersonated=was_impersonated,+ item_id=related_object_id,+ scope="Account",+ activity="updated",+ detail=Detail(+ name=related_object_name,+ changes=[+ Change(+ type="Account",+ field="tag",+ action=account_tag_action,+ after=tagged_item.tag.name if activity == "created" else None,+ before=tagged_item.tag.name if activity == "deleted" else None,+ )+ ],+ ),+ )diff --git a/posthog/api/test/__snapshots__/test_feature_flag.ambr b/posthog/api/test/__snapshots__/test_feature_flag.ambrindex 16d14cd71edc..fb90556ddd3b 100644--- a/posthog/api/test/__snapshots__/test_feature_flag.ambr+++ b/posthog/api/test/__snapshots__/test_feature_flag.ambr@@ -1828,6 +1828,7 @@"posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id","posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id","posthog_tag"."id","posthog_tag"."name","posthog_tag"."team_id"diff --git a/posthog/api/test/__snapshots__/test_insight.ambr b/posthog/api/test/__snapshots__/test_insight.ambrindex f82d27b943a8..07459fdb1672 100644--- a/posthog/api/test/__snapshots__/test_insight.ambr+++ b/posthog/api/test/__snapshots__/test_insight.ambr@@ -2207,7 +2207,8 @@"posthog_taggeditem"."action_id","posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id"+ "posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id"FROM "posthog_taggeditem"WHERE "posthog_taggeditem"."insight_id" IN (1,2,@@ -2228,6 +2229,7 @@"posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id","posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id","posthog_tag"."id","posthog_tag"."name","posthog_tag"."team_id"diff --git a/posthog/api/test/__snapshots__/test_organization_feature_flag.ambr b/posthog/api/test/__snapshots__/test_organization_feature_flag.ambrindex 60b2f821096b..435037402a8c 100644--- a/posthog/api/test/__snapshots__/test_organization_feature_flag.ambr+++ b/posthog/api/test/__snapshots__/test_organization_feature_flag.ambr@@ -1131,7 +1131,8 @@"posthog_taggeditem"."action_id","posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id"+ "posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id"FROM "posthog_taggeditem"WHERE "posthog_taggeditem"."dashboard_id" = 99999'''@@ -1157,7 +1158,8 @@"posthog_taggeditem"."action_id","posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id"+ "posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id"FROM "posthog_taggeditem"WHERE "posthog_taggeditem"."dashboard_id" = 99999'''@@ -2995,7 +2997,8 @@"posthog_taggeditem"."action_id","posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id"+ "posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id"FROM "posthog_taggeditem"WHERE "posthog_taggeditem"."feature_flag_id" = 99999'''@@ -3011,7 +3014,8 @@"posthog_taggeditem"."action_id","posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id"+ "posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id"FROM "posthog_taggeditem"WHERE "posthog_taggeditem"."feature_flag_id" = 99999'''diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambrindex 7e3fce966229..d0911a60227d 100644--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr@@ -2134,6 +2134,7 @@"posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id","posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id","posthog_tag"."id","posthog_tag"."name","posthog_tag"."team_id"@@ -2729,6 +2730,7 @@"posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id","posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id","posthog_tag"."id","posthog_tag"."name","posthog_tag"."team_id"@@ -4684,6 +4686,7 @@"posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id","posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id","posthog_tag"."id","posthog_tag"."name","posthog_tag"."team_id"@@ -9882,6 +9885,7 @@"posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id","posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id","posthog_tag"."id","posthog_tag"."name","posthog_tag"."team_id"@@ -10459,6 +10463,7 @@"posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id","posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id","posthog_tag"."id","posthog_tag"."name","posthog_tag"."team_id"@@ -15287,6 +15292,7 @@"posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id","posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id","posthog_tag"."id","posthog_tag"."name","posthog_tag"."team_id"@@ -18376,6 +18382,7 @@"posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id","posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id","posthog_tag"."id","posthog_tag"."name","posthog_tag"."team_id"diff --git a/posthog/migrations/1172_remove_taggeditem_exactly_one_related_object_and_more.py b/posthog/migrations/1172_remove_taggeditem_exactly_one_related_object_and_more.pynew file mode 100644index 000000000000..1aaa01046d39--- /dev/null+++ b/posthog/migrations/1172_remove_taggeditem_exactly_one_related_object_and_more.py@@ -0,0 +1,224 @@+# Generated by Django 5.2.14 on 2026-05-20 17:41++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0005_account"),+ ("posthog", "1171_backfill_credentials_reviewed_at"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.RemoveConstraint(+ model_name="taggeditem",+ name="exactly_one_related_object",+ ),+ migrations.AlterUniqueTogether(+ name="taggeditem",+ unique_together=set(),+ ),+ migrations.AddField(+ model_name="taggeditem",+ name="account",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="tagged_items",+ to="customer_analytics.account",+ ),+ ),+ migrations.AlterUniqueTogether(+ name="taggeditem",+ unique_together={+ (+ "tag",+ "dashboard",+ "insight",+ "event_definition",+ "property_definition",+ "action",+ "feature_flag",+ "experiment_saved_metric",+ "ticket",+ "account",+ )+ },+ ),+ migrations.AddConstraint(+ model_name="taggeditem",+ constraint=models.UniqueConstraint(+ condition=models.Q(("account__isnull", False)),+ fields=("tag", "account"),+ name="unique_account_tagged_item",+ ),+ ),+ migrations.AddConstraint(+ model_name="taggeditem",+ constraint=models.CheckConstraint(+ condition=models.Q(+ models.Q(+ ("dashboard__isnull", False),+ ("insight__isnull", True),+ ("event_definition__isnull", True),+ ("property_definition__isnull", True),+ ("action__isnull", True),+ ("feature_flag__isnull", True),+ ("experiment_saved_metric__isnull", True),+ ("ticket__isnull", True),+ ("account__isnull", True),+ ),+ models.Q(+ ("dashboard__isnull", True),+ ("insight__isnull", False),+ ("event_definition__isnull", True),+ ("property_definition__isnull", True),+ ("action__isnull", True),+ ("feature_flag__isnull", True),+ ("experiment_saved_metric__isnull", True),+ ("ticket__isnull", True),+ ("account__isnull", True),+ ),+ models.Q(+ ("dashboard__isnull", True),+ ("insight__isnull", True),+ ("event_definition__isnull", False),+ ("property_definition__isnull", True),+ ("action__isnull", True),+ ("feature_flag__isnull", True),+ ("experiment_saved_metric__isnull", True),+ ("ticket__isnull", True),+ ("account__isnull", True),+ ),+ models.Q(+ ("dashboard__isnull", True),+ ("insight__isnull", True),+ ("event_definition__isnull", True),+ ("property_definition__isnull", False),+ ("action__isnull", True),+ ("feature_flag__isnull", True),+ ("experiment_saved_metric__isnull", True),+ ("ticket__isnull", True),+ ("account__isnull", True),+ ),+ models.Q(+ ("dashboard__isnull", True),+ ("insight__isnull", True),+ ("event_definition__isnull", True),+ ("property_definition__isnull", True),+ ("action__isnull", False),+ ("feature_flag__isnull", True),+ ("experiment_saved_metric__isnull", True),+ ("ticket__isnull", True),+ ("account__isnull", True),+ ),+ models.Q(+ ("dashboard__isnull", True),+ ("insight__isnull", True),+ ("event_definition__isnull", True),+ ("property_definition__isnull", True),+ ("action__isnull", True),+ ("feature_flag__isnull", False),+ ("experiment_saved_metric__isnull", True),+ ("ticket__isnull", True),+ ("account__isnull", True),+ ),+ models.Q(+ ("dashboard__isnull", True),+ ("insight__isnull", True),+ ("event_definition__isnull", True),+ ("property_definition__isnull", True),+ ("action__isnull", True),+ ("feature_flag__isnull", True),+ ("experiment_saved_metric__isnull", False),+ ("ticket__isnull", True),+ ("account__isnull", True),+ ),+ models.Q(+ ("dashboard__isnull", True),+ ("insight__isnull", True),+ ("event_definition__isnull", True),+ ("property_definition__isnull", True),+ ("action__isnull", True),+ ("feature_flag__isnull", True),+ ("experiment_saved_metric__isnull", True),+ ("ticket__isnull", False),+ ("account__isnull", True),+ ),+ models.Q(+ ("dashboard__isnull", True),+ ("insight__isnull", True),+ ("event_definition__isnull", True),+ ("property_definition__isnull", True),+ ("action__isnull", True),+ ("feature_flag__isnull", True),+ ("experiment_saved_metric__isnull", True),+ ("ticket__isnull", True),+ ("account__isnull", False),+ ),+ _connector="OR",+ ),+ name="exactly_one_related_object",+ ),+ ),+ ],+ database_operations=[+ migrations.RunSQL(+ sql="""+ ALTER TABLE "posthog_taggeditem"+ ADD COLUMN "account_id" uuid NULL+ CONSTRAINT "posthog_taggeditem_account_id_fk"+ REFERENCES "customer_analytics_account"("id")+ DEFERRABLE INITIALLY DEFERRED; -- existing-table-constraint-ignore+ SET CONSTRAINTS "posthog_taggeditem_account_id_fk" IMMEDIATE; -- existing-table-constraint-ignore+ """,+ reverse_sql="""+ ALTER TABLE "posthog_taggeditem" DROP COLUMN IF EXISTS "account_id";+ """,+ ),+ migrations.RunSQL(+ sql="""+ ALTER TABLE "posthog_taggeditem" DROP CONSTRAINT IF EXISTS "exactly_one_related_object";+ ALTER TABLE "posthog_taggeditem" ADD CONSTRAINT "exactly_one_related_object" CHECK ( /* -- existing-table-constraint-ignore */+ (+ (dashboard_id IS NOT NULL AND insight_id IS NULL AND event_definition_id IS NULL AND property_definition_id IS NULL AND action_id IS NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NULL AND account_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NOT NULL AND event_definition_id IS NULL AND property_definition_id IS NULL AND action_id IS NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NULL AND account_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NULL AND event_definition_id IS NOT NULL AND property_definition_id IS NULL AND action_id IS NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NULL AND account_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NULL AND event_definition_id IS NULL AND property_definition_id IS NOT NULL AND action_id IS NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NULL AND account_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NULL AND event_definition_id IS NULL AND property_definition_id IS NULL AND action_id IS NOT NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NULL AND account_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NULL AND event_definition_id IS NULL AND property_definition_id IS NULL AND action_id IS NULL AND feature_flag_id IS NOT NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NULL AND account_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NULL AND event_definition_id IS NULL AND property_definition_id IS NULL AND action_id IS NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NOT NULL AND ticket_id IS NULL AND account_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NULL AND event_definition_id IS NULL AND property_definition_id IS NULL AND action_id IS NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NOT NULL AND account_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NULL AND event_definition_id IS NULL AND property_definition_id IS NULL AND action_id IS NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NULL AND account_id IS NOT NULL) /* -- not-null-ignore */+ )+ ) NOT VALID;+ """,+ reverse_sql="""+ ALTER TABLE "posthog_taggeditem" DROP CONSTRAINT IF EXISTS "exactly_one_related_object";+ ALTER TABLE "posthog_taggeditem" ADD CONSTRAINT "exactly_one_related_object" CHECK ( /* -- existing-table-constraint-ignore */+ (+ (dashboard_id IS NOT NULL AND insight_id IS NULL AND event_definition_id IS NULL AND property_definition_id IS NULL AND action_id IS NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NOT NULL AND event_definition_id IS NULL AND property_definition_id IS NULL AND action_id IS NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NULL AND event_definition_id IS NOT NULL AND property_definition_id IS NULL AND action_id IS NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NULL AND event_definition_id IS NULL AND property_definition_id IS NOT NULL AND action_id IS NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NULL AND event_definition_id IS NULL AND property_definition_id IS NULL AND action_id IS NOT NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NULL AND event_definition_id IS NULL AND property_definition_id IS NULL AND action_id IS NULL AND feature_flag_id IS NOT NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NULL AND event_definition_id IS NULL AND property_definition_id IS NULL AND action_id IS NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NOT NULL AND ticket_id IS NULL) OR /* -- not-null-ignore */+ (dashboard_id IS NULL AND insight_id IS NULL AND event_definition_id IS NULL AND property_definition_id IS NULL AND action_id IS NULL AND feature_flag_id IS NULL AND experiment_saved_metric_id IS NULL AND ticket_id IS NOT NULL) /* -- not-null-ignore */+ )+ ) NOT VALID;+ """,+ ),+ migrations.RunSQL(+ sql="""+ ALTER TABLE "posthog_taggeditem" DROP CONSTRAINT IF EXISTS "posthog_taggeditem_tag_id_dashboard_id_insi_d90686d0_uniq";+ """,+ reverse_sql=migrations.RunSQL.noop,+ ),+ ],+ )+ ]diff --git a/posthog/migrations/1173_taggeditem_account_indexes.py b/posthog/migrations/1173_taggeditem_account_indexes.pynew file mode 100644index 000000000000..7c6cc624a4d7--- /dev/null+++ b/posthog/migrations/1173_taggeditem_account_indexes.py@@ -0,0 +1,62 @@+from django.db import migrations+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("posthog", "1172_remove_taggeditem_exactly_one_related_object_and_more"),+ ]++ operations = [+ migrations.RunSQL(+ sql="""+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "posthog_taggeditem_account_id_idx"+ ON "posthog_taggeditem" ("account_id");+ """,+ reverse_sql="""+ DROP INDEX IF EXISTS "posthog_taggeditem_account_id_idx";+ """,+ ),+ migrations.RunSQL(+ sql="""+ CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "unique_account_tagged_item"+ ON "posthog_taggeditem" ("tag_id", "account_id")+ WHERE "account_id" IS NOT NULL; -- not-null-ignore+ """,+ reverse_sql="""+ DROP INDEX IF EXISTS "unique_account_tagged_item";+ """,+ ),+ migrations.RunSQL(+ sql="""+ CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "posthog_taggeditem_tag_id_dashboard_id_insi_4fe7898b_uniq"+ ON "posthog_taggeditem" (+ "tag_id",+ "dashboard_id",+ "insight_id",+ "event_definition_id",+ "property_definition_id",+ "action_id",+ "feature_flag_id",+ "experiment_saved_metric_id",+ "ticket_id",+ "account_id"+ );+ """,+ reverse_sql="""+ CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "posthog_taggeditem_tag_id_dashboard_id_insi_d90686d0_uniq"+ ON "posthog_taggeditem" (+ "tag_id",+ "dashboard_id",+ "insight_id",+ "event_definition_id",+ "property_definition_id",+ "action_id",+ "feature_flag_id",+ "experiment_saved_metric_id",+ "ticket_id"+ );+ """,+ ),+ ]diff --git a/posthog/migrations/1174_taggeditem_account_unique_constraint.py b/posthog/migrations/1174_taggeditem_account_unique_constraint.pynew file mode 100644index 000000000000..52d24a4b5c84--- /dev/null+++ b/posthog/migrations/1174_taggeditem_account_unique_constraint.py@@ -0,0 +1,19 @@+from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1173_taggeditem_account_indexes"),+ ]++ operations = [+ migrations.RunSQL(+ sql="""+ ALTER TABLE "posthog_taggeditem" ADD CONSTRAINT "posthog_taggeditem_tag_id_dashboard_id_insi_4fe7898b_uniq"+ UNIQUE USING INDEX "posthog_taggeditem_tag_id_dashboard_id_insi_4fe7898b_uniq"; -- existing-table-constraint-ignore+ """,+ reverse_sql="""+ ALTER TABLE "posthog_taggeditem" DROP CONSTRAINT IF EXISTS "posthog_taggeditem_tag_id_dashboard_id_insi_4fe7898b_uniq";+ """,+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 21c87619460b..afcf22beea36 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1171_backfill_credentials_reviewed_at+1174_taggeditem_account_unique_constraintdiff --git a/posthog/models/tagged_item.py b/posthog/models/tagged_item.pyindex ab069c76a687..b80f8ff1581b 100644--- a/posthog/models/tagged_item.py+++ b/posthog/models/tagged_item.py@@ -13,6 +13,7 @@ RELATED_OBJECTS = ("feature_flag","experiment_saved_metric","ticket",+ "account",)@@ -91,6 +92,13 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):blank=True,related_name="tagged_items",)+ account = models.ForeignKey(+ "customer_analytics.Account",+ on_delete=models.CASCADE,+ null=True,+ blank=True,+ related_name="tagged_items",+ )class Meta:unique_together = ("tag", *RELATED_OBJECTS)diff --git a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambrindex 1771ed1bc7ff..c1799e1ccbcf 100644--- a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr+++ b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr@@ -148,7 +148,8 @@"posthog_taggeditem"."action_id","posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id"+ "posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id"FROM "posthog_taggeditem"WHERE "posthog_taggeditem"."feature_flag_id" = 99999'''@@ -164,7 +165,8 @@"posthog_taggeditem"."action_id","posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id"+ "posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id"FROM "posthog_taggeditem"WHERE "posthog_taggeditem"."feature_flag_id" = 99999'''@@ -866,7 +868,8 @@"posthog_taggeditem"."action_id","posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id"+ "posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id"FROM "posthog_taggeditem"WHERE "posthog_taggeditem"."feature_flag_id" = 99999'''@@ -882,7 +885,8 @@"posthog_taggeditem"."action_id","posthog_taggeditem"."feature_flag_id","posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id"+ "posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id"FROM "posthog_taggeditem"WHERE "posthog_taggeditem"."feature_flag_id" = 99999'''diff --git a/products/customer_analytics/backend/api/serializers.py b/products/customer_analytics/backend/api/serializers.pyindex f85bf8a88ab7..314b5daf099f 100644--- a/products/customer_analytics/backend/api/serializers.py+++ b/products/customer_analytics/backend/api/serializers.py@@ -4,6 +4,8 @@ from drf_spectacular.utils import extend_schema_fieldfrom pydantic import ValidationError as PydanticValidationErrorfrom rest_framework import serializers+from posthog.api.tagged_item import TaggedItemSerializerMixin+from products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfigfrom products.customer_analytics.backend.models.account import AccountProperties@@ -119,7 +121,9 @@ class CustomerJourneySerializer(serializers.ModelSerializer):raise Conflict("A customer journey already exists for this insight.")-class AccountSerializer(serializers.ModelSerializer):+class AccountSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):+ """A Customer Analytics account — a logical grouping used to assign customer-success ownership."""+name = serializers.CharField(max_length=400,help_text="Human-readable name of the account.",@@ -141,6 +145,11 @@ class AccountSerializer(serializers.ModelSerializer):"sfdc_id, zendesk_id). Defaults to an empty object. Unknown keys are rejected."),)+ tags = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ help_text="Tag names attached to the account. Pass a list to replace existing tags.",+ )class Meta:model = Account@@ -149,6 +158,7 @@ class AccountSerializer(serializers.ModelSerializer):"name","external_id","properties",+ "tags","created_at","created_by","updated_at",diff --git a/products/customer_analytics/backend/api/test_views.py b/products/customer_analytics/backend/api/test_views.pyindex e1a5c4e35a5b..ebc1f1c4516c 100644--- a/products/customer_analytics/backend/api/test_views.py+++ b/products/customer_analytics/backend/api/test_views.py@@ -5,7 +5,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.constants import AvailableFeature-from posthog.models import Insight+from posthog.models import Insight, Tag, TaggedItemfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Team@@ -639,6 +639,159 @@ class TestAccountViewSet(APIBaseTest):response = getattr(self.client, method.lower())(url, format="json")self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])+ def test_create_with_tags(self):+ response = self.client.post(+ self.endpoint_base,+ {"name": "Tagged Account", "tags": ["enterprise", "priority"]},+ format="json",+ )++ self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())+ self.assertEqual(sorted(response.json()["tags"]), ["enterprise", "priority"])+ # nosemgrep: idor-lookup-without-team (test assertion)+ account = Account.objects.unscoped().get(id=response.json()["id"])+ self.assertEqual(+ sorted(Tag.objects.filter(team=self.team).values_list("name", flat=True)),+ ["enterprise", "priority"],+ )+ self.assertEqual(+ sorted(TaggedItem.objects.filter(account=account).values_list("tag__name", flat=True)),+ ["enterprise", "priority"],+ )++ def test_retrieve_returns_tags(self):+ account = self._create_account()+ tag = Tag.objects.create(name="vip", team=self.team)+ account.tagged_items.create(tag=tag)++ response = self.client.get(f"{self.endpoint_base}{account.id}/")++ self.assertEqual(status.HTTP_200_OK, response.status_code)+ self.assertEqual(response.json()["tags"], ["vip"])++ def test_list_returns_tags(self):+ account = self._create_account()+ for name in ("alpha", "beta"):+ account.tagged_items.create(tag=Tag.objects.create(name=name, team=self.team))++ response = self.client.get(self.endpoint_base)++ self.assertEqual(status.HTTP_200_OK, response.status_code)+ results = {r["id"]: r for r in response.json()["results"]}+ self.assertEqual(sorted(results[str(account.id)]["tags"]), ["alpha", "beta"])++ def test_update_replaces_tags(self):+ account = self._create_account()+ account.tagged_items.create(tag=Tag.objects.create(name="old", team=self.team))++ response = self.client.patch(+ f"{self.endpoint_base}{account.id}/",+ {"tags": ["new"]},+ format="json",+ )++ self.assertEqual(status.HTTP_200_OK, response.status_code)+ self.assertEqual(response.json()["tags"], ["new"])+ self.assertEqual(list(account.tagged_items.values_list("tag__name", flat=True)), ["new"])++ def test_update_with_empty_tags_clears_them(self):+ account = self._create_account()+ account.tagged_items.create(tag=Tag.objects.create(name="stale", team=self.team))++ response = self.client.patch(f"{self.endpoint_base}{account.id}/", {"tags": []}, format="json")++ self.assertEqual(status.HTTP_200_OK, response.status_code)+ self.assertEqual(response.json()["tags"], [])+ self.assertFalse(account.tagged_items.exists())++ def test_list_filters_by_tags(self):+ billing_tag = Tag.objects.create(name="billing", team=self.team)+ urgent_tag = Tag.objects.create(name="urgent", team=self.team)+ churn_tag = Tag.objects.create(name="churn", team=self.team)++ billing = self._create_account(name="Billing Co")+ billing.tagged_items.create(tag=billing_tag)+ urgent = self._create_account(name="Urgent Co")+ urgent.tagged_items.create(tag=urgent_tag)+ churn = self._create_account(name="Churn Co")+ churn.tagged_items.create(tag=churn_tag)+ self._create_account(name="Untagged Co")++ response = self.client.get(f'{self.endpoint_base}?tags=["billing","urgent"]')++ self.assertEqual(status.HTTP_200_OK, response.status_code)+ names = {r["name"] for r in response.json()["results"]}+ self.assertEqual(names, {"Billing Co", "Urgent Co"})++ def test_list_tags_filter_returns_each_account_once_when_multiple_tags_match(self):+ billing_tag = Tag.objects.create(name="billing", team=self.team)+ urgent_tag = Tag.objects.create(name="urgent", team=self.team)+ account = self._create_account(name="Double Tagged")+ account.tagged_items.create(tag=billing_tag)+ account.tagged_items.create(tag=urgent_tag)++ response = self.client.get(f'{self.endpoint_base}?tags=["billing","urgent"]')++ self.assertEqual(status.HTTP_200_OK, response.status_code)+ self.assertEqual(response.json()["count"], 1)++ def test_list_ignores_malformed_tags_param(self):+ Tag.objects.create(name="billing", team=self.team)+ self._create_account(name="Account A")+ self._create_account(name="Account B")++ response = self.client.get(f"{self.endpoint_base}?tags=not-json")++ self.assertEqual(status.HTTP_200_OK, response.status_code)+ self.assertEqual(response.json()["count"], 2)++ def test_list_ignores_empty_tags_array(self):+ self._create_account(name="Account A")+ self._create_account(name="Account B")++ response = self.client.get(f"{self.endpoint_base}?tags=[]")++ self.assertEqual(status.HTTP_200_OK, response.status_code)+ self.assertEqual(response.json()["count"], 2)++ def test_list_with_tags_filter_does_not_n_plus_one(self):+ billing_tag = Tag.objects.create(name="billing", team=self.team)+ urgent_tag = Tag.objects.create(name="urgent", team=self.team)+ for i in range(10):+ account = self._create_account(name=f"Acct {i}")+ account.tagged_items.create(tag=billing_tag)+ account.tagged_items.create(tag=urgent_tag)++ with self.assertNumQueries(11):+ # Query budget for a tag-filtered account list. Constant regardless of result count+ # because tagged_items is prefetched once. If a query is added, please confirm it+ # does not scale with the number of accounts before raising the limit:+ # 1: load Django session+ # 2: load authenticated user+ # 3: load user's current organization+ # 4: load team for the requested project+ # 5: load org membership for permission checks+ # 6: load RBAC access controls for customer_analytics+ # 7: load org membership again for role inheritance+ # 8: load constance instance setting (rate limit config)+ # 9: COUNT(*) for pagination+ # 10: SELECT page of accounts filtered by tag name+ # 11: prefetch tagged_items + tag for the page (the prefetch that prevents N+1)+ response = self.client.get(f'{self.endpoint_base}?tags=["billing","urgent"]')++ self.assertEqual(status.HTTP_200_OK, response.status_code)+ self.assertEqual(response.json()["count"], 10)++ def test_tag_change_logs_to_account_activity_stream(self):+ account = self._create_account()+ initial_logs = ActivityLog.objects.filter(team_id=self.team.id, scope="Account", activity="updated").count()++ response = self.client.patch(f"{self.endpoint_base}{account.id}/", {"tags": ["audit"]}, format="json")+ self.assertEqual(status.HTTP_200_OK, response.status_code)++ new_logs = ActivityLog.objects.filter(team_id=self.team.id, scope="Account", activity="updated").count()+ self.assertGreater(new_logs, initial_logs)+@pytest.mark.eeclass TestCustomerAnalyticsAccessControl(APIBaseTest):diff --git a/products/customer_analytics/backend/api/views.py b/products/customer_analytics/backend/api/views.pyindex a6fe86f36279..b0fb52035a99 100644--- a/products/customer_analytics/backend/api/views.py+++ b/products/customer_analytics/backend/api/views.py@@ -1,7 +1,10 @@-from drf_spectacular.utils import extend_schema+import json++from drf_spectacular.utils import OpenApiParameter, OpenApiTypes, extend_schemafrom rest_framework import viewsetsfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.tagged_item import TaggedItemViewSetMixinfrom posthog.api.utils import log_activity_from_viewsetfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin@@ -60,13 +63,42 @@ class CustomerJourneyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin,@extend_schema(tags=["customer_analytics"])-class AccountViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):+class AccountViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):scope_object = "account"queryset = Account.objects.unscoped().order_by("-created_at")serializer_class = AccountSerializer+ bulk_update_tags = None # Mixin action assumes integer PKs; Account uses UUIDs.++ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="tags",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description=(+ 'JSON-encoded array of tag names to filter by, e.g. `["enterprise","priority"]`. '+ "Returns accounts that have any of the listed tags."+ ),+ ),+ ],+ )+ def list(self, request, *args, **kwargs):+ return super().list(request, *args, **kwargs)def safely_get_queryset(self, queryset):- return queryset.filter(team_id=self.team.id)+ queryset = queryset.filter(team_id=self.team.id)++ tags_param = self.request.query_params.get("tags")+ if tags_param:+ try:+ tags_list = json.loads(tags_param)+ except json.JSONDecodeError:+ return queryset+ if isinstance(tags_list, list) and tags_list:+ queryset = queryset.filter(tagged_items__tag__name__in=tags_list).distinct()++ return querysetdef perform_create(self, serializer):serializer.save()diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex be1fecfae5bb..ff77cd81842f 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -39,6 +39,9 @@ export type AccountApiProperties = {zendesk_id?: string | null} | null+/**+ * A Customer Analytics account — a logical grouping used to assign customer-success ownership.+ */export interface AccountApi {readonly id: string/**@@ -57,6 +60,8 @@ export interface AccountApi {* @nullable*/properties?: AccountApiProperties+ /** Tag names attached to the account. Pass a list to replace existing tags. */+ tags?: string[]readonly created_at: string/** @nullable */readonly created_by: number | null@@ -105,6 +110,9 @@ export type PatchedAccountApiProperties = {zendesk_id?: string | null} | null+/**+ * A Customer Analytics account — a logical grouping used to assign customer-success ownership.+ */export interface PatchedAccountApi {readonly id?: string/**@@ -123,6 +131,8 @@ export interface PatchedAccountApi {* @nullable*/properties?: PatchedAccountApiProperties+ /** Tag names attached to the account. Pass a list to replace existing tags. */+ tags?: string[]readonly created_at?: string/** @nullable */readonly created_by?: number | null@@ -339,6 +349,10 @@ export type AccountsListParams = {* The initial index from which to return the results.*/offset?: number+ /**+ * JSON-encoded array of tag names to filter by, e.g. `["enterprise","priority"]`. Returns accounts that have any of the listed tags.+ */+ tags?: string}export type CustomerJourneysListParams = {diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex febeca2432ed..6daa98e01c4a 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -13,130 +13,152 @@ export const accountsCreateBodyNameMax = 400export const accountsCreateBodyExternalIdMax = 400-export const AccountsCreateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(accountsCreateBodyNameMax).describe('Human-readable name of the account.'),- external_id: zod- .string()- .max(accountsCreateBodyExternalIdMax)- .nullish()- .describe('Identifier for the account in an external system (e.g. CRM ID). Optional.'),- properties: zod- .object({- csm: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_executive: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_owner: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- stripe_customer_id: zod.string().nullish(),- hubspot_deal_id: zod.string().nullish(),- billing_id: zod.string().nullish(),- sfdc_id: zod.string().nullish(),- zendesk_id: zod.string().nullish(),- })- .nullish()- .describe(- 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id). Defaults to an empty object. Unknown keys are rejected.'- ),-})+export const AccountsCreateBody = /* @__PURE__ */ zod+ .object({+ name: zod.string().max(accountsCreateBodyNameMax).describe('Human-readable name of the account.'),+ external_id: zod+ .string()+ .max(accountsCreateBodyExternalIdMax)+ .nullish()+ .describe('Identifier for the account in an external system (e.g. CRM ID). Optional.'),+ properties: zod+ .object({+ csm: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ account_executive: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ account_owner: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ stripe_customer_id: zod.string().nullish(),+ hubspot_deal_id: zod.string().nullish(),+ billing_id: zod.string().nullish(),+ sfdc_id: zod.string().nullish(),+ zendesk_id: zod.string().nullish(),+ })+ .nullish()+ .describe(+ 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id). Defaults to an empty object. Unknown keys are rejected.'+ ),+ tags: zod+ .array(zod.string())+ .optional()+ .describe('Tag names attached to the account. Pass a list to replace existing tags.'),+ })+ .describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')export const accountsUpdateBodyNameMax = 400export const accountsUpdateBodyExternalIdMax = 400-export const AccountsUpdateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(accountsUpdateBodyNameMax).describe('Human-readable name of the account.'),- external_id: zod- .string()- .max(accountsUpdateBodyExternalIdMax)- .nullish()- .describe('Identifier for the account in an external system (e.g. CRM ID). Optional.'),- properties: zod- .object({- csm: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_executive: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_owner: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- stripe_customer_id: zod.string().nullish(),- hubspot_deal_id: zod.string().nullish(),- billing_id: zod.string().nullish(),- sfdc_id: zod.string().nullish(),- zendesk_id: zod.string().nullish(),- })- .nullish()- .describe(- 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id). Defaults to an empty object. Unknown keys are rejected.'- ),-})+export const AccountsUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod.string().max(accountsUpdateBodyNameMax).describe('Human-readable name of the account.'),+ external_id: zod+ .string()+ .max(accountsUpdateBodyExternalIdMax)+ .nullish()+ .describe('Identifier for the account in an external system (e.g. CRM ID). Optional.'),+ properties: zod+ .object({+ csm: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ account_executive: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ account_owner: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ stripe_customer_id: zod.string().nullish(),+ hubspot_deal_id: zod.string().nullish(),+ billing_id: zod.string().nullish(),+ sfdc_id: zod.string().nullish(),+ zendesk_id: zod.string().nullish(),+ })+ .nullish()+ .describe(+ 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id). Defaults to an empty object. Unknown keys are rejected.'+ ),+ tags: zod+ .array(zod.string())+ .optional()+ .describe('Tag names attached to the account. Pass a list to replace existing tags.'),+ })+ .describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')export const accountsPartialUpdateBodyNameMax = 400export const accountsPartialUpdateBodyExternalIdMax = 400-export const AccountsPartialUpdateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(accountsPartialUpdateBodyNameMax).optional().describe('Human-readable name of the account.'),- external_id: zod- .string()- .max(accountsPartialUpdateBodyExternalIdMax)- .nullish()- .describe('Identifier for the account in an external system (e.g. CRM ID). Optional.'),- properties: zod- .object({- csm: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_executive: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_owner: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- stripe_customer_id: zod.string().nullish(),- hubspot_deal_id: zod.string().nullish(),- billing_id: zod.string().nullish(),- sfdc_id: zod.string().nullish(),- zendesk_id: zod.string().nullish(),- })- .nullish()- .describe(- 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id). Defaults to an empty object. Unknown keys are rejected.'- ),-})+export const AccountsPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(accountsPartialUpdateBodyNameMax)+ .optional()+ .describe('Human-readable name of the account.'),+ external_id: zod+ .string()+ .max(accountsPartialUpdateBodyExternalIdMax)+ .nullish()+ .describe('Identifier for the account in an external system (e.g. CRM ID). Optional.'),+ properties: zod+ .object({+ csm: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ account_executive: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ account_owner: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ stripe_customer_id: zod.string().nullish(),+ hubspot_deal_id: zod.string().nullish(),+ billing_id: zod.string().nullish(),+ sfdc_id: zod.string().nullish(),+ zendesk_id: zod.string().nullish(),+ })+ .nullish()+ .describe(+ 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id). Defaults to an empty object. Unknown keys are rejected.'+ ),+ tags: zod+ .array(zod.string())+ .optional()+ .describe('Tag names attached to the account. Pass a list to replace existing tags.'),+ })+ .describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')export const customerJourneysCreateBodyNameMax = 400diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex e4aef18f31a7..b458f2b302bb 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -21,9 +21,10 @@ tools:title: Create accountdescription: >Create a new Customer Analytics account. An account is a logical container for assigning ownership across- the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), and- optional `properties` to set role assignments (`csm`, `account_executive`, `account_owner`) and external- system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`).+ the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), optional+ `properties` to set role assignments (`csm`, `account_executive`, `account_owner`) and external system+ identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`), and optional+ `tags` to categorize the account.param_overrides:properties:description: >@@ -31,6 +32,10 @@ tools:takes `{id, email}` of an existing user. `stripe_customer_id`, `hubspot_deal_id`, `billing_id`,`sfdc_id`, `zendesk_id` are optional string identifiers for the account in external systems. Allfields are optional.+ tags:+ description: >+ Tag names to attach to the account. Tags are created on demand if they do not already exist for the+ team.feature_flag: customer-analytics-cspaccounts-destroy:operation: accounts_destroy@@ -60,7 +65,14 @@ tools:List Customer Analytics accounts in the project, ordered by most recently created. Each result includes theaccount `id`, `name`, `external_id`, typed `properties` (assignment fields csm, account_executive,account_owner and external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id,- zendesk_id), and creation/update metadata. Use `accounts-retrieve` for a single account by id.+ zendesk_id), `tags`, and creation/update metadata. Pass `tags` (JSON-encoded array, e.g.+ `["enterprise","priority"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve`+ for a single account by id.+ param_overrides:+ tags:+ description: >+ JSON-encoded array of tag names to filter by, e.g. `["enterprise","priority"]`. Returns accounts+ that have any of the listed tags.feature_flag: customer-analytics-cspaccounts-partial-update:operation: accounts_partial_update@@ -74,7 +86,7 @@ tools:title: Update accountdescription: >Update fields on an existing Customer Analytics account. Accepts a subset of fields; unspecified fields are- left unchanged.+ left unchanged. Pass `tags` to replace the full set of tags on the account.param_overrides:properties:description: >@@ -82,6 +94,10 @@ tools:existing values you want to preserve. Supported keys: `csm`, `account_executive`, `account_owner`(each `{id, email}` of an existing user), plus `stripe_customer_id`, `hubspot_deal_id`,`billing_id`, `sfdc_id`, `zendesk_id` (optional string identifiers for external systems).+ tags:+ description: >+ Tag names to set on the account. Replaces the full existing tag set — pass the complete list, not a+ delta. Tags are created on demand if they do not already exist for the team.feature_flag: customer-analytics-cspaccounts-retrieve:operation: accounts_retrieve@@ -96,7 +112,7 @@ tools:description: >Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (csm,account_executive, account_owner assignments plus stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id,- zendesk_id external identifiers).+ zendesk_id external identifiers) and `tags`.feature_flag: customer-analytics-cspaccounts-update:operation: accounts_updatediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 30ef7c673d75..2494ddf1a016 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1,6 +1,6 @@{"accounts-create": {- "description": "Create a new Customer Analytics account. An account is a logical container for assigning ownership across the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), and optional `properties` to set role assignments (`csm`, `account_executive`, `account_owner`) and external system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`).",+ "description": "Create a new Customer Analytics account. An account is a logical container for assigning ownership across the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), optional `properties` to set role assignments (`csm`, `account_executive`, `account_owner`) and external system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`), and optional `tags` to categorize the account.","category": "Customer analytics","feature": "customer_analytics","summary": "Create account",@@ -32,7 +32,7 @@"feature_flag": "customer-analytics-csp"},"accounts-list": {- "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (assignment fields csm, account_executive, account_owner and external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), and creation/update metadata. Use `accounts-retrieve` for a single account by id.",+ "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (assignment fields csm, account_executive, account_owner and external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, and creation/update metadata. Pass `tags` (JSON-encoded array, e.g. `[\"enterprise\",\"priority\"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id.","category": "Customer analytics","feature": "customer_analytics","summary": "List accounts",@@ -48,7 +48,7 @@"feature_flag": "customer-analytics-csp"},"accounts-partial-update": {- "description": "Update fields on an existing Customer Analytics account. Accepts a subset of fields; unspecified fields are left unchanged.",+ "description": "Update fields on an existing Customer Analytics account. Accepts a subset of fields; unspecified fields are left unchanged. Pass `tags` to replace the full set of tags on the account.","category": "Customer analytics","feature": "customer_analytics","summary": "Update account",@@ -64,7 +64,7 @@"feature_flag": "customer-analytics-csp"},"accounts-retrieve": {- "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (csm, account_executive, account_owner assignments plus stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers).",+ "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (csm, account_executive, account_owner assignments plus stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers) and `tags`.","category": "Customer analytics","feature": "customer_analytics","summary": "Get account",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 2500d7babdc6..dbf835c1cd70 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1,6 +1,6 @@{"accounts-create": {- "description": "Create a new Customer Analytics account. An account is a logical container for assigning ownership across the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), and optional `properties` to set role assignments (`csm`, `account_executive`, `account_owner`) and external system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`).",+ "description": "Create a new Customer Analytics account. An account is a logical container for assigning ownership across the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), optional `properties` to set role assignments (`csm`, `account_executive`, `account_owner`) and external system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`), and optional `tags` to categorize the account.","category": "Customer analytics","feature": "customer_analytics","summary": "Create account",@@ -32,7 +32,7 @@"feature_flag": "customer-analytics-csp"},"accounts-list": {- "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (assignment fields csm, account_executive, account_owner and external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), and creation/update metadata. Use `accounts-retrieve` for a single account by id.",+ "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (assignment fields csm, account_executive, account_owner and external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, and creation/update metadata. Pass `tags` (JSON-encoded array, e.g. `[\"enterprise\",\"priority\"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id.","category": "Customer analytics","feature": "customer_analytics","summary": "List accounts",@@ -48,7 +48,7 @@"feature_flag": "customer-analytics-csp"},"accounts-partial-update": {- "description": "Update fields on an existing Customer Analytics account. Accepts a subset of fields; unspecified fields are left unchanged.",+ "description": "Update fields on an existing Customer Analytics account. Accepts a subset of fields; unspecified fields are left unchanged. Pass `tags` to replace the full set of tags on the account.","category": "Customer analytics","feature": "customer_analytics","summary": "Update account",@@ -64,7 +64,7 @@"feature_flag": "customer-analytics-csp"},"accounts-retrieve": {- "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (csm, account_executive, account_owner assignments plus stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers).",+ "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (csm, account_executive, account_owner assignments plus stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers) and `tags`.","category": "Customer analytics","feature": "customer_analytics","summary": "Get account",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 04dce89ae2e3..836e8c68688e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -89,6 +89,9 @@ export namespace Schemas {zendesk_id?: string | null;} | null;+ /**+ * A Customer Analytics account — a logical grouping used to assign customer-success ownership.+ */export interface Account {readonly id: string;/**@@ -107,6 +110,8 @@ export namespace Schemas {* @nullable*/properties?: AccountProperties;+ /** Tag names attached to the account. Pass a list to replace existing tags. */+ tags?: string[];readonly created_at: string;/** @nullable */readonly created_by: number | null;@@ -25669,6 +25674,9 @@ export namespace Schemas {zendesk_id?: string | null;} | null;+ /**+ * A Customer Analytics account — a logical grouping used to assign customer-success ownership.+ */export interface PatchedAccount {readonly id?: string;/**@@ -25687,6 +25695,8 @@ export namespace Schemas {* @nullable*/properties?: PatchedAccountProperties;+ /** Tag names attached to the account. Pass a list to replace existing tags. */+ tags?: string[];readonly created_at?: string;/** @nullable */readonly created_by?: number | null;@@ -39891,6 +39901,10 @@ export namespace Schemas {* The initial index from which to return the results.*/offset?: number;+ /**+ * JSON-encoded array of tag names to filter by, e.g. `["enterprise","priority"]`. Returns accounts that have any of the listed tags.+ */+ tags?: string;};export type ApprovalPoliciesListParams = {diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.tsindex 22a30c080174..6d2b1850b15d 100644--- a/services/mcp/src/generated/customer_analytics/api.ts+++ b/services/mcp/src/generated/customer_analytics/api.ts@@ -19,6 +19,12 @@ export const AccountsListParams = /* @__PURE__ */ zod.object({export const AccountsListQueryParams = /* @__PURE__ */ zod.object({limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),+ tags: zod+ .string()+ .optional()+ .describe(+ 'JSON-encoded array of tag names to filter by, e.g. `["enterprise","priority"]`. Returns accounts that have any of the listed tags.'+ ),})export const AccountsCreateParams = /* @__PURE__ */ zod.object({@@ -33,44 +39,50 @@ export const accountsCreateBodyNameMax = 400export const accountsCreateBodyExternalIdMax = 400-export const AccountsCreateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(accountsCreateBodyNameMax).describe('Human-readable name of the account.'),- external_id: zod- .string()- .max(accountsCreateBodyExternalIdMax)- .nullish()- .describe('Identifier for the account in an external system (e.g. CRM ID). Optional.'),- properties: zod- .object({- csm: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_executive: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_owner: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- stripe_customer_id: zod.string().nullish(),- hubspot_deal_id: zod.string().nullish(),- billing_id: zod.string().nullish(),- sfdc_id: zod.string().nullish(),- zendesk_id: zod.string().nullish(),- })- .nullish()- .describe(- 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id). Defaults to an empty object. Unknown keys are rejected.'- ),-})+export const AccountsCreateBody = /* @__PURE__ */ zod+ .object({+ name: zod.string().max(accountsCreateBodyNameMax).describe('Human-readable name of the account.'),+ external_id: zod+ .string()+ .max(accountsCreateBodyExternalIdMax)+ .nullish()+ .describe('Identifier for the account in an external system (e.g. CRM ID). Optional.'),+ properties: zod+ .object({+ csm: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ account_executive: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ account_owner: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ stripe_customer_id: zod.string().nullish(),+ hubspot_deal_id: zod.string().nullish(),+ billing_id: zod.string().nullish(),+ sfdc_id: zod.string().nullish(),+ zendesk_id: zod.string().nullish(),+ })+ .nullish()+ .describe(+ 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id). Defaults to an empty object. Unknown keys are rejected.'+ ),+ tags: zod+ .array(zod.string())+ .optional()+ .describe('Tag names attached to the account. Pass a list to replace existing tags.'),+ })+ .describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')export const AccountsRetrieveParams = /* @__PURE__ */ zod.object({id: zod.string().describe('A UUID string identifying this account.'),@@ -94,44 +106,54 @@ export const accountsPartialUpdateBodyNameMax = 400export const accountsPartialUpdateBodyExternalIdMax = 400-export const AccountsPartialUpdateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(accountsPartialUpdateBodyNameMax).optional().describe('Human-readable name of the account.'),- external_id: zod- .string()- .max(accountsPartialUpdateBodyExternalIdMax)- .nullish()- .describe('Identifier for the account in an external system (e.g. CRM ID). Optional.'),- properties: zod- .object({- csm: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_executive: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_owner: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- stripe_customer_id: zod.string().nullish(),- hubspot_deal_id: zod.string().nullish(),- billing_id: zod.string().nullish(),- sfdc_id: zod.string().nullish(),- zendesk_id: zod.string().nullish(),- })- .nullish()- .describe(- 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id). Defaults to an empty object. Unknown keys are rejected.'- ),-})+export const AccountsPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(accountsPartialUpdateBodyNameMax)+ .optional()+ .describe('Human-readable name of the account.'),+ external_id: zod+ .string()+ .max(accountsPartialUpdateBodyExternalIdMax)+ .nullish()+ .describe('Identifier for the account in an external system (e.g. CRM ID). Optional.'),+ properties: zod+ .object({+ csm: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ account_executive: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ account_owner: zod+ .object({+ id: zod.number(),+ email: zod.string(),+ })+ .nullish(),+ stripe_customer_id: zod.string().nullish(),+ hubspot_deal_id: zod.string().nullish(),+ billing_id: zod.string().nullish(),+ sfdc_id: zod.string().nullish(),+ zendesk_id: zod.string().nullish(),+ })+ .nullish()+ .describe(+ 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id). Defaults to an empty object. Unknown keys are rejected.'+ ),+ tags: zod+ .array(zod.string())+ .optional()+ .describe('Tag names attached to the account. Pass a list to replace existing tags.'),+ })+ .describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')export const AccountsDestroyParams = /* @__PURE__ */ zod.object({id: zod.string().describe('A UUID string identifying this account.'),diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.tsindex dd2909bf7f1e..7f1ce0e21c15 100644--- a/services/mcp/src/tools/generated/customer_analytics.ts+++ b/services/mcp/src/tools/generated/customer_analytics.ts@@ -26,6 +26,9 @@ const AccountsCreateSchema = AccountsCreateBody.extend({properties: AccountsCreateBody.shape['properties'].describe('Typed account properties. `csm`, `account_executive`, `account_owner` are role assignments — each takes `{id, email}` of an existing user. `stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id` are optional string identifiers for the account in external systems. All fields are optional.'),+ tags: AccountsCreateBody.shape['tags'].describe(+ 'Tag names to attach to the account. Tags are created on demand if they do not already exist for the team.'+ ),})const accountsCreate = (): ToolBase<typeof AccountsCreateSchema, Schemas.Account> => ({@@ -43,6 +46,9 @@ const accountsCreate = (): ToolBase<typeof AccountsCreateSchema, Schemas.Accountif (params.properties !== undefined) {body['properties'] = params.properties}+ if (params.tags !== undefined) {+ body['tags'] = params.tags+ }const result = await context.api.request<Schemas.Account>({method: 'POST',path: `/api/environments/${encodeURIComponent(String(projectId))}/accounts/`,@@ -67,7 +73,11 @@ const accountsDestroy = (): ToolBase<typeof AccountsDestroySchema, unknown> => (},})-const AccountsListSchema = AccountsListQueryParams+const AccountsListSchema = AccountsListQueryParams.extend({+ tags: AccountsListQueryParams.shape['tags'].describe(+ 'JSON-encoded array of tag names to filter by, e.g. `["enterprise","priority"]`. Returns accounts that have any of the listed tags.'+ ),+})const accountsList = (): ToolBase<typeof AccountsListSchema, WithPostHogUrl<Schemas.PaginatedAccountList>> => ({name: 'accounts-list',@@ -80,6 +90,7 @@ const accountsList = (): ToolBase<typeof AccountsListSchema, WithPostHogUrl<Schequery: {limit: params.limit,offset: params.offset,+ tags: params.tags,},})return await withPostHogUrl(context, result, '/customer-analytics')@@ -92,6 +103,9 @@ const AccountsPartialUpdateSchema = AccountsPartialUpdateParams.omit({ project_iproperties: AccountsPartialUpdateBody.shape['properties'].describe('Typed account properties. The server replaces the `properties` object as a whole, so include any existing values you want to preserve. Supported keys: `csm`, `account_executive`, `account_owner` (each `{id, email}` of an existing user), plus `stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id` (optional string identifiers for external systems).'),+ tags: AccountsPartialUpdateBody.shape['tags'].describe(+ 'Tag names to set on the account. Replaces the full existing tag set — pass the complete list, not a delta. Tags are created on demand if they do not already exist for the team.'+ ),})const accountsPartialUpdate = (): ToolBase<typeof AccountsPartialUpdateSchema, Schemas.Account> => ({@@ -109,6 +123,9 @@ const accountsPartialUpdate = (): ToolBase<typeof AccountsPartialUpdateSchema, Sif (params.properties !== undefined) {body['properties'] = params.properties}+ if (params.tags !== undefined) {+ body['tags'] = params.tags+ }const result = await context.api.request<Schemas.Account>({method: 'PATCH',path: `/api/environments/${encodeURIComponent(String(projectId))}/accounts/${encodeURIComponent(String(params.id))}/`,