Skip to content

: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.

feat(customer-analytics): let project secret keys create external accounts (#107740)

Arthur Moreira de Deus014a0d93d125
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index acc663f5f19f..180b7a85c1a5 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -299,6 +299,7 @@ export const PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION = [
'endpoint:read',
'feature_flag:read',
'account:read',
+ 'account:write',
'loop:write',
'experiment:read',
'offline_evaluation_ingestion:write',
diff --git a/posthog/scopes.py b/posthog/scopes.py
index fea3bcc87451..c4f970fa3d41 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -232,6 +232,9 @@ PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIS
# Gated on a PSAK so the team-wide secret_api_token (readable by any project member)
# can't be used to sidestep per-user account access controls.
("account", "read"),
+ # Lets a service create customer analytics accounts through the external account POST.
+ # Updates on that route stay team-token only.
+ ("account", "write"),
# First write-capable PSAK scope: lets a service credential fire a loop via
# `loops/:id/trigger/`. PSAKs are project-wide, so a leaked key can fire any loop
# in the project (accepted and documented in products/tasks/docs/LOOPS.md).
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index caf35d8d1189..cf6ec0a968a4 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -580,11 +580,17 @@ def list_account_external_ids_for_audience(
def create_external_account(
- team: Team, *, external_id: str, workflow_id: str | None = None
+ team: Team,
+ *,
+ external_id: str,
+ name: str | None = None,
+ properties: dict | None = None,
+ workflow_id: str | None = None,
) -> tuple[contracts.ExternalAccount, bool]:
"""Get-or-create an account by external id for the external API. Returns the account and
- whether it was created; an existing account is returned untouched. The name comes from the
- matching group's ``name`` property (fallback: the external id). Attribution goes to the
+ whether it was created; an existing account is returned untouched, so a supplied ``name``
+ or ``properties`` never overwrite it. Without a ``name``, the name comes from the matching group's ``name``
+ property (fallback: the external id). Attribution goes to the
originating workflow (activity-log trigger) — there is no acting user on this path.
On workflow-originated creates, warehouse-backed custom properties are synced inline
(best-effort) so the response already carries them.
@@ -594,7 +600,11 @@ def create_external_account(
return _to_external_account(existing), False
trigger = Trigger(job_type="hog_flow", job_id=workflow_id, payload={}) if workflow_id else None
account = create_account(
- team=team, name=_account_name_from_group(team, external_id), external_id=external_id, trigger=trigger
+ team=team,
+ name=name or _account_name_from_group(team, external_id),
+ external_id=external_id,
+ properties=properties,
+ trigger=trigger,
)
if workflow_id is not None:
# Synchronous so the workflow can read the values in its next step; best-effort inside —
@@ -3585,7 +3595,6 @@ def create_account(
was_impersonated=was_impersonated,
trigger=trigger,
)
- schedule_email_thread_link_recalculation(team.pk)
return account
diff --git a/products/customer_analytics/backend/presentation/views/account_actions.py b/products/customer_analytics/backend/presentation/views/account_actions.py
index dce2021a7b89..a1f69ebf2929 100644
--- a/products/customer_analytics/backend/presentation/views/account_actions.py
+++ b/products/customer_analytics/backend/presentation/views/account_actions.py
@@ -24,6 +24,7 @@ from products.customer_analytics.backend.facade import (
from products.customer_analytics.backend.presentation.views.ownership_serializers import (
ExternalAccountOwnershipSerializer,
)
+from products.customer_analytics.backend.presentation.views.serializers import AccountPropertiesField
ACCOUNT_ACTION_AUTH_COUNTER = Counter(
"posthog_customer_analytics_account_action_auth_total",
@@ -158,7 +159,25 @@ class ExternalAccountCreateSerializer(serializers.Serializer):
max_length=400,
help_text=(
"External ID (group key) for the account. An account with this ID already existing is a no-op. "
- "The account name is derived from the matching group's `name` property, falling back to this ID."
+ "Without a `name`, the account name is derived from the matching group's `name` property, "
+ "falling back to this ID."
+ ),
+ )
+ name = serializers.CharField(
+ max_length=400,
+ required=False,
+ allow_blank=True,
+ allow_null=True,
+ help_text="Name for a new account. Ignored when the account already exists. Blank means no name.",
+ )
+ properties = AccountPropertiesField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Typed properties for a new account: website_domain, external system identifiers (stripe_customer_id, "
+ "hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, "
+ "metabase_link), email_domains and known_emails. Unknown keys are rejected. Ignored when the account "
+ "already exists."
),
)
@@ -246,8 +265,12 @@ def handle_account_create(request: Request, team: Team) -> Response:
account, created = facade.create_external_account(
team,
external_id=external_id,
+ name=data.get("name") or None,
+ properties=data.get("properties"),
workflow_id=_workflow_id_from_request(request),
)
+ except facade.AccountPropertiesValidationError as exc:
+ return Response({"error": f"Invalid account properties: {exc}"}, status=status.HTTP_400_BAD_REQUEST)
except facade.AccountConflictError:
# Lost a concurrent-create race; the account exists now, so honor no-op semantics.
existing = facade.get_external_account(team.id, external_id)
diff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.py
index a100241ac43f..1597b7b324fe 100644
--- a/products/customer_analytics/backend/presentation/views/external.py
+++ b/products/customer_analytics/backend/presentation/views/external.py
@@ -6,7 +6,8 @@ authenticate via the team secret API token passed as a Bearer token in the
Authorization header. The bulk account list instead authenticates via a project
secret API key or personal API key carrying the ``account:read`` scope, because the team token is
readable by every project member and must not unlock a team-wide account export.
-The single-account GET accepts either credential; its writes stay team-token only.
+The single-account GET accepts either credential, and so does POST, where a project secret
+API key needs the ``account:write`` scope. PATCH stays team-token only.
The team token deliberately grants single-account writes (create, tags,
relationships, custom property values) without per-user ``account`` scope checks:
@@ -54,6 +55,7 @@ from products.customer_analytics.backend.facade import api as facade
from products.customer_analytics.backend.facade.constants import CUSTOMER_ANALYTICS_CSP_FLAG
from products.customer_analytics.backend.presentation.views.account_actions import (
ACCOUNT_ACTION_AUTH_COUNTER,
+ ExternalAccountCreateSerializer,
ExternalAccountCustomPropertiesSerializer,
handle_account_create,
handle_account_get,
@@ -68,6 +70,7 @@ logger = structlog.get_logger(__name__)
EXTERNAL_ACCOUNT_LIST_MAX_LIMIT = 100
EXTERNAL_ACCOUNT_READ_SCOPE = "account:read"
+EXTERNAL_ACCOUNT_WRITE_SCOPE = "account:write"
class _ExternalAccountThrottle(SimpleRateThrottle):
@@ -195,8 +198,8 @@ def _authenticate_team(request: Request) -> tuple[Team, None] | tuple[None, Resp
return team, None
-def _authenticate_psak_team(request: Request) -> tuple[Team, None] | tuple[None, Response]:
- """Resolve the team from a project secret API key with the ``account:read`` scope."""
+def _authenticate_psak_team(request: Request, required_scope: str) -> tuple[Team, None] | tuple[None, Response]:
+ """Resolve the team from a project secret API key with ``required_scope``."""
if not is_authenticated_via_project_secret_api_key(request):
return None, Response({"error": "Missing or invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)
@@ -205,22 +208,33 @@ def _authenticate_psak_team(request: Request) -> tuple[Team, None] | tuple[None,
key_scopes = set(get_authenticator_scopes(authenticator) or [])
# A key that may write accounts may read them too; the reverse does not hold.
- valid_scopes = {EXTERNAL_ACCOUNT_READ_SCOPE, "account:write"}
+ valid_scopes = {required_scope, EXTERNAL_ACCOUNT_WRITE_SCOPE}
if "*" not in key_scopes and key_scopes.isdisjoint(valid_scopes):
return None, Response(
- {"error": f"API key missing required scope '{EXTERNAL_ACCOUNT_READ_SCOPE}'"},
+ {"error": f"API key missing required scope '{required_scope}'"},
status=status.HTTP_403_FORBIDDEN,
)
return psak.team, None
-def _authenticate_team_for_write(request: Request) -> tuple[Team, None] | tuple[None, Response]:
- """Writes stay team-token only. A project secret API key is rejected explicitly, because
- the team-token lookup treats it as an unknown token and answers 401 instead of 403."""
+def _authenticate_team_or_psak(request: Request, psak_scope: str) -> tuple[Team, None] | tuple[None, Response]:
+ if is_authenticated_via_project_secret_api_key(request):
+ return _authenticate_psak_team(request, psak_scope)
+ return _authenticate_team(request)
+
+
+def _get_auth_method_label(request: Request) -> str:
+ return "project_secret_api_key" if is_authenticated_via_project_secret_api_key(request) else "secret_api_token"
+
+
+def _authenticate_team_for_update(request: Request) -> tuple[Team, None] | tuple[None, Response]:
+ """Updates stay team-token only: they change tags, relationships and churn state. A project
+ secret API key is rejected explicitly, because the team-token lookup treats it as an
+ unknown token and answers 401 instead of 403."""
if is_authenticated_via_project_secret_api_key(request):
return None, Response(
- {"error": "Project secret API keys can only read accounts on this route"},
+ {"error": "Project secret API keys cannot update accounts on this route"},
status=status.HTTP_403_FORBIDDEN,
)
return _authenticate_team(request)
@@ -279,7 +293,8 @@ class ExternalAccountView(APIView):
PATCH /api/customer_analytics/external/account — Update an account's relationships, tags, and churn state
GET accepts either the team secret_api_token or a project secret API key with the
- ``account:read`` scope as a Bearer token. POST and PATCH accept only the team
+ ``account:read`` scope as a Bearer token. POST accepts the team secret_api_token or a
+ project secret API key with the ``account:write`` scope. PATCH accepts only the team
secret_api_token.
"""
@@ -327,17 +342,12 @@ class ExternalAccountView(APIView):
),
)
def get(self, request: Request) -> Response:
- if is_authenticated_via_project_secret_api_key(request):
- team, error = _authenticate_psak_team(request)
- auth_method = "project_secret_api_key"
- else:
- team, error = _authenticate_team(request)
- auth_method = "secret_api_token"
+ team, error = _authenticate_team_or_psak(request, EXTERNAL_ACCOUNT_READ_SCOPE)
if error:
return error
assert team is not None
- ACCOUNT_ACTION_AUTH_COUNTER.labels(auth_method=auth_method, http_method="get").inc()
+ ACCOUNT_ACTION_AUTH_COUNTER.labels(auth_method=_get_auth_method_label(request), http_method="get").inc()
external_id = request.query_params.get("external_id", "").strip()
if not external_id:
@@ -345,22 +355,41 @@ class ExternalAccountView(APIView):
return handle_account_get(team, external_id)
- # The write operations stay out of the generated schema. drf-spectacular renders a PATCH body
- # as fully optional although this route requires external_id, and validation failures return
- # field-keyed errors that ExternalAccountErrorSerializer does not describe.
- @extend_schema(exclude=True)
+ @extend_schema(
+ request=ExternalAccountCreateSerializer,
+ responses={
+ 200: OpenApiResponse(response=ExternalAccountSerializer, description="The account already existed."),
+ 201: OpenApiResponse(response=ExternalAccountSerializer, description="The account was created."),
+ 400: OpenApiResponse(response=OpenApiTypes.OBJECT, description="Invalid request body."),
+ 401: OpenApiResponse(
+ response=ExternalAccountErrorSerializer, description="Missing or invalid Bearer token."
+ ),
+ 403: OpenApiResponse(
+ response=ExternalAccountErrorSerializer,
+ description="Project secret API key does not carry the account:write scope.",
+ ),
+ },
+ summary="Create an external customer analytics account",
+ description=(
+ "Create an account by external ID. If the account already exists, return it unchanged with HTTP 200. "
+ "Accepts the team secret API token or a project secret API key with the `account:write` scope."
+ ),
+ )
def post(self, request: Request) -> Response:
- team, error = _authenticate_team_for_write(request)
+ team, error = _authenticate_team_or_psak(request, EXTERNAL_ACCOUNT_WRITE_SCOPE)
if error:
return error
assert team is not None
- ACCOUNT_ACTION_AUTH_COUNTER.labels(auth_method="secret_api_token", http_method="post").inc()
+ ACCOUNT_ACTION_AUTH_COUNTER.labels(auth_method=_get_auth_method_label(request), http_method="post").inc()
return handle_account_create(request, team)
+ # PATCH stays out of the generated schema. drf-spectacular renders its body as fully optional
+ # although this route requires external_id, and validation failures return field-keyed errors
+ # that ExternalAccountErrorSerializer does not describe.
@extend_schema(exclude=True)
def patch(self, request: Request) -> Response:
- team, error = _authenticate_team_for_write(request)
+ team, error = _authenticate_team_for_update(request)
if error:
return error
@@ -551,7 +580,7 @@ class ExternalAccountListView(APIView):
team = None
access = None
if not personal_key:
- team, error = _authenticate_psak_team(request)
+ team, error = _authenticate_psak_team(request, EXTERNAL_ACCOUNT_READ_SCOPE)
if error:
return error
query_serializer = ExternalAccountListQuerySerializer(data=request.query_params)
diff --git a/products/customer_analytics/backend/test/test_email_account_matching.py b/products/customer_analytics/backend/test/test_email_account_matching.py
index 028f23a05480..debcf7c1d3cd 100644
--- a/products/customer_analytics/backend/test/test_email_account_matching.py
+++ b/products/customer_analytics/backend/test/test_email_account_matching.py
@@ -348,8 +348,7 @@ class TestEmailAccountMatching(BaseTest):
properties={"known_emails": ["[email protected]"]},
)
- mock_schedule.assert_called_once_with(self.team.id)
- mock_schedule.reset_mock()
+ mock_schedule.assert_not_called()
with self.captureOnCommitCallbacks(execute=True):
api.update_account(
diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.py
index b2d2177b4230..f426f9e16467 100644
--- a/products/customer_analytics/backend/test/test_external.py
+++ b/products/customer_analytics/backend/test/test_external.py
@@ -120,11 +120,18 @@ class TestExternalAccountAPI(APIBaseTest):
read_psak = self._create_psak_token(scopes=["account:read"], label="read")
wrong_scope_psak = self._create_psak_token(scopes=["endpoint:read"], label="wrong-scope")
self.mock_csp_enabled.return_value = False
+ write_psak = self._create_psak_token(scopes=["account:write"], label="write")
for token in [self.team.secret_api_token, read_psak, wrong_scope_psak]:
with self.subTest(token=token):
response = self._get(token=token)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response.json(), {"error": "Invalid API key"})
+ for token in [self.team.secret_api_token, write_psak]:
+ with self.subTest(token=token, method="post"):
+ response = self._post({"external_id": "acme-2"}, token=token)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.json(), {"error": "Invalid API key"})
+ self.assertFalse(Account.objects.for_team(self.team.id).filter(external_id="acme-2").exists())
def test_get_accepts_project_secret_api_key_with_account_read_scope(self):
response = self._get(token=self._create_psak_token(scopes=["account:read"]))
@@ -138,11 +145,14 @@ class TestExternalAccountAPI(APIBaseTest):
@parameterized.expand(
[
("post_read_scope", "_post", ["account:read"], {"external_id": "acme-2"}),
- ("post_write_scope", "_post", ["account:write"], {"external_id": "acme-2"}),
+ ("post_unrelated_scope", "_post", ["endpoint:read"], {"external_id": "acme-2"}),
("patch_read_scope", "_patch", ["account:read"], {"external_id": "acme-1", "churned_at": "2026-08-01"}),
+ ("patch_write_scope", "_patch", ["account:write"], {"external_id": "acme-1", "churned_at": "2026-08-01"}),
]
)
- def test_writes_reject_project_secret_api_key(self, _name, request_method, scopes, payload):
+ def test_writes_reject_project_secret_api_key(
+ self, _name: str, request_method: str, scopes: list[str], payload: dict[str, str]
+ ) -> None:
token = self._create_psak_token(scopes=scopes)
response = getattr(self, request_method)(payload, token=token)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
@@ -150,6 +160,18 @@ class TestExternalAccountAPI(APIBaseTest):
self.account.refresh_from_db()
self.assertIsNone(self.account.churned_at)
+ def test_post_accepts_project_secret_api_key_with_account_write_scope(self) -> None:
+ token = self._create_psak_token(scopes=["account:write"])
+
+ created = self._post({"external_id": "acme-2", "name": "Acme Two"}, token=token)
+ repeated = self._post({"external_id": "acme-2", "name": "Renamed"}, token=token)
+
+ self.assertEqual(created.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(repeated.status_code, status.HTTP_200_OK)
+ self.assertEqual(repeated.json()["id"], created.json()["id"])
+ accounts = Account.objects.for_team(self.team.id).filter(external_id="acme-2")
+ self.assertEqual([account.name for account in accounts], ["Acme Two"])
+
def test_project_secret_api_keys_share_a_team_rate_limit(self):
cache.clear()
self.addCleanup(cache.clear)
@@ -523,6 +545,25 @@ class TestExternalAccountAPI(APIBaseTest):
self.assertEqual(account.name, "New Corp")
self.assertIsNone(account.created_by)
+ @parameterized.expand(
+ [
+ ("supplied_name", {"name": " Supplied Corp "}, "Supplied Corp"),
+ ("blank_name", {"name": " "}, "New Corp"),
+ ("null_name", {"name": None}, "New Corp"),
+ ]
+ )
+ def test_post_supplied_name_overrides_group_name(
+ self, _name: str, extra_payload: dict[str, str | None], expected_name: str
+ ) -> None:
+ self.team.customer_analytics_config.account_group_type_index = 0
+ self.team.customer_analytics_config.save()
+ create_group(team=self.team, group_type_index=0, group_key="new-1", group_properties={"name": "New Corp"})
+
+ response = self._post({"external_id": "new-1", **extra_payload})
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.json()["name"], expected_name)
+
@parameterized.expand(
[
("no_group_type_configured", False, False),
@@ -537,17 +578,53 @@ class TestExternalAccountAPI(APIBaseTest):
if create_nameless_group:
create_group(team=self.team, group_type_index=0, group_key="new-1", group_properties={"plan": "free"})
- response = self._post({"external_id": "new-1"})
+ response = self._post({"external_id": "new-1", "name": ""})
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.json()["name"], "new-1")
def test_post_existing_account_is_a_noop(self):
- response = self._post({"external_id": "acme-1"})
+ response = self._post(
+ {"external_id": "acme-1", "name": "Renamed", "properties": {"stripe_customer_id": "cus_new"}}
+ )
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["name"], "Acme Corp")
self.account.refresh_from_db()
self.assertEqual(self.account.name, "Acme Corp")
+ self.assertIsNone(self.account.properties.stripe_customer_id)
+
+ def test_post_stores_supplied_properties(self) -> None:
+ response = self._post(
+ {
+ "external_id": "new-1",
+ "properties": {
+ "website_domain": "https://www.example.com/pricing",
+ "stripe_customer_id": "cus_123",
+ "sfdc_id": "001ABC",
+ "slack_channel_id": "C0123",
+ },
+ }
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ properties = Account.objects.for_team(self.team.id).get(external_id="new-1").properties
+ self.assertEqual(properties.website_domain, "example.com")
+ self.assertEqual(properties.stripe_customer_id, "cus_123")
+ self.assertEqual(properties.sfdc_id, "001ABC")
+ self.assertEqual(properties.slack_channel_id, "C0123")
+
+ @parameterized.expand(
+ [
+ ("unknown_key", {"favorite_color": "blue"}),
+ ("wrong_type", {"email_domains": "example.com"}),
+ ("not_an_object", ["cus_123"]),
+ ]
+ )
+ def test_post_rejects_invalid_properties(self, _name: str, properties: object) -> None:
+ response = self._post({"external_id": "new-1", "properties": properties})
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertFalse(Account.objects.for_team(self.team.id).filter(external_id="new-1").exists())
@parameterized.expand([("missing", {}), ("blank", {"external_id": " "})])
def test_post_requires_external_id(self, _name, payload):
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index c40b7a32e3a6..84278e73971d 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -161,6 +161,57 @@ export interface ExternalAccountErrorApi {
error: string
}
+/**
+ * Typed properties for a new account: website_domain, external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link), email_domains and known_emails. Unknown keys are rejected. Ignored when the account already exists.
+ * @nullable
+ */
+export type ExternalAccountCreateApiProperties = {
+ /**
+ * Primary company website hostname used for account identity and logo lookup.
+ * @nullable
+ */
+ website_domain?: string | null
+ /** Email domains owned by this account's company, used to match inbound touchpoints to the account. */
+ email_domains?: string[]
+ /** Individual email addresses pinned to this account, matched before the domain fallback. */
+ known_emails?: string[]
+ /** @nullable */
+ stripe_customer_id?: string | null
+ /** @nullable */
+ hubspot_deal_id?: string | null
+ /** @nullable */
+ billing_id?: string | null
+ /** @nullable */
+ sfdc_id?: string | null
+ /** @nullable */
+ zendesk_id?: string | null
+ /** @nullable */
+ slack_channel_id?: string | null
+ /** @nullable */
+ usage_dashboard_link?: string | null
+ /** @nullable */
+ metabase_link?: string | null
+} | null | null
+
+export interface ExternalAccountCreateApi {
+ /**
+ * External ID (group key) for the account. An account with this ID already existing is a no-op. Without a `name`, the account name is derived from the matching group's `name` property, falling back to this ID.
+ * @maxLength 400
+ */
+ external_id: string
+ /**
+ * Name for a new account. Ignored when the account already exists. Blank means no name.
+ * @maxLength 400
+ * @nullable
+ */
+ name?: string | null
+ /**
+ * Typed properties for a new account: website_domain, external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link), email_domains and known_emails. Unknown keys are rejected. Ignored when the account already exists.
+ * @nullable
+ */
+ properties?: ExternalAccountCreateApiProperties
+}
+
export interface ExternalAccountListAssignmentApi {
/** PostHog user id of the assigned user. */
user_id: number
@@ -4411,6 +4462,8 @@ export type CustomerAnalyticsExternalAccountRetrieveParams = {
external_id: string
}
+export type CustomerAnalyticsExternalAccountCreate400 = { [key: string]: unknown }
+
export type CustomerAnalyticsExternalAccountsRetrieveParams = {
/**
* When true, return only accounts with at least one active relationship assignment to a current member of the project's organization.
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index 66e77832620c..16b6e95f2cb1 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -71,6 +71,7 @@ import type {
EventStreamMemberWriteApi,
EventStreamTestMessageApi,
ExternalAccountApi,
+ ExternalAccountCreateApi,
ExternalAccountListPageApi,
FeatureRequestAddAccountApi,
FeatureRequestApi,
@@ -172,6 +173,26 @@ export const customerAnalyticsExternalAccountRetrieve = async (
})
}
+export const getCustomerAnalyticsExternalAccountCreateUrl = () => {
+ return `/api/customer_analytics/external/account`
+}
+
+/**
+ * Create an account by external ID. If the account already exists, return it unchanged with HTTP 200. Accepts the team secret API token or a project secret API key with the `account:write` scope.
+ * @summary Create an external customer analytics account
+ */
+export const customerAnalyticsExternalAccountCreate = async (
+ externalAccountCreateApi: ExternalAccountCreateApi,
+ options?: RequestInit
+): Promise<ExternalAccountApi> => {
+ return apiMutator<ExternalAccountApi>(getCustomerAnalyticsExternalAccountCreateUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(externalAccountCreateApi),
+ })
+}
+
export const getCustomerAnalyticsExternalAccountsRetrieveUrl = (
params?: CustomerAnalyticsExternalAccountsRetrieveParams
) => {
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index 497e5bfa1f1d..8f39604cdb9d 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -9,6 +9,57 @@
*/
import * as zod from 'zod'
+/**
+ * Create an account by external ID. If the account already exists, return it unchanged with HTTP 200. Accepts the team secret API token or a project secret API key with the `account:write` scope.
+ * @summary Create an external customer analytics account
+ */
+export const customerAnalyticsExternalAccountCreateBodyExternalIdMax = 400
+
+export const customerAnalyticsExternalAccountCreateBodyNameMax = 400
+
+export const CustomerAnalyticsExternalAccountCreateBody = /* @__PURE__ */ zod.object({
+ external_id: zod
+ .string()
+ .max(customerAnalyticsExternalAccountCreateBodyExternalIdMax)
+ .describe(
+ "External ID (group key) for the account. An account with this ID already existing is a no-op. Without a `name`, the account name is derived from the matching group's `name` property, falling back to this ID."
+ ),
+ name: zod
+ .string()
+ .max(customerAnalyticsExternalAccountCreateBodyNameMax)
+ .nullish()
+ .describe('Name for a new account. Ignored when the account already exists. Blank means no name.'),
+ properties: zod
+ .object({
+ website_domain: zod
+ .string()
+ .nullish()
+ .describe('Primary company website hostname used for account identity and logo lookup.'),
+ email_domains: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ "Email domains owned by this account's company, used to match inbound touchpoints to the account."
+ ),
+ known_emails: zod
+ .array(zod.string())
+ .optional()
+ .describe('Individual email addresses pinned to this account, matched before the domain fallback.'),
+ 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(),
+ slack_channel_id: zod.string().nullish(),
+ usage_dashboard_link: zod.string().nullish(),
+ metabase_link: zod.string().nullish(),
+ })
+ .nullish()
+ .describe(
+ 'Typed properties for a new account: website_domain, external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link), email_domains and known_emails. Unknown keys are rejected. Ignored when the account already exists.'
+ ),
+})
+
export const accountRelationshipDefinitionsCreateBodyNameMax = 400
export const accountRelationshipDefinitionsCreateBodyIsSingleHolderDefault = true
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index 35cf594611f2..6aa50c830d40 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -802,6 +802,9 @@ tools:
customer-analytics-accounts-table-query-create:
operation: customer_analytics_accounts_table_query_create
enabled: false
+ customer-analytics-external-account-create:
+ operation: customer_analytics_external_account_create
+ enabled: false
customer-analytics-external-account-retrieve:
operation: customer_analytics_external_account_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 273aa201f6f5..86427237265c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -43030,6 +43030,57 @@ export namespace Schemas {
custom_properties: ExternalAccountCustomProperties;
}
+ /**
+ * Typed properties for a new account: website_domain, external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link), email_domains and known_emails. Unknown keys are rejected. Ignored when the account already exists.
+ * @nullable
+ */
+ export type ExternalAccountCreateProperties = {
+ /**
+ * Primary company website hostname used for account identity and logo lookup.
+ * @nullable
+ */
+ website_domain?: string | null;
+ /** Email domains owned by this account's company, used to match inbound touchpoints to the account. */
+ email_domains?: string[];
+ /** Individual email addresses pinned to this account, matched before the domain fallback. */
+ known_emails?: string[];
+ /** @nullable */
+ stripe_customer_id?: string | null;
+ /** @nullable */
+ hubspot_deal_id?: string | null;
+ /** @nullable */
+ billing_id?: string | null;
+ /** @nullable */
+ sfdc_id?: string | null;
+ /** @nullable */
+ zendesk_id?: string | null;
+ /** @nullable */
+ slack_channel_id?: string | null;
+ /** @nullable */
+ usage_dashboard_link?: string | null;
+ /** @nullable */
+ metabase_link?: string | null;
+ } | null | null;
+
+ export interface ExternalAccountCreate {
+ /**
+ * External ID (group key) for the account. An account with this ID already existing is a no-op. Without a `name`, the account name is derived from the matching group's `name` property, falling back to this ID.
+ * @maxLength 400
+ */
+ external_id: string;
+ /**
+ * Name for a new account. Ignored when the account already exists. Blank means no name.
+ * @maxLength 400
+ * @nullable
+ */
+ name?: string | null;
+ /**
+ * Typed properties for a new account: website_domain, external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link), email_domains and known_emails. Unknown keys are rejected. Ignored when the account already exists.
+ * @nullable
+ */
+ properties?: ExternalAccountCreateProperties;
+ }
+
export interface ExternalAccountError {
/** What went wrong with the request. */
error: string;
@@ -107454,6 +107505,8 @@ export namespace Schemas {
external_id: string;
};
+ export type CustomerAnalyticsExternalAccountCreate400 = { [key: string]: unknown };
+
export type CustomerAnalyticsExternalAccountsRetrieveParams = {
/**
* When true, return only accounts with at least one active relationship assignment to a current member of the project's organization.