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): account notebooks (#59935)

Arthur Moreira de Deus17c558db7339
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 9f238465ceeb..d1914d8f2fa9 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -3975,13 +3975,13 @@ snapshots:
scenes-app-batchexports--runs-with-data--light:
hash: v1.k794b7964.f4a8d5cc4f5447f093d5ddbbcd8572e13f7297a7db8a89504f9290226e60a2bc._CkUe6i49hMMGaDUNDHeNZDgaVp5DJQCay44V8WqfR4
scenes-app-customer-analytics-accounts--default--dark:
- hash: v1.k794b7964.fd9405867e8535a41514151b501adebee6e68e397c6639b8659b16e5321a4eb1.OhMniev44ZDEnT5QywBOE08-CGReq52bQG-8OeOweLQ
+ hash: v1.k794b7964.b64ab80fac4a73cee1ff6a383ad9f40961b061f38c606014b38c683ce6f399fb.BGLWJjIrm8jKJ0cgbg0N8-tr7KL675JJqN_9SkLCgmA
scenes-app-customer-analytics-accounts--default--light:
- hash: v1.k794b7964.4ef351ff95ff81eb5fd835e24660aef0ddf95264339a4b3a98794daf14a846f4.JwzzYwyVeNkrpI_vncMRDJeTrqkOts_oIX4eTKCBALc
+ hash: v1.k794b7964.21d11055ac489c5d965e0d3256ce0986ca896c1fc92ecb21c47a22bca77c929b.bVU8oCCiqYQT14HPANB_-ghcaWBP16m1TJF4N2H5drs
scenes-app-customer-analytics-accounts--empty--dark:
- hash: v1.k794b7964.0955aeed4cb1f5a282fca7174abd372c33241408d833fe3f151785980e75ebea.PSbb0da1CRNWCZR8qZnoY6DELEAs6LAuH9xDObSCtp0
+ hash: v1.k794b7964.1db26d99c1ac9c7ea882bae7d36a3d4fcc234e21d8cd28cc1ededb941a687cdf.OcbjFe5xD5bLFViFj0meBcCEoxa2bhK9VzJRPF0dQHo
scenes-app-customer-analytics-accounts--empty--light:
- hash: v1.k794b7964.bbe7c2ee845832842f8ea2092505b75ef75ab3efc51c7697f90ba7c25025d65a.Ttybs24_wfKgqh879lBbYHH-WqV9XgZJtSEJbc6csh0
+ hash: v1.k794b7964.924b1f7107778ab02e2986a600cb325ffd6c3d7a1f1828cd2dcd4b5cc51e5b91.GGu3igWGbRQbv3o129YtgLqk_EcmpDePG3KDI4UhklE
scenes-app-customer-analytics-accounts--feature-gate-off--dark:
hash: v1.k794b7964.7750bce37ad591ab773135ad1a9b8738ac790727774c03d3aa7b5abbfc42fab0.KbXf74dR5pSVh6Wc8mSjrNGqL8LbTcsMl78W7WVvTXU
scenes-app-customer-analytics-accounts--feature-gate-off--light:
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index e064e0e6b36d..4b24d2dce6cb 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -438,13 +438,20 @@ environments_router.register(
["team_id"],
)
-environments_router.register(
+environment_accounts_router = environments_router.register(
r"accounts",
customer_analytics.AccountViewSet,
"environment_accounts",
["team_id"],
)
+environment_accounts_router.register(
+ r"notebooks",
+ customer_analytics.AccountNotebookViewSet,
+ "environment_account_notebooks",
+ ["team_id", "account_id"],
+)
+
projects_router.register(
r"data_management",
DataManagementViewSet,
diff --git a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
index 495d11a6596c..d384e353750e 100644
--- a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
+++ b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
@@ -943,7 +943,8 @@
'''
SELECT "posthog_resourcenotebook"."id",
"posthog_resourcenotebook"."notebook_id",
- "posthog_resourcenotebook"."group_id"
+ "posthog_resourcenotebook"."group_id",
+ "posthog_resourcenotebook"."account_id"
FROM "posthog_resourcenotebook"
WHERE "posthog_resourcenotebook"."notebook_id" = '00000000000000000000000000000000'::uuid
'''
@@ -952,7 +953,8 @@
'''
SELECT "posthog_resourcenotebook"."id",
"posthog_resourcenotebook"."notebook_id",
- "posthog_resourcenotebook"."group_id"
+ "posthog_resourcenotebook"."group_id",
+ "posthog_resourcenotebook"."account_id"
FROM "posthog_resourcenotebook"
WHERE "posthog_resourcenotebook"."notebook_id" = '00000000000000000000000000000000'::uuid
'''
diff --git a/products/customer_analytics/backend/api/serializers.py b/products/customer_analytics/backend/api/serializers.py
index 314b5daf099f..e57460cbecaa 100644
--- a/products/customer_analytics/backend/api/serializers.py
+++ b/products/customer_analytics/backend/api/serializers.py
@@ -4,10 +4,12 @@ from drf_spectacular.utils import extend_schema_field
from pydantic import ValidationError as PydanticValidationError
from rest_framework import serializers
+from posthog.api.shared import UserBasicSerializer
from posthog.api.tagged_item import TaggedItemSerializerMixin
from products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfig
from products.customer_analytics.backend.models.account import AccountProperties
+from products.notebooks.backend.models import Notebook
_ACCOUNT_ASSIGNMENT_SCHEMA = {
"type": "object",
@@ -150,6 +152,12 @@ class AccountSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):
required=False,
help_text="Tag names attached to the account. Pass a list to replace existing tags.",
)
+ notebooks = serializers.SerializerMethodField(
+ help_text=(
+ "Short IDs of the internal notebooks linked to this account, used to persist investigations, "
+ "call notes, and other free-form context. Empty list if no notebooks have been created for the account."
+ )
+ )
class Meta:
model = Account
@@ -159,17 +167,23 @@ class AccountSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):
"external_id",
"properties",
"tags",
+ "notebooks",
"created_at",
"created_by",
"updated_at",
]
read_only_fields = [
"id",
+ "notebooks",
"created_at",
"created_by",
"updated_at",
]
+ @extend_schema_field({"type": "array", "items": {"type": "string"}})
+ def get_notebooks(self, obj: Account) -> list[str]:
+ return [link.notebook.short_id for link in obj.notebooks.all()]
+
def validate_properties(self, value):
if value is None:
return {}
@@ -208,3 +222,48 @@ def _format_pydantic_errors(exc: PydanticValidationError) -> list[str]:
loc = ".".join(str(part) for part in err["loc"])
messages.append(f"{loc}: {err['msg']}" if loc else err["msg"])
return messages
+
+
+class AccountNotebookSerializer(serializers.ModelSerializer):
+ created_by = UserBasicSerializer(read_only=True)
+ last_modified_by = UserBasicSerializer(read_only=True)
+ title = serializers.CharField(
+ max_length=256,
+ required=False,
+ allow_blank=True,
+ allow_null=True,
+ help_text="Human-readable title of the account notebook.",
+ )
+ content = serializers.JSONField(
+ required=False,
+ allow_null=True,
+ help_text="Notebook content as a ProseMirror JSON document structure.",
+ )
+ text_content = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ allow_null=True,
+ help_text="Plain text representation of the notebook content for search.",
+ )
+
+ class Meta:
+ model = Notebook
+ fields = [
+ "id",
+ "short_id",
+ "title",
+ "content",
+ "text_content",
+ "created_at",
+ "created_by",
+ "last_modified_at",
+ "last_modified_by",
+ ]
+ read_only_fields = [
+ "id",
+ "short_id",
+ "created_at",
+ "created_by",
+ "last_modified_at",
+ "last_modified_by",
+ ]
diff --git a/products/customer_analytics/backend/api/test_views.py b/products/customer_analytics/backend/api/test_views.py
index 5799573eb054..ceb9f9d0c26a 100644
--- a/products/customer_analytics/backend/api/test_views.py
+++ b/products/customer_analytics/backend/api/test_views.py
@@ -773,10 +773,10 @@ class TestAccountViewSet(APIBaseTest):
account.tagged_items.create(tag=billing_tag)
account.tagged_items.create(tag=urgent_tag)
- with self.assertNumQueries(11):
+ with self.assertNumQueries(12):
# 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:
+ # because tagged_items and notebooks are 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
@@ -787,7 +787,8 @@ class TestAccountViewSet(APIBaseTest):
# 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)
+ # 11: prefetch resourcenotebook (joined with notebook) for the page
+ # 12: 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)
@@ -933,6 +934,205 @@ class TestAccountViewSet(APIBaseTest):
response = self.client.get(f"/api/environments/{self.team.id}/accounts/?csm=7")
assert [r["name"] for r in response.json()["results"]] == ["MyAccount"]
+ def test_retrieve_returns_empty_notebooks_when_none_linked(self):
+ account = self._create_account()
+
+ response = self.client.get(f"{self.endpoint_base}{account.id}/")
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code)
+ self.assertEqual(response.json()["notebooks"], [])
+
+ def test_retrieve_returns_all_linked_notebooks(self):
+ from products.notebooks.backend.models import Notebook, ResourceNotebook
+
+ account = self._create_account()
+ notebook_a = Notebook.objects.create(
+ team=self.team, title="A", content=[], visibility=Notebook.Visibility.INTERNAL
+ )
+ notebook_b = Notebook.objects.create(
+ team=self.team, title="B", content=[], visibility=Notebook.Visibility.INTERNAL
+ )
+ ResourceNotebook.objects.create(notebook=notebook_a, account=account)
+ ResourceNotebook.objects.create(notebook=notebook_b, account=account)
+
+ response = self.client.get(f"{self.endpoint_base}{account.id}/")
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code)
+ self.assertEqual(set(response.json()["notebooks"]), {notebook_a.short_id, notebook_b.short_id})
+
+ def test_list_includes_notebooks_field(self):
+ from products.notebooks.backend.models import Notebook, ResourceNotebook
+
+ account = self._create_account()
+ notebook = Notebook.objects.create(
+ team=self.team, title="Existing", content=[], visibility=Notebook.Visibility.INTERNAL
+ )
+ ResourceNotebook.objects.create(notebook=notebook, account=account)
+
+ response = self.client.get(self.endpoint_base)
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code)
+ result = next(r for r in response.json()["results"] if r["id"] == str(account.id))
+ self.assertEqual(result["notebooks"], [notebook.short_id])
+
+
+class TestAccountNotebookViewSet(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.account = Account.objects.unscoped().create(team=self.team, name="Acme Corp")
+ self.endpoint_base = f"/api/environments/{self.team.id}/accounts/{self.account.id}/notebooks/"
+
+ def test_create_account_notebook_uses_internal_visibility(self):
+ from products.notebooks.backend.models import Notebook, ResourceNotebook
+
+ response = self.client.post(
+ self.endpoint_base,
+ {"title": "Q3 call", "content": {"type": "doc", "content": []}},
+ format="json",
+ )
+
+ self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())
+ data = response.json()
+ self.assertIn("short_id", data)
+ self.assertEqual(data["title"], "Q3 call")
+
+ # nosemgrep: idor-lookup-without-team (test assertion)
+ notebook = Notebook.objects.get(short_id=data["short_id"])
+ self.assertEqual(notebook.team, self.team)
+ self.assertEqual(notebook.visibility, Notebook.Visibility.INTERNAL)
+ self.assertEqual(notebook.created_by, self.user)
+
+ self.assertTrue(
+ ResourceNotebook.objects.filter(notebook=notebook, account=self.account).exists(),
+ )
+
+ def test_list_returns_only_notebooks_for_account(self):
+ from products.notebooks.backend.models import Notebook, ResourceNotebook
+
+ account_notebook = Notebook.objects.create(
+ team=self.team, title="Account note", content={}, visibility=Notebook.Visibility.INTERNAL
+ )
+ ResourceNotebook.objects.create(notebook=account_notebook, account=self.account)
+
+ other_account = Account.objects.unscoped().create(team=self.team, name="Other")
+ other_notebook = Notebook.objects.create(
+ team=self.team, title="Other note", content={}, visibility=Notebook.Visibility.INTERNAL
+ )
+ ResourceNotebook.objects.create(notebook=other_notebook, account=other_account)
+
+ Notebook.objects.create(team=self.team, title="Standalone", content={}, visibility=Notebook.Visibility.DEFAULT)
+
+ response = self.client.get(self.endpoint_base)
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code)
+ short_ids = [n["short_id"] for n in response.json()["results"]]
+ self.assertEqual(short_ids, [account_notebook.short_id])
+
+ def test_retrieve_returns_notebook_for_account(self):
+ from products.notebooks.backend.models import Notebook, ResourceNotebook
+
+ notebook = Notebook.objects.create(
+ team=self.team, title="Note", content={"foo": "bar"}, visibility=Notebook.Visibility.INTERNAL
+ )
+ ResourceNotebook.objects.create(notebook=notebook, account=self.account)
+
+ response = self.client.get(f"{self.endpoint_base}{notebook.short_id}/")
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code)
+ data = response.json()
+ self.assertEqual(data["short_id"], notebook.short_id)
+ self.assertEqual(data["title"], "Note")
+ self.assertEqual(data["content"], {"foo": "bar"})
+
+ def test_retrieve_notebook_not_linked_to_account_returns_404(self):
+ from products.notebooks.backend.models import Notebook
+
+ unrelated = Notebook.objects.create(
+ team=self.team, title="Unrelated", content={}, visibility=Notebook.Visibility.DEFAULT
+ )
+
+ response = self.client.get(f"{self.endpoint_base}{unrelated.short_id}/")
+
+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
+
+ def test_destroy_notebook_for_account(self):
+ from products.notebooks.backend.models import Notebook, ResourceNotebook
+
+ notebook = Notebook.objects.create(
+ team=self.team, title="Note", content={}, visibility=Notebook.Visibility.INTERNAL
+ )
+ ResourceNotebook.objects.create(notebook=notebook, account=self.account)
+ notebook_pk = notebook.pk
+
+ response = self.client.delete(f"{self.endpoint_base}{notebook.short_id}/")
+
+ self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code)
+ # nosemgrep: idor-lookup-without-team (test assertion)
+ self.assertFalse(Notebook.objects.filter(pk=notebook_pk).exists())
+ self.assertFalse(ResourceNotebook.objects.filter(account=self.account).exists())
+
+ def test_create_for_unknown_account_returns_404(self):
+ bad_url = f"/api/environments/{self.team.id}/accounts/00000000-0000-0000-0000-000000000000/notebooks/"
+
+ response = self.client.post(bad_url, {"title": "X"}, format="json")
+
+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
+
+ def test_other_team_account_is_not_accessible(self):
+ other_team = Team.objects.create(organization=self.organization)
+ other_account = Account.objects.unscoped().create(team=other_team, name="Other team")
+
+ url = f"/api/environments/{self.team.id}/accounts/{other_account.id}/notebooks/"
+ response = self.client.post(url, {"title": "X"}, format="json")
+
+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
+
+ def test_internal_account_notebooks_do_not_appear_in_notebooks_list(self):
+ from products.notebooks.backend.models import Notebook, ResourceNotebook
+
+ notebook = Notebook.objects.create(
+ team=self.team, title="Account note", content={}, visibility=Notebook.Visibility.INTERNAL
+ )
+ ResourceNotebook.objects.create(notebook=notebook, account=self.account)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/notebooks/")
+ self.assertEqual(status.HTTP_200_OK, response.status_code)
+ short_ids = [n["short_id"] for n in response.json()["results"]]
+ self.assertNotIn(notebook.short_id, short_ids)
+
+ 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}abc123/"),
+ ("DELETE", f"{self.endpoint_base}abc123/"),
+ ]:
+ 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])
+
+ def test_list_excludes_non_internal_notebooks_linked_to_account(self):
+ from products.notebooks.backend.models import Notebook, ResourceNotebook
+
+ internal_notebook = Notebook.objects.create(
+ team=self.team, title="Internal", content={}, visibility=Notebook.Visibility.INTERNAL
+ )
+ ResourceNotebook.objects.create(notebook=internal_notebook, account=self.account)
+
+ default_notebook = Notebook.objects.create(
+ team=self.team, title="Default", content={}, visibility=Notebook.Visibility.DEFAULT
+ )
+ ResourceNotebook.objects.create(notebook=default_notebook, account=self.account)
+
+ response = self.client.get(self.endpoint_base)
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code)
+ short_ids = [n["short_id"] for n in response.json()["results"]]
+ self.assertIn(internal_notebook.short_id, short_ids)
+ self.assertNotIn(default_notebook.short_id, short_ids)
+
@pytest.mark.ee
class TestCustomerAnalyticsAccessControl(APIBaseTest):
@@ -1167,3 +1367,28 @@ class TestCustomerAnalyticsAccessControl(APIBaseTest):
response = self.client.get(self.accounts_url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ # -- Account notebooks inherit object-level access from the parent account --
+
+ def test_account_notebooks_404_when_parent_account_access_denied(self):
+ from ee.models.rbac.access_control import AccessControl
+
+ AccessControl.objects.create(
+ team=self.team,
+ resource="account",
+ resource_id=str(self.account.id),
+ access_level="none",
+ organization_member=OrganizationMembership.objects.get(
+ user=self.viewer_user, organization=self.organization
+ ),
+ )
+ self._set_access_level(self.viewer_user, resource="account", access_level="viewer")
+ self.client.force_login(self.viewer_user)
+
+ url = f"{self.accounts_url}{self.account.id}/notebooks/"
+
+ list_response = self.client.get(url)
+ self.assertEqual(list_response.status_code, status.HTTP_404_NOT_FOUND)
+
+ create_response = self.client.post(url, {"title": "x"}, format="json")
+ self.assertEqual(create_response.status_code, status.HTTP_404_NOT_FOUND)
diff --git a/products/customer_analytics/backend/api/views.py b/products/customer_analytics/backend/api/views.py
index 473f2984c705..17421eac2166 100644
--- a/products/customer_analytics/backend/api/views.py
+++ b/products/customer_analytics/backend/api/views.py
@@ -1,9 +1,12 @@
import json
-from django.db.models import Q
+from django.db import transaction
+from django.db.models import Prefetch, Q
+from django.shortcuts import get_object_or_404
-from drf_spectacular.utils import OpenApiParameter, OpenApiTypes, extend_schema
-from rest_framework import viewsets
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, extend_schema
+from rest_framework import mixins, viewsets
from rest_framework.exceptions import ValidationError
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -12,8 +15,14 @@ from posthog.api.utils import log_activity_from_viewset
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfig
-
-from .serializers import AccountSerializer, CustomerJourneySerializer, CustomerProfileConfigSerializer
+from products.notebooks.backend.models import Notebook, ResourceNotebook
+
+from .serializers import (
+ AccountNotebookSerializer,
+ AccountSerializer,
+ CustomerJourneySerializer,
+ CustomerProfileConfigSerializer,
+)
from .utils import log_customer_profile_config_activity
@@ -138,7 +147,9 @@ class AccountViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContr
return super().list(request, *args, **kwargs)
def safely_get_queryset(self, queryset):
- queryset = queryset.filter(team_id=self.team.id)
+ queryset = queryset.filter(team_id=self.team.id).prefetch_related(
+ Prefetch("notebooks", queryset=ResourceNotebook.objects.select_related("notebook"))
+ )
search = self.request.query_params.get("search", "").strip()
if search:
@@ -210,3 +221,59 @@ class AccountViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContr
def perform_destroy(self, instance):
log_activity_from_viewset(self, instance, activity="deleted", name=instance.name)
super().perform_destroy(instance)
+
+
+@extend_schema(
+ tags=["customer_analytics"],
+ parameters=[
+ OpenApiParameter(
+ name="account_id",
+ type=OpenApiTypes.UUID,
+ location=OpenApiParameter.PATH,
+ description="UUID of the parent account.",
+ ),
+ ],
+)
+class AccountNotebookViewSet(
+ TeamAndOrgViewSetMixin,
+ AccessControlViewSetMixin,
+ mixins.CreateModelMixin,
+ mixins.ListModelMixin,
+ mixins.RetrieveModelMixin,
+ mixins.DestroyModelMixin,
+ viewsets.GenericViewSet,
+):
+ scope_object = "account"
+ serializer_class = AccountNotebookSerializer
+ queryset = Notebook.objects.all()
+ lookup_field = "short_id"
+ filter_rewrite_rules = {"account_id": "resources__account_id"}
+
+ def _get_account(self) -> Account:
+ queryset = self.user_access_control.filter_queryset_by_access_level(
+ Account.objects.unscoped().filter(team_id=self.team.id),
+ )
+ return get_object_or_404(queryset, id=self.parents_query_dict["account_id"])
+
+ def safely_get_queryset(self, queryset):
+ self._get_account()
+ return (
+ queryset.filter(deleted=False, visibility=Notebook.Visibility.INTERNAL)
+ .select_related("created_by", "last_modified_by")
+ .order_by("-last_modified_at")
+ )
+
+ @transaction.atomic
+ def perform_create(self, serializer):
+ account = self._get_account()
+ notebook = serializer.save(
+ team=self.team,
+ created_by=self.request.user,
+ last_modified_by=self.request.user,
+ visibility=Notebook.Visibility.INTERNAL,
+ )
+ ResourceNotebook.objects.create(notebook=notebook, account=account)
+
+ @transaction.atomic
+ def perform_destroy(self, instance: Notebook):
+ instance.delete()
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
index a21499a3ef38..58d36fe03564 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
@@ -46,6 +46,15 @@ export function AccountsTable(): JSX.Element {
<span className="text-muted">—</span>
),
},
+ {
+ title: 'Notebooks',
+ key: 'notebooks',
+ dataIndex: 'notebooks',
+ render: (_, account) => {
+ const count = account.notebooks?.length ?? 0
+ return count > 0 ? <span>{count}</span> : <span className="text-muted">—</span>
+ },
+ },
{
title: 'CSM',
key: 'csm',
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index f440caaa2d30..1229abac559b 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -62,6 +62,8 @@ export interface AccountApi {
properties?: AccountApiProperties
/** Tag names attached to the account. Pass a list to replace existing tags. */
tags?: string[]
+ /** Short IDs of the internal notebooks linked to this account, used to persist investigations, call notes, and other free-form context. Empty list if no notebooks have been created for the account. */
+ readonly notebooks: readonly string[]
readonly created_at: string
/** @nullable */
readonly created_by: number | null
@@ -78,6 +80,92 @@ export interface PaginatedAccountListApi {
results: AccountApi[]
}
+/**
+ * * `engineering` - Engineering
+ * `data` - Data
+ * `product` - Product Management
+ * `founder` - Founder
+ * `leadership` - Leadership
+ * `marketing` - Marketing
+ * `sales` - Sales / Success
+ * `other` - Other
+ */
+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]
+
+export const RoleAtOrganizationEnumApi = {
+ Engineering: 'engineering',
+ Data: 'data',
+ Product: 'product',
+ Founder: 'founder',
+ Leadership: 'leadership',
+ Marketing: 'marketing',
+ Sales: 'sales',
+ Other: 'other',
+} as const
+
+export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]
+
+export const BlankEnumApi = {
+ '': '',
+} as const
+
+/**
+ * @nullable
+ */
+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null
+
+export interface UserBasicApi {
+ readonly id: number
+ readonly uuid: string
+ /**
+ * @maxLength 200
+ * @nullable
+ */
+ distinct_id?: string | null
+ /** @maxLength 150 */
+ first_name?: string
+ /** @maxLength 150 */
+ last_name?: string
+ /** @maxLength 254 */
+ email: string
+ /** @nullable */
+ is_email_verified?: boolean | null
+ /** @nullable */
+ readonly hedgehog_config: UserBasicApiHedgehogConfig
+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
+}
+
+export interface AccountNotebookApi {
+ readonly id: string
+ readonly short_id: string
+ /**
+ * Human-readable title of the account notebook.
+ * @maxLength 256
+ * @nullable
+ */
+ title?: string | null
+ /** Notebook content as a ProseMirror JSON document structure. */
+ content?: unknown
+ /**
+ * Plain text representation of the notebook content for search.
+ * @nullable
+ */
+ text_content?: string | null
+ readonly created_at: string
+ readonly created_by: UserBasicApi
+ readonly last_modified_at: string
+ readonly last_modified_by: UserBasicApi
+}
+
+export interface PaginatedAccountNotebookListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: AccountNotebookApi[]
+}
+
/**
* 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.
* @nullable
@@ -133,6 +221,8 @@ export interface PatchedAccountApi {
properties?: PatchedAccountApiProperties
/** Tag names attached to the account. Pass a list to replace existing tags. */
tags?: string[]
+ /** Short IDs of the internal notebooks linked to this account, used to persist investigations, call notes, and other free-form context. Empty list if no notebooks have been created for the account. */
+ readonly notebooks?: readonly string[]
readonly created_at?: string
/** @nullable */
readonly created_by?: number | null
@@ -379,6 +469,17 @@ export type AccountsListParams = {
tags?: string
}
+export type AccountsNotebooksListParams = {
+ /**
+ * 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.ts
index 9c1bbba88087..6d3407382a47 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -10,7 +10,9 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
AccountApi,
+ AccountNotebookApi,
AccountsListParams,
+ AccountsNotebooksListParams,
CustomerJourneyApi,
CustomerJourneysListParams,
CustomerProfileConfigApi,
@@ -18,6 +20,7 @@ import type {
GroupUsageMetricApi,
GroupsTypesMetricsListParams,
PaginatedAccountListApi,
+ PaginatedAccountNotebookListApi,
PaginatedCustomerJourneyListApi,
PaginatedCustomerProfileConfigListApi,
PaginatedGroupUsageMetricListApi,
@@ -86,6 +89,88 @@ export const accountsCreate = async (
})
}
+export const getAccountsNotebooksListUrl = (
+ projectId: string,
+ accountId: string,
+ params?: AccountsNotebooksListParams
+) => {
+ 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/${accountId}/notebooks/?${stringifiedParams}`
+ : `/api/environments/${projectId}/accounts/${accountId}/notebooks/`
+}
+
+export const accountsNotebooksList = async (
+ projectId: string,
+ accountId: string,
+ params?: AccountsNotebooksListParams,
+ options?: RequestInit
+): Promise<PaginatedAccountNotebookListApi> => {
+ return apiMutator<PaginatedAccountNotebookListApi>(getAccountsNotebooksListUrl(projectId, accountId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAccountsNotebooksCreateUrl = (projectId: string, accountId: string) => {
+ return `/api/environments/${projectId}/accounts/${accountId}/notebooks/`
+}
+
+export const accountsNotebooksCreate = async (
+ projectId: string,
+ accountId: string,
+ accountNotebookApi?: NonReadonly<AccountNotebookApi>,
+ options?: RequestInit
+): Promise<AccountNotebookApi> => {
+ return apiMutator<AccountNotebookApi>(getAccountsNotebooksCreateUrl(projectId, accountId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(accountNotebookApi),
+ })
+}
+
+export const getAccountsNotebooksRetrieveUrl = (projectId: string, accountId: string, shortId: string) => {
+ return `/api/environments/${projectId}/accounts/${accountId}/notebooks/${shortId}/`
+}
+
+export const accountsNotebooksRetrieve = async (
+ projectId: string,
+ accountId: string,
+ shortId: string,
+ options?: RequestInit
+): Promise<AccountNotebookApi> => {
+ return apiMutator<AccountNotebookApi>(getAccountsNotebooksRetrieveUrl(projectId, accountId, shortId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAccountsNotebooksDestroyUrl = (projectId: string, accountId: string, shortId: string) => {
+ return `/api/environments/${projectId}/accounts/${accountId}/notebooks/${shortId}/`
+}
+
+export const accountsNotebooksDestroy = async (
+ projectId: string,
+ accountId: string,
+ shortId: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getAccountsNotebooksDestroyUrl(projectId, accountId, shortId), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getAccountsRetrieveUrl = (projectId: string, id: string) => {
return `/api/environments/${projectId}/accounts/${id}/`
}
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index 6daa98e01c4a..7cd71d6ac61f 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -58,6 +58,18 @@ export const AccountsCreateBody = /* @__PURE__ */ zod
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
+export const accountsNotebooksCreateBodyTitleMax = 256
+
+export const AccountsNotebooksCreateBody = /* @__PURE__ */ zod.object({
+ title: zod
+ .string()
+ .max(accountsNotebooksCreateBodyTitleMax)
+ .nullish()
+ .describe('Human-readable title of the account notebook.'),
+ content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),
+ text_content: zod.string().nullish().describe('Plain text representation of the notebook content for search.'),
+})
+
export const accountsUpdateBodyNameMax = 400
export const accountsUpdateBodyExternalIdMax = 400
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index b458f2b302bb..9ff6a8347e8a 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -73,6 +73,66 @@ tools:
description: >
JSON-encoded array of tag names to filter by, e.g. `["enterprise","priority"]`. Returns accounts
that have any of the listed tags.
+ mcp_version: 1
+ feature_flag: customer-analytics-csp
+ accounts-notebooks-create:
+ operation: accounts_notebooks_create
+ enabled: true
+ scopes:
+ - account:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Create account notebook
+ description: >
+ Create a notebook attached to a Customer Analytics account. Use for persisting investigations, call notes,
+ and other free-form context. Provide `title` and optional `content` (ProseMirror JSON document structure).
+ The notebook is created with internal visibility so it does not appear in the global notebooks list.
+ feature_flag: customer-analytics-csp
+ accounts-notebooks-destroy:
+ operation: accounts_notebooks_destroy
+ enabled: true
+ scopes:
+ - account:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Delete account notebook
+ description: |
+ Permanently delete an account notebook by its `short_id`.
+ feature_flag: customer-analytics-csp
+ accounts-notebooks-list:
+ operation: accounts_notebooks_list
+ enabled: true
+ scopes:
+ - account:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List account notebooks
+ description: >
+ List notebooks attached to a Customer Analytics account, ordered by most recently modified. Each result
+ includes the notebook `short_id`, `title`, `content`, and authorship metadata.
+ mcp_version: 1
+ feature_flag: customer-analytics-csp
+ accounts-notebooks-retrieve:
+ operation: accounts_notebooks_retrieve
+ enabled: true
+ scopes:
+ - account:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get account notebook
+ description: >
+ Fetch a single account notebook by its `short_id`. Returns the full notebook including `content`
+ (ProseMirror JSON document structure) and authorship metadata.
+ mcp_version: 1
feature_flag: customer-analytics-csp
accounts-partial-update:
operation: accounts_partial_update
@@ -113,6 +173,7 @@ tools:
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`.
+ mcp_version: 1
feature_flag: customer-analytics-csp
accounts-update:
operation: accounts_update
diff --git a/products/notebooks/backend/migrations/0004_resourcenotebook_account.py b/products/notebooks/backend/migrations/0004_resourcenotebook_account.py
new file mode 100644
index 000000000000..82bf867af37a
--- /dev/null
+++ b/products/notebooks/backend/migrations/0004_resourcenotebook_account.py
@@ -0,0 +1,96 @@
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0005_account"),
+ ("notebooks", "0003_add_kernel_timeouts"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.RemoveConstraint(
+ model_name="resourcenotebook",
+ name="exactly_one_notebook_related_resource",
+ ),
+ migrations.AlterUniqueTogether(
+ name="resourcenotebook",
+ unique_together=set(),
+ ),
+ migrations.AddField(
+ model_name="resourcenotebook",
+ name="account",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="notebooks",
+ to="customer_analytics.account",
+ ),
+ ),
+ migrations.AlterUniqueTogether(
+ name="resourcenotebook",
+ unique_together={("notebook", "group", "account")},
+ ),
+ migrations.AddConstraint(
+ model_name="resourcenotebook",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("account__isnull", False)),
+ fields=("notebook", "account"),
+ name="unique_notebook_account",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="resourcenotebook",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ models.Q(("group__isnull", False), ("account__isnull", True)),
+ models.Q(("group__isnull", True), ("account__isnull", False)),
+ _connector="OR",
+ ),
+ name="exactly_one_notebook_related_resource",
+ ),
+ ),
+ ],
+ database_operations=[
+ migrations.RunSQL(
+ sql="""
+ ALTER TABLE "posthog_resourcenotebook"
+ ADD COLUMN "account_id" uuid NULL
+ CONSTRAINT "posthog_resourcenotebook_account_id_fk"
+ REFERENCES "customer_analytics_account"("id")
+ DEFERRABLE INITIALLY DEFERRED; -- existing-table-constraint-ignore
+ SET CONSTRAINTS "posthog_resourcenotebook_account_id_fk" IMMEDIATE; -- existing-table-constraint-ignore
+ """,
+ reverse_sql="""
+ ALTER TABLE "posthog_resourcenotebook" DROP COLUMN IF EXISTS "account_id";
+ """,
+ ),
+ migrations.RunSQL(
+ sql="""
+ ALTER TABLE "posthog_resourcenotebook" DROP CONSTRAINT IF EXISTS "exactly_one_notebook_related_resource";
+ ALTER TABLE "posthog_resourcenotebook" ADD CONSTRAINT "exactly_one_notebook_related_resource" CHECK ( /* -- existing-table-constraint-ignore */
+ (
+ (group_id IS NOT NULL AND account_id IS NULL) OR /* -- not-null-ignore */
+ (group_id IS NULL AND account_id IS NOT NULL) /* -- not-null-ignore */
+ )
+ ) NOT VALID;
+ """,
+ reverse_sql="""
+ ALTER TABLE "posthog_resourcenotebook" DROP CONSTRAINT IF EXISTS "exactly_one_notebook_related_resource";
+ ALTER TABLE "posthog_resourcenotebook" ADD CONSTRAINT "exactly_one_notebook_related_resource" CHECK ( /* -- existing-table-constraint-ignore */
+ (group_id IS NOT NULL) /* -- not-null-ignore */
+ ) NOT VALID;
+ """,
+ ),
+ migrations.RunSQL(
+ sql="""
+ ALTER TABLE "posthog_resourcenotebook" DROP CONSTRAINT IF EXISTS "posthog_resourcenotebook_notebook_id_group_id_88c0a30b_uniq";
+ """,
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ ],
+ )
+ ]
diff --git a/products/notebooks/backend/migrations/0005_resourcenotebook_account_indexes.py b/products/notebooks/backend/migrations/0005_resourcenotebook_account_indexes.py
new file mode 100644
index 000000000000..219a4c452e23
--- /dev/null
+++ b/products/notebooks/backend/migrations/0005_resourcenotebook_account_indexes.py
@@ -0,0 +1,48 @@
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("notebooks", "0004_resourcenotebook_account"),
+ ]
+
+ operations = [
+ migrations.RunSQL(
+ sql="""
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "posthog_resourcenotebook_account_id_idx"
+ ON "posthog_resourcenotebook" ("account_id");
+ """,
+ reverse_sql="""
+ DROP INDEX IF EXISTS "posthog_resourcenotebook_account_id_idx";
+ """,
+ ),
+ migrations.RunSQL(
+ sql="""
+ CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "unique_notebook_account"
+ ON "posthog_resourcenotebook" ("notebook_id", "account_id")
+ WHERE "account_id" IS NOT NULL; -- not-null-ignore
+ """,
+ reverse_sql="""
+ DROP INDEX IF EXISTS "unique_notebook_account";
+ """,
+ ),
+ migrations.RunSQL(
+ sql="""
+ CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "posthog_resourcenotebook_notebook_id_group_id_acc_7a017f67_uniq"
+ ON "posthog_resourcenotebook" (
+ "notebook_id",
+ "group_id",
+ "account_id"
+ );
+ """,
+ reverse_sql="""
+ CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "posthog_resourcenotebook_notebook_id_group_id_88c0a30b_uniq"
+ ON "posthog_resourcenotebook" (
+ "notebook_id",
+ "group_id"
+ );
+ """,
+ ),
+ ]
diff --git a/products/notebooks/backend/migrations/0006_resourcenotebook_account_unique_constraint.py b/products/notebooks/backend/migrations/0006_resourcenotebook_account_unique_constraint.py
new file mode 100644
index 000000000000..b2fe518495cb
--- /dev/null
+++ b/products/notebooks/backend/migrations/0006_resourcenotebook_account_unique_constraint.py
@@ -0,0 +1,19 @@
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("notebooks", "0005_resourcenotebook_account_indexes"),
+ ]
+
+ operations = [
+ migrations.RunSQL(
+ sql="""
+ ALTER TABLE "posthog_resourcenotebook" ADD CONSTRAINT "posthog_resourcenotebook_notebook_id_group_id_acc_7a017f67_uniq"
+ UNIQUE USING INDEX "posthog_resourcenotebook_notebook_id_group_id_acc_7a017f67_uniq"; -- existing-table-constraint-ignore
+ """,
+ reverse_sql="""
+ ALTER TABLE "posthog_resourcenotebook" DROP CONSTRAINT IF EXISTS "posthog_resourcenotebook_notebook_id_group_id_acc_7a017f67_uniq";
+ """,
+ ),
+ ]
diff --git a/products/notebooks/backend/migrations/max_migration.txt b/products/notebooks/backend/migrations/max_migration.txt
index 0c9676661e7f..b068a5676249 100644
--- a/products/notebooks/backend/migrations/max_migration.txt
+++ b/products/notebooks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0003_add_kernel_timeouts
+0006_resourcenotebook_account_unique_constraint
diff --git a/products/notebooks/backend/models.py b/products/notebooks/backend/models.py
index 705445d96354..8b4be0093891 100644
--- a/products/notebooks/backend/models.py
+++ b/products/notebooks/backend/models.py
@@ -63,7 +63,7 @@ class Notebook(FileSystemSyncMixin, RootTeamMixin, UUIDTModel):
)
-RELATED_OBJECTS = ("group",)
+RELATED_OBJECTS = ("group", "account")
class ResourceNotebook(UUIDTModel):
@@ -87,6 +87,13 @@ class ResourceNotebook(UUIDTModel):
blank=True,
db_column="group_id",
)
+ account = models.ForeignKey(
+ "customer_analytics.Account",
+ null=True,
+ blank=True,
+ on_delete=models.CASCADE,
+ related_name="notebooks",
+ )
class Meta:
unique_together = ("notebook", *RELATED_OBJECTS)
diff --git a/products/notebooks/mcp/tools.yaml b/products/notebooks/mcp/tools.yaml
index ae9359d04e74..2f6bcdb7bd16 100644
--- a/products/notebooks/mcp/tools.yaml
+++ b/products/notebooks/mcp/tools.yaml
@@ -9,6 +9,18 @@ feature: notebooks
url_prefix: /notebooks
ui_apps: {}
tools:
+ accounts-notebooks-create:
+ operation: accounts_notebooks_create
+ enabled: false
+ accounts-notebooks-destroy:
+ operation: accounts_notebooks_destroy
+ enabled: false
+ accounts-notebooks-list:
+ operation: accounts_notebooks_list
+ enabled: false
+ accounts-notebooks-retrieve:
+ operation: accounts_notebooks_retrieve
+ enabled: false
notebooks-activity-retrieve:
operation: notebooks_activity_retrieve
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index fb3fed168b92..4fb4ba69578f 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -38,7 +38,71 @@
"summary": "List accounts",
"title": "List accounts",
"required_scopes": ["account:read"],
+ "new_mcp": false,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "customer-analytics-csp"
+ },
+ "accounts-notebooks-create": {
+ "description": "Create a notebook attached to a Customer Analytics account. Use for persisting investigations, call notes, and other free-form context. Provide `title` and optional `content` (ProseMirror JSON document structure). The notebook is created with internal visibility so it does not appear in the global notebooks list.",
+ "category": "Customer analytics",
+ "feature": "customer_analytics",
+ "summary": "Create account notebook",
+ "title": "Create account notebook",
+ "required_scopes": ["account:write"],
"new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "customer-analytics-csp"
+ },
+ "accounts-notebooks-destroy": {
+ "description": "Permanently delete an account notebook by its `short_id`.",
+ "category": "Customer analytics",
+ "feature": "customer_analytics",
+ "summary": "Delete account notebook",
+ "title": "Delete account notebook",
+ "required_scopes": ["account:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "customer-analytics-csp"
+ },
+ "accounts-notebooks-list": {
+ "description": "List notebooks attached to a Customer Analytics account, ordered by most recently modified. Each result includes the notebook `short_id`, `title`, `content`, and authorship metadata.",
+ "category": "Customer analytics",
+ "feature": "customer_analytics",
+ "summary": "List account notebooks",
+ "title": "List account notebooks",
+ "required_scopes": ["account:read"],
+ "new_mcp": false,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "customer-analytics-csp"
+ },
+ "accounts-notebooks-retrieve": {
+ "description": "Fetch a single account notebook by its `short_id`. Returns the full notebook including `content` (ProseMirror JSON document structure) and authorship metadata.",
+ "category": "Customer analytics",
+ "feature": "customer_analytics",
+ "summary": "Get account notebook",
+ "title": "Get account notebook",
+ "required_scopes": ["account:read"],
+ "new_mcp": false,
"annotations": {
"destructiveHint": false,
"idempotentHint": true,
@@ -70,7 +134,7 @@
"summary": "Get account",
"title": "Get account",
"required_scopes": ["account:read"],
- "new_mcp": true,
+ "new_mcp": false,
"annotations": {
"destructiveHint": false,
"idempotentHint": true,
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 9b3d57d4a983..4f2768cc72ad 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -38,7 +38,71 @@
"summary": "List accounts",
"title": "List accounts",
"required_scopes": ["account:read"],
+ "new_mcp": false,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "customer-analytics-csp"
+ },
+ "accounts-notebooks-create": {
+ "description": "Create a notebook attached to a Customer Analytics account. Use for persisting investigations, call notes, and other free-form context. Provide `title` and optional `content` (ProseMirror JSON document structure). The notebook is created with internal visibility so it does not appear in the global notebooks list.",
+ "category": "Customer analytics",
+ "feature": "customer_analytics",
+ "summary": "Create account notebook",
+ "title": "Create account notebook",
+ "required_scopes": ["account:write"],
"new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "customer-analytics-csp"
+ },
+ "accounts-notebooks-destroy": {
+ "description": "Permanently delete an account notebook by its `short_id`.",
+ "category": "Customer analytics",
+ "feature": "customer_analytics",
+ "summary": "Delete account notebook",
+ "title": "Delete account notebook",
+ "required_scopes": ["account:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "customer-analytics-csp"
+ },
+ "accounts-notebooks-list": {
+ "description": "List notebooks attached to a Customer Analytics account, ordered by most recently modified. Each result includes the notebook `short_id`, `title`, `content`, and authorship metadata.",
+ "category": "Customer analytics",
+ "feature": "customer_analytics",
+ "summary": "List account notebooks",
+ "title": "List account notebooks",
+ "required_scopes": ["account:read"],
+ "new_mcp": false,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "customer-analytics-csp"
+ },
+ "accounts-notebooks-retrieve": {
+ "description": "Fetch a single account notebook by its `short_id`. Returns the full notebook including `content` (ProseMirror JSON document structure) and authorship metadata.",
+ "category": "Customer analytics",
+ "feature": "customer_analytics",
+ "summary": "Get account notebook",
+ "title": "Get account notebook",
+ "required_scopes": ["account:read"],
+ "new_mcp": false,
"annotations": {
"destructiveHint": false,
"idempotentHint": true,
@@ -70,7 +134,7 @@
"summary": "Get account",
"title": "Get account",
"required_scopes": ["account:read"],
- "new_mcp": true,
+ "new_mcp": false,
"annotations": {
"destructiveHint": false,
"idempotentHint": true,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5e0c95c4376f..b8b58d2f4ec0 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -112,6 +112,8 @@ export namespace Schemas {
properties?: AccountProperties;
/** Tag names attached to the account. Pass a list to replace existing tags. */
tags?: string[];
+ /** Short IDs of the internal notebooks linked to this account, used to persist investigations, call notes, and other free-form context. Empty list if no notebooks have been created for the account. */
+ readonly notebooks: readonly string[];
readonly created_at: string;
/** @nullable */
readonly created_by: number | null;
@@ -119,6 +121,85 @@ export namespace Schemas {
readonly updated_at: string | null;
}
+ /**
+ * * `engineering` - Engineering
+ * `data` - Data
+ * `product` - Product Management
+ * `founder` - Founder
+ * `leadership` - Leadership
+ * `marketing` - Marketing
+ * `sales` - Sales / Success
+ * `other` - Other
+ */
+ export type RoleAtOrganizationEnum = typeof RoleAtOrganizationEnum[keyof typeof RoleAtOrganizationEnum];
+
+
+ export const RoleAtOrganizationEnum = {
+ Engineering: 'engineering',
+ Data: 'data',
+ Product: 'product',
+ Founder: 'founder',
+ Leadership: 'leadership',
+ Marketing: 'marketing',
+ Sales: 'sales',
+ Other: 'other',
+ } as const;
+
+ export type BlankEnum = typeof BlankEnum[keyof typeof BlankEnum];
+
+
+ export const BlankEnum = {
+ '': '',
+ } as const;
+
+ /**
+ * @nullable
+ */
+ export type UserBasicHedgehogConfig = { [key: string]: unknown } | null;
+
+ export interface UserBasic {
+ readonly id: number;
+ readonly uuid: string;
+ /**
+ * @maxLength 200
+ * @nullable
+ */
+ distinct_id?: string | null;
+ /** @maxLength 150 */
+ first_name?: string;
+ /** @maxLength 150 */
+ last_name?: string;
+ /** @maxLength 254 */
+ email: string;
+ /** @nullable */
+ is_email_verified?: boolean | null;
+ /** @nullable */
+ readonly hedgehog_config: UserBasicHedgehogConfig;
+ role_at_organization?: RoleAtOrganizationEnum | BlankEnum | null;
+ }
+
+ export interface AccountNotebook {
+ readonly id: string;
+ readonly short_id: string;
+ /**
+ * Human-readable title of the account notebook.
+ * @maxLength 256
+ * @nullable
+ */
+ title?: string | null;
+ /** Notebook content as a ProseMirror JSON document structure. */
+ content?: unknown;
+ /**
+ * Plain text representation of the notebook content for search.
+ * @nullable
+ */
+ text_content?: string | null;
+ readonly created_at: string;
+ readonly created_by: UserBasic;
+ readonly last_modified_at: string;
+ readonly last_modified_by: UserBasic;
+ }
+
/**
* * `event` - event
* `event_metadata` - event_metadata
@@ -571,63 +652,6 @@ export namespace Schemas {
url_matching?: ActionStepMatchingEnum | null;
}
- /**
- * * `engineering` - Engineering
- * `data` - Data
- * `product` - Product Management
- * `founder` - Founder
- * `leadership` - Leadership
- * `marketing` - Marketing
- * `sales` - Sales / Success
- * `other` - Other
- */
- export type RoleAtOrganizationEnum = typeof RoleAtOrganizationEnum[keyof typeof RoleAtOrganizationEnum];
-
-
- export const RoleAtOrganizationEnum = {
- Engineering: 'engineering',
- Data: 'data',
- Product: 'product',
- Founder: 'founder',
- Leadership: 'leadership',
- Marketing: 'marketing',
- Sales: 'sales',
- Other: 'other',
- } as const;
-
- export type BlankEnum = typeof BlankEnum[keyof typeof BlankEnum];
-
-
- export const BlankEnum = {
- '': '',
- } as const;
-
- /**
- * @nullable
- */
- export type UserBasicHedgehogConfig = { [key: string]: unknown } | null;
-
- export interface UserBasic {
- readonly id: number;
- readonly uuid: string;
- /**
- * @maxLength 200
- * @nullable
- */
- distinct_id?: string | null;
- /** @maxLength 150 */
- first_name?: string;
- /** @maxLength 150 */
- last_name?: string;
- /** @maxLength 254 */
- email: string;
- /** @nullable */
- is_email_verified?: boolean | null;
- /** @nullable */
- readonly hedgehog_config: UserBasicHedgehogConfig;
- role_at_organization?: RoleAtOrganizationEnum | BlankEnum | null;
- }
-
/**
* Serializer mixin that handles tags for objects.
*/
@@ -22060,6 +22084,15 @@ export namespace Schemas {
results: Account[];
}
+ export interface PaginatedAccountNotebookList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: AccountNotebook[];
+ }
+
export interface PaginatedActionList {
count: number;
/** @nullable */
@@ -25988,6 +26021,8 @@ export namespace Schemas {
properties?: PatchedAccountProperties;
/** Tag names attached to the account. Pass a list to replace existing tags. */
tags?: string[];
+ /** Short IDs of the internal notebooks linked to this account, used to persist investigations, call notes, and other free-form context. Empty list if no notebooks have been created for the account. */
+ readonly notebooks?: readonly string[];
readonly created_at?: string;
/** @nullable */
readonly created_by?: number | null;
@@ -40416,6 +40451,17 @@ export namespace Schemas {
tags?: string;
};
+ export type AccountsNotebooksListParams = {
+ /**
+ * 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/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.ts
index 6a44079d9292..2816dd3a8327 100644
--- a/services/mcp/src/generated/customer_analytics/api.ts
+++ b/services/mcp/src/generated/customer_analytics/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 10 enabled ops
+ * PostHog API - MCP 14 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -99,6 +99,61 @@ export const AccountsCreateBody = /* @__PURE__ */ zod
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
+export const AccountsNotebooksListParams = /* @__PURE__ */ zod.object({
+ account_id: zod.string().describe('UUID of the parent account.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const AccountsNotebooksListQueryParams = /* @__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.'),
+})
+
+export const AccountsNotebooksCreateParams = /* @__PURE__ */ zod.object({
+ account_id: zod.string().describe('UUID of the parent account.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const accountsNotebooksCreateBodyTitleMax = 256
+
+export const AccountsNotebooksCreateBody = /* @__PURE__ */ zod.object({
+ title: zod
+ .string()
+ .max(accountsNotebooksCreateBodyTitleMax)
+ .nullish()
+ .describe('Human-readable title of the account notebook.'),
+ content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),
+ text_content: zod.string().nullish().describe('Plain text representation of the notebook content for search.'),
+})
+
+export const AccountsNotebooksRetrieveParams = /* @__PURE__ */ zod.object({
+ account_id: zod.string().describe('UUID of the parent account.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+ short_id: zod.string(),
+})
+
+export const AccountsNotebooksDestroyParams = /* @__PURE__ */ zod.object({
+ account_id: zod.string().describe('UUID of the parent account.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+ short_id: zod.string(),
+})
+
export const AccountsRetrieveParams = /* @__PURE__ */ zod.object({
id: zod.string().describe('A UUID string identifying this account.'),
project_id: zod
diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.ts
index 913eee81f113..ed7731816462 100644
--- a/services/mcp/src/tools/generated/customer_analytics.ts
+++ b/services/mcp/src/tools/generated/customer_analytics.ts
@@ -6,6 +6,12 @@ import {
AccountsCreateBody,
AccountsDestroyParams,
AccountsListQueryParams,
+ AccountsNotebooksCreateBody,
+ AccountsNotebooksCreateParams,
+ AccountsNotebooksDestroyParams,
+ AccountsNotebooksListParams,
+ AccountsNotebooksListQueryParams,
+ AccountsNotebooksRetrieveParams,
AccountsPartialUpdateBody,
AccountsPartialUpdateParams,
AccountsRetrieveParams,
@@ -82,6 +88,7 @@ const AccountsListSchema = AccountsListQueryParams.extend({
const accountsList = (): ToolBase<typeof AccountsListSchema, WithPostHogUrl<Schemas.PaginatedAccountList>> => ({
name: 'accounts-list',
schema: AccountsListSchema,
+ mcpVersion: 1,
handler: async (context: Context, params: z.infer<typeof AccountsListSchema>) => {
const projectId = await context.stateManager.getProjectId()
const result = await context.api.request<Schemas.PaginatedAccountList>({
@@ -103,6 +110,90 @@ const accountsList = (): ToolBase<typeof AccountsListSchema, WithPostHogUrl<Sche
},
})
+const AccountsNotebooksCreateSchema = AccountsNotebooksCreateParams.omit({ project_id: true }).extend(
+ AccountsNotebooksCreateBody.shape
+)
+
+const accountsNotebooksCreate = (): ToolBase<typeof AccountsNotebooksCreateSchema, Schemas.AccountNotebook> => ({
+ name: 'accounts-notebooks-create',
+ schema: AccountsNotebooksCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof AccountsNotebooksCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.title !== undefined) {
+ body['title'] = params.title
+ }
+ if (params.content !== undefined) {
+ body['content'] = params.content
+ }
+ if (params.text_content !== undefined) {
+ body['text_content'] = params.text_content
+ }
+ const result = await context.api.request<Schemas.AccountNotebook>({
+ method: 'POST',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/accounts/${encodeURIComponent(String(params.account_id))}/notebooks/`,
+ body,
+ })
+ return result
+ },
+})
+
+const AccountsNotebooksDestroySchema = AccountsNotebooksDestroyParams.omit({ project_id: true })
+
+const accountsNotebooksDestroy = (): ToolBase<typeof AccountsNotebooksDestroySchema, unknown> => ({
+ name: 'accounts-notebooks-destroy',
+ schema: AccountsNotebooksDestroySchema,
+ handler: async (context: Context, params: z.infer<typeof AccountsNotebooksDestroySchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'DELETE',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/accounts/${encodeURIComponent(String(params.account_id))}/notebooks/${encodeURIComponent(String(params.short_id))}/`,
+ })
+ return result
+ },
+})
+
+const AccountsNotebooksListSchema = AccountsNotebooksListParams.omit({ project_id: true }).extend(
+ AccountsNotebooksListQueryParams.shape
+)
+
+const accountsNotebooksList = (): ToolBase<
+ typeof AccountsNotebooksListSchema,
+ WithPostHogUrl<Schemas.PaginatedAccountNotebookList>
+> => ({
+ name: 'accounts-notebooks-list',
+ schema: AccountsNotebooksListSchema,
+ mcpVersion: 1,
+ handler: async (context: Context, params: z.infer<typeof AccountsNotebooksListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedAccountNotebookList>({
+ method: 'GET',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/accounts/${encodeURIComponent(String(params.account_id))}/notebooks/`,
+ query: {
+ limit: params.limit,
+ offset: params.offset,
+ },
+ })
+ return await withPostHogUrl(context, result, '/customer-analytics')
+ },
+})
+
+const AccountsNotebooksRetrieveSchema = AccountsNotebooksRetrieveParams.omit({ project_id: true })
+
+const accountsNotebooksRetrieve = (): ToolBase<typeof AccountsNotebooksRetrieveSchema, Schemas.AccountNotebook> => ({
+ name: 'accounts-notebooks-retrieve',
+ schema: AccountsNotebooksRetrieveSchema,
+ mcpVersion: 1,
+ handler: async (context: Context, params: z.infer<typeof AccountsNotebooksRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AccountNotebook>({
+ method: 'GET',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/accounts/${encodeURIComponent(String(params.account_id))}/notebooks/${encodeURIComponent(String(params.short_id))}/`,
+ })
+ return result
+ },
+})
+
const AccountsPartialUpdateSchema = AccountsPartialUpdateParams.omit({ project_id: true })
.extend(AccountsPartialUpdateBody.shape)
.extend({
@@ -146,6 +237,7 @@ const AccountsRetrieveSchema = AccountsRetrieveParams.omit({ project_id: true })
const accountsRetrieve = (): ToolBase<typeof AccountsRetrieveSchema, Schemas.Account> => ({
name: 'accounts-retrieve',
schema: AccountsRetrieveSchema,
+ mcpVersion: 1,
handler: async (context: Context, params: z.infer<typeof AccountsRetrieveSchema>) => {
const projectId = await context.stateManager.getProjectId()
const result = await context.api.request<Schemas.Account>({
@@ -324,6 +416,10 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'accounts-create': accountsCreate,
'accounts-destroy': accountsDestroy,
'accounts-list': accountsList,
+ 'accounts-notebooks-create': accountsNotebooksCreate,
+ 'accounts-notebooks-destroy': accountsNotebooksDestroy,
+ 'accounts-notebooks-list': accountsNotebooksList,
+ 'accounts-notebooks-retrieve': accountsNotebooksRetrieve,
'accounts-partial-update': accountsPartialUpdate,
'accounts-retrieve': accountsRetrieve,
'usage-metrics-create': usageMetricsCreate,
diff --git a/tach.toml b/tach.toml
index 76da02121894..015ad476e9b3 100644
--- a/tach.toml
+++ b/tach.toml
@@ -163,6 +163,7 @@ depends_on = [
"ee",
"posthog",
"products.data_warehouse",
+ "products.notebooks",
]
layer = "modules"