: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): Add account CRUD API (#58155)
Arthur Moreira de Deus7d048fbee19f
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex 928eaf7bd608..43b44a623ac1 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -16,6 +16,7 @@ export type APIScope = {export const API_SCOPES: APIScope[] = [{ key: 'action', objectName: 'Action', objectPlural: 'actions' },{ key: 'access_control', objectName: 'Access control', objectPlural: 'access controls' },+ { key: 'account', objectName: 'Account', objectPlural: 'accounts' },{ key: 'activity_log', objectName: 'Activity log', objectPlural: 'activity logs' },{ key: 'alert', objectName: 'Alert', objectPlural: 'alerts' },{ key: 'annotation', objectName: 'Annotation', objectPlural: 'annotations' },diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 190236a89191..56de225ac43a 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5295,6 +5295,7 @@ export interface RoleMemberType {export type APIScopeObject =| 'action'| 'access_control'+ | 'account'| 'activity_log'| 'alert'| 'annotation'diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex c6328d742c20..f89f9ba57cb8 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -425,6 +425,13 @@ environments_router.register(["team_id"],)+environments_router.register(+ r"accounts",+ customer_analytics.AccountViewSet,+ "environment_accounts",+ ["team_id"],+)+projects_router.register(r"data_management",DataManagementViewSet,diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.pyindex 924419788238..5cd4d4e93b66 100644--- a/posthog/rbac/user_access_control.py+++ b/posthog/rbac/user_access_control.py@@ -85,6 +85,7 @@ RESOURCE_INHERITANCE_MAP: dict[APIScopeObject, APIScopeObject] = {"llm_provider_key": "llm_analytics","llm_prompt": "llm_analytics","llm_skill": "llm_analytics",+ "account": "customer_analytics","customer_journey": "customer_analytics","experiment_saved_metric": "experiment","dashboard_template": "dashboard",diff --git a/posthog/scopes.py b/posthog/scopes.pyindex 1476af221e59..151f9036bbe1 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -16,6 +16,7 @@ from typing import Literal, get_argsAPIScopeObject = Literal["action","access_control",+ "account","activity_log","alert","annotation",diff --git a/products/customer_analytics/backend/api/serializers.py b/products/customer_analytics/backend/api/serializers.pyindex 3599b8c5941b..bd817cb92395 100644--- a/products/customer_analytics/backend/api/serializers.py+++ b/products/customer_analytics/backend/api/serializers.py@@ -1,8 +1,36 @@import json+from drf_spectacular.utils import extend_schema_field+from pydantic import ValidationError as PydanticValidationErrorfrom rest_framework import serializers-from products.customer_analytics.backend.models import CustomerJourney, CustomerProfileConfig+from products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfig+from products.customer_analytics.backend.models.account import AccountProperties++_ACCOUNT_ASSIGNMENT_SCHEMA = {+ "type": "object",+ "nullable": True,+ "properties": {+ "id": {"type": "integer"},+ "email": {"type": "string"},+ },+ "required": ["id", "email"],+}++_ACCOUNT_PROPERTIES_SCHEMA = {+ "type": "object",+ "additionalProperties": False,+ "properties": {+ "csm": _ACCOUNT_ASSIGNMENT_SCHEMA,+ "account_executive": _ACCOUNT_ASSIGNMENT_SCHEMA,+ "account_owner": _ACCOUNT_ASSIGNMENT_SCHEMA,+ },+}+++@extend_schema_field(_ACCOUNT_PROPERTIES_SCHEMA)+class AccountPropertiesField(serializers.JSONField):+ passclass CustomerProfileConfigSerializer(serializers.ModelSerializer):@@ -84,3 +112,83 @@ class CustomerJourneySerializer(serializers.ModelSerializer):return super().create(validated_data)except IntegrityError:raise Conflict("A customer journey already exists for this insight.")+++class AccountSerializer(serializers.ModelSerializer):+ name = serializers.CharField(+ max_length=400,+ help_text="Human-readable name of the account.",+ )+ external_id = serializers.CharField(+ max_length=400,+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="Identifier for the account in an external system (e.g. CRM ID). Optional.",+ )+ properties = AccountPropertiesField(+ source="_properties",+ required=False,+ allow_null=True,+ help_text=(+ "Typed account properties: assignment fields (csm, account_executive, account_owner). "+ "Defaults to an empty object. Unknown keys are rejected."+ ),+ )++ class Meta:+ model = Account+ fields = [+ "id",+ "name",+ "external_id",+ "properties",+ "created_at",+ "created_by",+ "updated_at",+ ]+ read_only_fields = [+ "id",+ "created_at",+ "created_by",+ "updated_at",+ ]++ def validate_properties(self, value):+ if value is None:+ return {}++ if not isinstance(value, dict):+ raise serializers.ValidationError("properties must be a JSON object.")++ try:+ json.dumps(value)+ except (TypeError, ValueError):+ raise serializers.ValidationError("properties must be JSON-serializable.")++ try:+ AccountProperties.model_validate(value)+ except PydanticValidationError as exc:+ raise serializers.ValidationError(_format_pydantic_errors(exc))++ return value++ def create(self, validated_data):+ from django.db import IntegrityError++ from posthog.exceptions import Conflict++ validated_data["created_by"] = self.context["request"].user+ validated_data["team_id"] = self.context["team_id"]+ try:+ return super().create(validated_data)+ except IntegrityError:+ raise Conflict("An account with this external_id already exists for this team.")+++def _format_pydantic_errors(exc: PydanticValidationError) -> list[str]:+ messages = []+ for err in exc.errors():+ loc = ".".join(str(part) for part in err["loc"])+ messages.append(f"{loc}: {err['msg']}" if loc else err["msg"])+ return messagesdiff --git a/products/customer_analytics/backend/api/test_views.py b/products/customer_analytics/backend/api/test_views.pyindex e498a820e702..50f4ebed3e23 100644--- a/products/customer_analytics/backend/api/test_views.py+++ b/products/customer_analytics/backend/api/test_views.py@@ -11,7 +11,8 @@ from posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.models.user import User-from products.customer_analytics.backend.models import CustomerJourney, CustomerProfileConfig+from products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfig+from products.customer_analytics.backend.models.account import AccountAssignmentclass TestCustomerProfileConfigViewSet(APIBaseTest):@@ -385,9 +386,213 @@ class TestCustomerJourneyViewSet(APIBaseTest):self.assertEqual(expected_status_code, response.status_code)+class TestAccountViewSet(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.endpoint_base = f"/api/environments/{self.team.id}/accounts/"++ def _create_account(self, **kwargs):+ defaults = {"team": self.team, "name": "Acme Corp"}+ defaults.update(kwargs)+ return Account.objects.unscoped().create(**defaults)++ def test_create(self):+ response = self.client.post(+ self.endpoint_base,+ {+ "name": "Acme Corp",+ "external_id": "acme-123",+ "properties": {"csm": {"id": self.user.id, "email": self.user.email}},+ },+ format="json",+ )++ self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())+ data = response.json()+ self.assertIn("id", data)+ self.assertEqual(data["name"], "Acme Corp")+ self.assertEqual(data["external_id"], "acme-123")+ self.assertEqual(data["properties"]["csm"], {"id": self.user.id, "email": self.user.email})+ self.assertIn("created_at", data)+ self.assertIn("updated_at", data)++ account = Account.objects.unscoped().get(id=data["id"]) # nosemgrep: semgrep.rules.idor-lookup-without-team+ self.assertEqual(account.created_by, self.user)+ self.assertEqual(account.team, self.team)+ self.assertEqual(account.properties.csm, AccountAssignment(id=self.user.id, email=self.user.email))++ def test_create_minimal_payload_uses_defaults(self):+ response = self.client.post(self.endpoint_base, {"name": "Bare Account"}, format="json")++ self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())+ data = response.json()+ self.assertEqual(data["name"], "Bare Account")+ self.assertIsNone(data["external_id"])+ self.assertEqual(data["properties"], {})++ def test_list(self):+ a1 = self._create_account(name="Account 1")+ a2 = self._create_account(name="Account 2")++ other_team = Team.objects.create(organization=self.organization)+ Account.objects.unscoped().create(team=other_team, name="Other Team Account")++ response = self.client.get(self.endpoint_base)++ self.assertEqual(status.HTTP_200_OK, response.status_code)+ data = response.json()+ self.assertEqual(data["count"], 2)+ ids = {r["id"] for r in data["results"]}+ self.assertEqual(ids, {str(a1.id), str(a2.id)})++ def test_retrieve(self):+ account = self._create_account(+ external_id="ext-1",+ properties={"csm": {"id": self.user.id, "email": self.user.email}},+ )++ response = self.client.get(f"{self.endpoint_base}{account.id}/")++ self.assertEqual(status.HTTP_200_OK, response.status_code)+ data = response.json()+ self.assertEqual(data["id"], str(account.id))+ self.assertEqual(data["name"], "Acme Corp")+ self.assertEqual(data["external_id"], "ext-1")+ self.assertEqual(data["properties"]["csm"], {"id": self.user.id, "email": self.user.email})++ def test_update(self):+ account = self._create_account(properties={"csm": {"id": self.user.id, "email": self.user.email}})++ response = self.client.patch(+ f"{self.endpoint_base}{account.id}/",+ {+ "name": "Renamed",+ "properties": {"account_owner": {"id": self.user.id, "email": self.user.email}},+ },+ format="json",+ )++ self.assertEqual(status.HTTP_200_OK, response.status_code)+ account.refresh_from_db()+ self.assertEqual(account.name, "Renamed")+ self.assertEqual(account.properties.account_owner, AccountAssignment(id=self.user.id, email=self.user.email))++ def test_delete(self):+ account = self._create_account()+ account_id = account.id++ response = self.client.delete(f"{self.endpoint_base}{account.id}/")++ self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code)+ # nosemgrep: idor-lookup-without-team (test assertion)+ self.assertFalse(Account.objects.unscoped().filter(id=account_id).exists())++ @parameterized.expand(+ [+ (+ "create",+ lambda self: self.client.post(self.endpoint_base, {"name": "Logged"}, format="json"),+ "created",+ ),+ (+ "update",+ lambda self: self.client.patch(+ f"{self.endpoint_base}{self._create_account().id}/",+ {"name": "Renamed"},+ format="json",+ ),+ "updated",+ ),+ (+ "delete",+ lambda self: self.client.delete(f"{self.endpoint_base}{self._create_account().id}/"),+ "deleted",+ ),+ ]+ )+ def test_activity_log(self, _name, perform_action, expected_activity):+ perform_action(self)++ logs = ActivityLog.objects.filter(team_id=self.team.id, scope="Account", activity=expected_activity)+ self.assertEqual(logs.count(), 1)++ def test_team_isolation(self):+ other_team = Team.objects.create(organization=self.organization)+ other_account = Account.objects.unscoped().create(team=other_team, name="Other")++ response = self.client.get(f"{self.endpoint_base}{other_account.id}/")+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)++ response = self.client.patch(f"{self.endpoint_base}{other_account.id}/", {"name": "Hijacked"}, format="json")+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)++ response = self.client.delete(f"{self.endpoint_base}{other_account.id}/")+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)++ @parameterized.expand(+ [+ ("missing_name", {}, "name"),+ ("name_too_long", {"name": "x" * 401}, "name"),+ ("properties_not_object", {"name": "Acme", "properties": [1, 2, 3]}, "properties"),+ ("properties_not_object_string", {"name": "Acme", "properties": "not-a-dict"}, "properties"),+ (+ "properties_unknown_key",+ {"name": "Acme", "properties": {"unknown_field": "x"}},+ "properties",+ ),+ (+ "properties_assignment_missing_email",+ {"name": "Acme", "properties": {"csm": {"id": 1}}},+ "properties",+ ),+ (+ "properties_assignment_wrong_id_type",+ {"name": "Acme", "properties": {"csm": {"id": "not-an-int", "email": "[email protected]"}}},+ "properties",+ ),+ ]+ )+ def test_validation_errors(self, _name, invalid_data, expected_error_field):+ response = self.client.post(self.endpoint_base, invalid_data, format="json")++ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)+ data = response.json()+ self.assertEqual(data["attr"], expected_error_field)+ self.assertEqual(data["type"], "validation_error")++ def test_properties_default_when_null(self):+ response = self.client.post(self.endpoint_base, {"name": "Acme", "properties": None}, format="json")++ self.assertEqual(status.HTTP_201_CREATED, response.status_code)+ self.assertEqual({}, response.json()["properties"])++ def test_create_duplicate_external_id_returns_409(self):+ first = self.client.post(self.endpoint_base, {"name": "First", "external_id": "acme-1"}, format="json")+ self.assertEqual(status.HTTP_201_CREATED, first.status_code, first.json())++ second = self.client.post(self.endpoint_base, {"name": "Second", "external_id": "acme-1"}, format="json")++ self.assertEqual(status.HTTP_409_CONFLICT, second.status_code, second.json())+ self.assertIn("already exists", second.json()["detail"])++ def test_authentication_required(self):+ self.client.logout()++ for method, url in [+ ("GET", self.endpoint_base),+ ("POST", self.endpoint_base),+ ("GET", f"{self.endpoint_base}test-id/"),+ ("PATCH", f"{self.endpoint_base}test-id/"),+ ("DELETE", f"{self.endpoint_base}test-id/"),+ ]:+ with self.subTest(method=method, url=url):+ response = getattr(self.client, method.lower())(url, format="json")+ self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])++@pytest.mark.eeclass TestCustomerAnalyticsAccessControl(APIBaseTest):- """Resource-level access control tests for customer journeys.+ """Resource-level access control tests for customer journeys and accounts.Note: CustomerProfileConfig is a settings resource and uses project-leveladmin permissions, not resource-level RBAC. See TestCustomerProfileConfigViewSet@@ -422,6 +627,9 @@ class TestCustomerAnalyticsAccessControl(APIBaseTest):self.journeys_url = f"/api/environments/{self.team.id}/customer_journeys/"+ self.account = Account.objects.unscoped().create(team=self.team, name="ACL Account")+ self.accounts_url = f"/api/environments/{self.team.id}/accounts/"+def _set_access_level(self, user: User, resource: str = "customer_analytics", access_level: str = "viewer") -> None:try:from ee.models.rbac.access_control import AccessControl@@ -585,3 +793,33 @@ class TestCustomerAnalyticsAccessControl(APIBaseTest):response = self.client.delete(f"{self.journeys_url}{self.journey.id}/")self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)++ # -- Resource inheritance: customer_analytics access cascades to accounts --++ def test_customer_analytics_viewer_can_list_accounts(self):+ self._set_access_level(self.viewer_user, resource="customer_analytics", access_level="viewer")+ self.client.force_login(self.viewer_user)++ response = self.client.get(self.accounts_url)+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ def test_customer_analytics_viewer_cannot_create_account(self):+ self._set_access_level(self.viewer_user, resource="customer_analytics", access_level="viewer")+ self.client.force_login(self.viewer_user)++ response = self.client.post(self.accounts_url, {"name": "Should Fail"}, format="json")+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_customer_analytics_editor_can_create_account(self):+ self._set_access_level(self.editor_user, resource="customer_analytics", access_level="editor")+ self.client.force_login(self.editor_user)++ response = self.client.post(self.accounts_url, {"name": "Inherited Account"}, format="json")+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ def test_customer_analytics_none_blocks_account_list(self):+ self._set_access_level(self.no_access_user, resource="customer_analytics", access_level="none")+ self.client.force_login(self.no_access_user)++ response = self.client.get(self.accounts_url)+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)diff --git a/products/customer_analytics/backend/api/views.py b/products/customer_analytics/backend/api/views.pyindex 6834e134357c..6306439c1662 100644--- a/products/customer_analytics/backend/api/views.py+++ b/products/customer_analytics/backend/api/views.py@@ -4,9 +4,9 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import log_activity_from_viewsetfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin-from products.customer_analytics.backend.models import CustomerJourney, CustomerProfileConfig+from products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfig-from .serializers import CustomerJourneySerializer, CustomerProfileConfigSerializer+from .serializers import AccountSerializer, CustomerJourneySerializer, CustomerProfileConfigSerializerfrom .utils import log_customer_profile_config_activity@@ -56,3 +56,25 @@ class CustomerJourneyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin,def perform_destroy(self, instance):log_activity_from_viewset(self, instance, activity="deleted", name=instance.name)super().perform_destroy(instance)+++class AccountViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):+ scope_object = "account"+ queryset = Account.objects.unscoped().order_by("-created_at")+ serializer_class = AccountSerializer++ def safely_get_queryset(self, queryset):+ return queryset.filter(team_id=self.team.id)++ def perform_create(self, serializer):+ serializer.save()+ log_activity_from_viewset(self, serializer.instance, name=serializer.instance.name)++ def perform_update(self, serializer):+ previous = self.get_object()+ serializer.save()+ log_activity_from_viewset(self, serializer.instance, name=serializer.instance.name, previous=previous)++ def perform_destroy(self, instance):+ log_activity_from_viewset(self, instance, activity="deleted", name=instance.name)+ super().perform_destroy(instance)diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex bb5b475d8e5a..393ae2424b61 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -7,6 +7,62 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+/**+ * Typed account properties: assignment fields (csm, account_executive, account_owner). Defaults to an empty object. Unknown keys are rejected.+ * @nullable+ */+export type AccountApiProperties = {+ /** @nullable */+ csm?: {+ id: number+ email: string+ } | null+ /** @nullable */+ account_executive?: {+ id: number+ email: string+ } | null+ /** @nullable */+ account_owner?: {+ id: number+ email: string+ } | null+} | null++export interface AccountApi {+ readonly id: string+ /**+ * Human-readable name of the account.+ * @maxLength 400+ */+ name: string+ /**+ * Identifier for the account in an external system (e.g. CRM ID). Optional.+ * @maxLength 400+ * @nullable+ */+ external_id?: string | null+ /**+ * Typed account properties: assignment fields (csm, account_executive, account_owner). Defaults to an empty object. Unknown keys are rejected.+ * @nullable+ */+ properties?: AccountApiProperties+ readonly created_at: string+ /** @nullable */+ readonly created_by: number | null+ /** @nullable */+ readonly updated_at: string | null+}++export interface PaginatedAccountListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: AccountApi[]+}+export interface CustomerJourneyApi {readonly id: stringinsight: number@@ -207,6 +263,17 @@ export interface PatchedGroupUsageMetricApi {math_property?: string | null}+export type AccountsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}+export type CustomerJourneysListParams = {/*** Number of results to return per page.diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex 95ccb88e5867..d71c8a090630 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -9,12 +9,15 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ AccountApi,+ AccountsListParams,CustomerJourneyApi,CustomerJourneysListParams,CustomerProfileConfigApi,CustomerProfileConfigsListParams,GroupUsageMetricApi,GroupsTypesMetricsListParams,+ PaginatedAccountListApi,PaginatedCustomerJourneyListApi,PaginatedCustomerProfileConfigListApi,PaginatedGroupUsageMetricListApi,@@ -38,6 +41,50 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>+export const getAccountsListUrl = (projectId: string, params?: AccountsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/environments/${projectId}/accounts/?${stringifiedParams}`+ : `/api/environments/${projectId}/accounts/`+}++export const accountsList = async (+ projectId: string,+ params?: AccountsListParams,+ options?: RequestInit+): Promise<PaginatedAccountListApi> => {+ return apiMutator<PaginatedAccountListApi>(getAccountsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getAccountsCreateUrl = (projectId: string) => {+ return `/api/environments/${projectId}/accounts/`+}++export const accountsCreate = async (+ projectId: string,+ accountApi: NonReadonly<AccountApi>,+ options?: RequestInit+): Promise<AccountApi> => {+ return apiMutator<AccountApi>(getAccountsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(accountApi),+ })+}+export const getCustomerJourneysListUrl = (projectId: string, params?: CustomerJourneysListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex edd9fa6aec33..b754338af9af 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -9,6 +9,44 @@*/import * as zod from 'zod'+export const accountsCreateBodyNameMax = 400++export 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(),+ })+ .nullish()+ .describe(+ 'Typed account properties: assignment fields (csm, account_executive, account_owner). Defaults to an empty object. Unknown keys are rejected.'+ ),+})+export const customerJourneysCreateBodyNameMax = 400export const CustomerJourneysCreateBody = /* @__PURE__ */ zod.object({diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex 2c6d19fbabd0..999b22d16dc2 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -9,6 +9,12 @@ feature: customer_analyticsurl_prefix: /customer-analyticsui_apps: {}tools:+ accounts-create:+ operation: accounts_create+ enabled: false+ accounts-list:+ operation: accounts_list+ enabled: falsecustomer-journeys-create:operation: customer_journeys_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 322d93c7bb82..119c1671f646 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -43,6 +43,53 @@ export namespace Schemas {Direct: 'direct',} as const;+ /**+ * Typed account properties: assignment fields (csm, account_executive, account_owner). Defaults to an empty object. Unknown keys are rejected.+ * @nullable+ */+ export type AccountProperties = {+ /** @nullable */+ csm?: {+ id: number;+ email: string;+ } | null;+ /** @nullable */+ account_executive?: {+ id: number;+ email: string;+ } | null;+ /** @nullable */+ account_owner?: {+ id: number;+ email: string;+ } | null;+ } | null;++ export interface Account {+ readonly id: string;+ /**+ * Human-readable name of the account.+ * @maxLength 400+ */+ name: string;+ /**+ * Identifier for the account in an external system (e.g. CRM ID). Optional.+ * @maxLength 400+ * @nullable+ */+ external_id?: string | null;+ /**+ * Typed account properties: assignment fields (csm, account_executive, account_owner). Defaults to an empty object. Unknown keys are rejected.+ * @nullable+ */+ properties?: AccountProperties;+ readonly created_at: string;+ /** @nullable */+ readonly created_by: number | null;+ /** @nullable */+ readonly updated_at: string | null;+ }+/*** * `event` - event* `event_metadata` - event_metadata@@ -21395,6 +21442,15 @@ export namespace Schemas {NeedsAttention: 'needs_attention',} as const;+ export interface PaginatedAccountList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: Account[];+ }+export interface PaginatedActionList {count: number;/** @nullable */@@ -25144,6 +25200,53 @@ export namespace Schemas {results: WebExperimentsAPI[];}+ /**+ * Typed account properties: assignment fields (csm, account_executive, account_owner). Defaults to an empty object. Unknown keys are rejected.+ * @nullable+ */+ export type PatchedAccountProperties = {+ /** @nullable */+ csm?: {+ id: number;+ email: string;+ } | null;+ /** @nullable */+ account_executive?: {+ id: number;+ email: string;+ } | null;+ /** @nullable */+ account_owner?: {+ id: number;+ email: string;+ } | null;+ } | null;++ export interface PatchedAccount {+ readonly id?: string;+ /**+ * Human-readable name of the account.+ * @maxLength 400+ */+ name?: string;+ /**+ * Identifier for the account in an external system (e.g. CRM ID). Optional.+ * @maxLength 400+ * @nullable+ */+ external_id?: string | null;+ /**+ * Typed account properties: assignment fields (csm, account_executive, account_owner). Defaults to an empty object. Unknown keys are rejected.+ * @nullable+ */+ properties?: PatchedAccountProperties;+ readonly created_at?: string;+ /** @nullable */+ readonly created_by?: number | null;+ /** @nullable */+ readonly updated_at?: string | null;+ }+/*** Serializer mixin that handles tags for objects.*/@@ -39005,6 +39108,17 @@ export namespace Schemas {search?: string;};+ export type AccountsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type ApprovalPoliciesListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.tsindex 88ef08614f20..d4f38fde2034 100644--- a/services/mcp/src/lib/oauth-scopes.generated.ts+++ b/services/mcp/src/lib/oauth-scopes.generated.ts@@ -15,6 +15,8 @@ export const OAUTH_SCOPES_SUPPORTED = ['action:write','access_control:read','access_control:write',+ 'account:read',+ 'account:write','activity_log:read','activity_log:write','alert:read',