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(notebooks): store every new notebook as a markdown notebook (#100471)

Sinan Kucukkoselerb21e22e821d3
diff --git a/posthog/api/test/notebooks/test_notebook.py b/posthog/api/test/notebooks/test_notebook.py
index 8946d055eec1..60f91e26d8e7 100644
--- a/posthog/api/test/notebooks/test_notebook.py
+++ b/posthog/api/test/notebooks/test_notebook.py
@@ -8,6 +8,7 @@ from rest_framework import status
from posthog.models import Organization, Team
from posthog.models.user import User
+from products.notebooks.backend.facade.content import build_markdown_notebook_content
from products.notebooks.backend.models import Notebook
@@ -75,28 +76,28 @@ class TestNotebooks(APIBaseTest, QueryMatchingTest):
@parameterized.expand(
[
- ("without_content", None, None),
+ ("without_content", None, None, ""),
(
- "with_content",
- {"some": "kind", "of": "tip", "tap": "content"},
- "some kind of tip tap content",
- ),
- (
- "with_markdown_content",
+ "with_rich_text_content",
{
"type": "doc",
"content": [
- {
- "type": "ph-markdown-notebook",
- "attrs": {"nodeId": "markdown-notebook-v2", "markdown": "# Test\n\nBody"},
- }
+ {"type": "heading", "attrs": {"level": 1}, "content": [{"type": "text", "text": "Test"}]},
+ {"type": "paragraph", "content": [{"type": "text", "text": "Body"}]},
],
},
+ "Test Body",
+ "# Test\n\nBody",
+ ),
+ (
+ "with_markdown_content_and_stale_text",
+ build_markdown_notebook_content("# Test\n\nBody"),
+ "stale search text",
"# Test\n\nBody",
),
]
)
- def test_create_a_notebook(self, _, content: dict | None, text_content: str | None) -> None:
+ def test_create_a_notebook(self, _, content: dict | None, text_content: str | None, expected_markdown: str) -> None:
response = self.client.post(
f"/api/projects/{self.team.id}/notebooks",
data={"content": content, "text_content": text_content},
@@ -106,8 +107,8 @@ class TestNotebooks(APIBaseTest, QueryMatchingTest):
assert response_json == {
"id": response_json["id"],
"short_id": response_json["short_id"],
- "content": content,
- "text_content": text_content,
+ "content": build_markdown_notebook_content(expected_markdown),
+ "text_content": expected_markdown,
"title": None,
"version": 0,
"created_at": response_json["created_at"],
@@ -129,26 +130,14 @@ class TestNotebooks(APIBaseTest, QueryMatchingTest):
@parameterized.expand(
[
("legacy_rich_text", {"some": "kind", "of": "tip", "tap": "content"}, None),
- (
- "markdown_notebook",
- {
- "type": "doc",
- "content": [
- {
- "type": "ph-markdown-notebook",
- "attrs": {"nodeId": "markdown-notebook-v2", "markdown": "# Test\n\nBody"},
- }
- ],
- },
- "# Test\n\nBody",
- ),
+ ("markdown_notebook", build_markdown_notebook_content("# Test\n\nBody"), "# Test\n\nBody"),
]
)
def test_gets_notebook_markdown_by_shortid(self, _, content: dict, expected_markdown: str | None) -> None:
- create_response = self.client.post(f"/api/projects/{self.team.id}/notebooks", data={"content": content})
- short_id = create_response.json()["short_id"]
+ # Seeded through the ORM, because the create endpoint converts rich text and the legacy case needs a legacy notebook.
+ notebook = Notebook.objects.create(team=self.team, content=content, created_by=self.user)
- response = self.client.get(f"/api/projects/{self.team.id}/notebooks/{short_id}/markdown")
+ response = self.client.get(f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/markdown")
assert response.status_code == status.HTTP_200_OK
assert response.json() == {"markdown": expected_markdown}
@@ -197,9 +186,9 @@ class TestNotebooks(APIBaseTest, QueryMatchingTest):
"type": "Notebook",
},
{
- "action": "created",
+ "action": "changed",
"after": {"some": "updated content"},
- "before": None,
+ "before": build_markdown_notebook_content(""),
"field": "content",
"type": "Notebook",
},
@@ -266,29 +255,56 @@ class TestNotebooks(APIBaseTest, QueryMatchingTest):
data={"content": bad_content},
)
assert response.status_code == status.HTTP_201_CREATED
- stored_query = response.json()["content"]["content"][0]["attrs"]["query"]
- assert stored_query == {
- "kind": "DataVisualizationNode",
- "source": {"kind": "HogQLQuery", "query": "SELECT 1"},
- "display": "ActionsBar",
- }
+ stored_markdown = response.json()["content"]["content"][0]["attrs"]["markdown"]
+ assert "InsightVizNode" not in stored_markdown
+ assert (
+ '{"kind":"DataVisualizationNode","source":{"kind":"HogQLQuery","query":"SELECT 1"},"display":"ActionsBar"}'
+ in stored_markdown
+ )
- def test_create_notebook_rejects_insight_viz_wrapping_unknown_kind(self) -> None:
- bad_content = {
- "type": "doc",
- "content": [
+ @parameterized.expand(
+ [
+ (
+ "insight_viz_wrapping_unknown_kind",
{
- "type": "ph-query",
- "attrs": {
- "nodeId": "n1",
- "query": {
- "kind": "InsightVizNode",
- "source": {"kind": "DefinitelyNotAQuery"},
+ "type": "doc",
+ "content": [
+ {
+ "type": "ph-query",
+ "attrs": {
+ "nodeId": "n1",
+ "query": {"kind": "InsightVizNode", "source": {"kind": "DefinitelyNotAQuery"}},
+ },
},
- },
+ ],
},
- ],
- }
+ "DefinitelyNotAQuery",
+ ),
+ (
+ "rich_text_that_cannot_convert",
+ {
+ "type": "doc",
+ "content": [{"type": "paragraph", "content": [{"type": "text", "text": "x", "marks": 1}]}],
+ },
+ "cannot be stored as a markdown notebook",
+ ),
+ (
+ "rich_text_over_the_cell_limit",
+ {
+ "type": "doc",
+ "content": [
+ {
+ "type": "ph-query",
+ "attrs": {"nodeId": f"q{i}", "query": {"kind": "SavedInsightNode", "shortId": "abc"}},
+ }
+ for i in range(51)
+ ],
+ },
+ "limit of 50 cells",
+ ),
+ ]
+ )
+ def test_create_notebook_rejects_invalid_content(self, _, bad_content: dict, expected_detail: str) -> None:
response = self.client.post(
f"/api/projects/{self.team.id}/notebooks",
data={"content": bad_content},
@@ -296,7 +312,8 @@ class TestNotebooks(APIBaseTest, QueryMatchingTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
body = response.json()
assert body["attr"] == "content"
- assert "DefinitelyNotAQuery" in body["detail"]
+ assert expected_detail in body["detail"]
+ assert not Notebook.objects.filter(team=self.team).exists()
def test_update_notebook_normalizes_invalid_query_node(self) -> None:
create = self.client.post(f"/api/projects/{self.team.id}/notebooks", data={})
diff --git a/posthog/api/test/notebooks/test_notebook_filtering.py b/posthog/api/test/notebooks/test_notebook_filtering.py
index f23bbf9a52fe..059b69af46cd 100644
--- a/posthog/api/test/notebooks/test_notebook_filtering.py
+++ b/posthog/api/test/notebooks/test_notebook_filtering.py
@@ -62,18 +62,16 @@ BASIC_TEXT = lambda text: {
class TestNotebooksFiltering(APIBaseTest, QueryMatchingTest):
def _create_notebook_with_content(self, inner_content: list[dict[str, Any]], title: str = "the title") -> str:
- response = self.client.post(
- f"/api/projects/{self.team.id}/notebooks",
- data={
- "title": title,
- "content": {
- "type": "doc",
- "content": inner_content,
- },
- },
- )
- assert response.status_code == status.HTTP_201_CREATED
- return response.json()["id"]
+ # Seeded through the ORM because the create endpoint stores every notebook as markdown, and the contains
+ # filter under test matches rich-text nodes only.
+ notebook = Notebook.objects.create(
+ team=self.team,
+ title=title,
+ content={"type": "doc", "content": inner_content},
+ created_by=self.user,
+ last_modified_by=self.user,
+ )
+ return str(notebook.id)
@parameterized.expand(
[
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 94c34dbffa39..646d38f48f86 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -1052,7 +1052,7 @@ class AccountNotebookSerializer(DataclassSerializer):
content = serializers.JSONField(
required=False,
allow_null=True,
- help_text="Notebook content as a ProseMirror JSON document structure.",
+ help_text="Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook.",
)
text_content = serializers.CharField(
required=False,
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index fd40b1176963..180c8b44610a 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -117,6 +117,7 @@ from products.customer_analytics.backend.presentation.views.serializers import (
UserCustomerAnalyticsConfigUpdateSerializer,
)
from products.notebooks.backend.facade.content import build_markdown_notebook_content
+from products.notebooks.backend.facade.contracts import NotebookCellLimitExceeded, NotebookContentNotConvertible
# Object-level access levels for the resource ViewSets, matching what
# ``AccessControlPermission._get_required_access_level`` derives for these scope objects:
@@ -2119,19 +2120,22 @@ class AccountNotebookViewSet(
serializer = AccountNotebookSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
data = serializer.validated_data
- notebook = api.create_account_notebook(
- team_id=self.team_id,
- team=self.team,
- account_id=self.parents_query_dict["account_id"],
- input=contracts.CreateAccountNotebookInput(
- title=data.title,
- content=data.content,
- text_content=data.text_content,
- synthesized_content=_synthesize_notebook_content(data.text_content, data.content),
- ),
- user=cast(User, request.user),
- user_access_control=self.user_access_control,
- )
+ try:
+ notebook = api.create_account_notebook(
+ team_id=self.team_id,
+ team=self.team,
+ account_id=self.parents_query_dict["account_id"],
+ input=contracts.CreateAccountNotebookInput(
+ title=data.title,
+ content=data.content,
+ text_content=data.text_content,
+ synthesized_content=_synthesize_notebook_content(data.text_content, data.content),
+ ),
+ user=cast(User, request.user),
+ user_access_control=self.user_access_control,
+ )
+ except (NotebookContentNotConvertible, NotebookCellLimitExceeded) as err:
+ raise ValidationError({"content": str(err)})
if notebook is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
return Response(AccountNotebookSerializer(instance=notebook).data, status=status.HTTP_201_CREATED)
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index b110c2903b58..1ae577e0938e 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -1299,41 +1299,72 @@ class TestAccountNotebookViewSet(APIBaseTest):
self.assertEqual(notebook.text_content, "# Heading\n\nSome **bold** text.")
self.assertEqual(notebook.content, build_markdown_notebook_content("# Heading\n\nSome **bold** text."))
- def test_create_preserves_caller_supplied_content(self):
- explicit_content = {
- "type": "doc",
- "content": [{"type": "paragraph", "content": [{"type": "text", "text": "from caller"}]}],
- }
- response = self.client.post(
- self.endpoint_base,
- {"title": "Provided", "content": explicit_content, "text_content": "# ignored"},
- format="json",
- )
-
- self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())
- # nosemgrep: idor-lookup-without-team (test assertion)
- notebook = Notebook.objects.get(short_id=response.json()["short_id"])
- self.assertEqual(notebook.content, explicit_content)
-
- def test_create_with_neither_field_leaves_content_null(self):
- response = self.client.post(self.endpoint_base, {"title": "Empty"}, format="json")
+ @parameterized.expand(
+ [
+ (
+ "rich_text_content",
+ {
+ "title": "Provided",
+ "content": {
+ "type": "doc",
+ "content": [{"type": "paragraph", "content": [{"type": "text", "text": "from caller"}]}],
+ },
+ "text_content": "# ignored",
+ },
+ "from caller",
+ ),
+ ("empty_rich_text_doc", {"title": "Empty doc", "content": {"type": "doc", "content": []}}, ""),
+ ("neither_field", {"title": "Empty"}, ""),
+ ("empty_text_content", {"title": "Empty body", "text_content": ""}, ""),
+ (
+ "markdown_content_with_stale_text",
+ {
+ "title": "Markdown",
+ "content": build_markdown_notebook_content("# Current"),
+ "text_content": "stale search text",
+ },
+ "# Current",
+ ),
+ ]
+ )
+ def test_create_stores_a_markdown_notebook(self, _name: str, payload: dict, expected_markdown: str) -> None:
+ response = self.client.post(self.endpoint_base, payload, format="json")
self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())
# nosemgrep: idor-lookup-without-team (test assertion)
notebook = Notebook.objects.get(short_id=response.json()["short_id"])
- self.assertIsNone(notebook.content)
+ self.assertEqual(notebook.content, build_markdown_notebook_content(expected_markdown))
+ self.assertEqual(notebook.text_content, expected_markdown)
- def test_create_with_empty_text_content_does_not_synthesize_content(self):
- response = self.client.post(
- self.endpoint_base,
- {"title": "Empty body", "text_content": ""},
- format="json",
- )
+ @parameterized.expand(
+ [
+ (
+ "rich_text_that_cannot_convert",
+ {
+ "type": "doc",
+ "content": [{"type": "paragraph", "content": [{"type": "text", "text": "x", "marks": 1}]}],
+ },
+ ),
+ (
+ "rich_text_over_the_cell_limit",
+ {
+ "type": "doc",
+ "content": [
+ {
+ "type": "ph-query",
+ "attrs": {"nodeId": f"q{i}", "query": {"kind": "SavedInsightNode", "shortId": "abc"}},
+ }
+ for i in range(51)
+ ],
+ },
+ ),
+ ]
+ )
+ def test_create_rejects_invalid_content(self, _name: str, content: dict) -> None:
+ response = self.client.post(self.endpoint_base, {"title": "Invalid", "content": content}, format="json")
- self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())
- # nosemgrep: idor-lookup-without-team (test assertion)
- notebook = Notebook.objects.get(short_id=response.json()["short_id"])
- self.assertIsNone(notebook.content)
+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code, response.json())
+ self.assertEqual(response.json()["attr"], "content")
def test_create_with_empty_dict_content_falls_back_to_markdown(self):
response = self.client.post(
@@ -1347,19 +1378,6 @@ class TestAccountNotebookViewSet(APIBaseTest):
notebook = Notebook.objects.get(short_id=response.json()["short_id"])
self.assertEqual(notebook.content, build_markdown_notebook_content("Just a sentence."))
- def test_create_with_empty_valid_prosemirror_doc_respects_caller(self):
- empty_doc = {"type": "doc", "content": []}
- response = self.client.post(
- self.endpoint_base,
- {"title": "Empty doc", "content": empty_doc, "text_content": "ignored"},
- format="json",
- )
-
- self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())
- # nosemgrep: idor-lookup-without-team (test assertion)
- notebook = Notebook.objects.get(short_id=response.json()["short_id"])
- self.assertEqual(notebook.content, empty_doc)
-
def test_notebook_detail_includes_parent_resource_for_linked_account(self):
notebook = Notebook.objects.create(
team=self.team, title="Account note", content={}, visibility=Notebook.Visibility.INTERNAL
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index abd6967e38de..18970fdd47c1 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -535,7 +535,7 @@ export interface AccountNotebookApi {
* @nullable
*/
title?: string | null
- /** Notebook content as a ProseMirror JSON document structure. */
+ /** Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook. */
content?: unknown
/**
* Plain text representation of the notebook content for search.
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index 96ce6a6bb2fa..d6eb38c84612 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -264,7 +264,12 @@ export const AccountsNotebooksCreateBody = /* @__PURE__ */ zod.object({
.max(accountsNotebooksCreateBodyTitleMax)
.nullish()
.describe('Human-readable title of the account notebook.'),
- content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),
+ content: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook.'
+ ),
text_content: zod.string().nullish().describe('Plain text representation of the notebook content for search.'),
})
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index 0664117deffa..97ca2a7bf18d 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -273,9 +273,9 @@ tools:
and other free-form context. Provide `title` and the note body as Markdown via `text_content` — the server
converts it into a formatted notebook (headings `#` through `######`, bullet lists `-`, ordered lists `1.`,
fenced code blocks, `**bold**`, `*italic*`, `` `code` ``, and `[label](url)` links). Pass `content`
- (ProseMirror JSON) only if you already have a structured document; in most cases leave it unset and write
- Markdown in `text_content`. The notebook is created with internal visibility so it does not appear in the
- global notebooks list.
+ (ProseMirror JSON) only if you already have a structured document; the server converts it into the same
+ markdown notebook format. In most cases leave it unset and write Markdown in `text_content`. 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
diff --git a/products/notebooks/backend/facade/api.py b/products/notebooks/backend/facade/api.py
index 4fc18913fb42..ad2fb7feafb8 100644
--- a/products/notebooks/backend/facade/api.py
+++ b/products/notebooks/backend/facade/api.py
@@ -224,6 +224,10 @@ def migrate_notebooks_to_markdown(
)
+def to_markdown_notebook_content(content: Any, *, organization_id: UUID) -> dict[str, Any] | None:
+ return markdown_migration.to_markdown_notebook_content(content, organization_id=organization_id)
+
+
# --- Resource links (groups, accounts) ---
diff --git a/products/notebooks/backend/facade/contracts.py b/products/notebooks/backend/facade/contracts.py
index 3c021ca2fb8e..4407bd39f05b 100644
--- a/products/notebooks/backend/facade/contracts.py
+++ b/products/notebooks/backend/facade/contracts.py
@@ -45,6 +45,14 @@ class NotebookCellLimitExceeded(Exception):
"""
+class NotebookContentNotConvertible(Exception):
+ """Raised when a create sends rich-text content that the markdown converter cannot read.
+
+ Lives here because it crosses the product boundary: account notebooks are created through
+ the facade, and that API has to turn this into a 400 on `content` instead of a 500.
+ """
+
+
@dataclass(frozen=True)
class NotebookData:
"""A notebook's persisted state, as other products read it."""
diff --git a/products/notebooks/backend/logic.py b/products/notebooks/backend/logic.py
index 6efa0fb1fb9b..b60d473e69f0 100644
--- a/products/notebooks/backend/logic.py
+++ b/products/notebooks/backend/logic.py
@@ -16,8 +16,12 @@ from django.utils import timezone
from asgiref.sync import sync_to_async
+from posthog.models import Team
+
from products.access_control.backend.facade.user_access_control import UserAccessControl
+from .markdown_conversion import get_markdown_notebook_markdown, is_markdown_notebook_content
+from .markdown_migration import to_markdown_notebook_content
from .models import Notebook, ResourceNotebook
from .sql_v2_state import validate_cell_count
@@ -188,6 +192,13 @@ def create_account_notebook(
created_by_id: int | None = None,
last_modified_by_id: int | None = None,
) -> Notebook:
+ if not is_markdown_notebook_content(content):
+ organization_id = Team.objects.values_list("organization_id", flat=True).get(id=team_id)
+ content = to_markdown_notebook_content(content, organization_id=organization_id)
+ # A converted or synthesized document can hold more cells than the editor allows, so count it before saving.
+ validate_cell_count(None, content)
+ # Search reads text_content, so it mirrors the stored markdown.
+ text_content = get_markdown_notebook_markdown(content)
with transaction.atomic():
notebook = Notebook.objects.create(
team_id=team_id,
diff --git a/products/notebooks/backend/markdown_conversion.py b/products/notebooks/backend/markdown_conversion.py
index 3b2a04b07a36..aff582108b3c 100644
--- a/products/notebooks/backend/markdown_conversion.py
+++ b/products/notebooks/backend/markdown_conversion.py
@@ -657,9 +657,17 @@ def _serialize_component_node(tag_name: str, props: Mapping[str, NotebookPropVal
return f"<{tag_name}{_serialize_component_props(props)} />"
+# A prop name is written into the tag unquoted, so a name outside this grammar could close the tag and open another.
+_COMPONENT_PROP_NAME_REGEX = re.compile(r"[A-Za-z_][A-Za-z0-9_-]*")
+
+
def _serialize_component_props(props: Mapping[str, NotebookPropValue]) -> str:
serializable_props = _get_serializable_component_props(props)
- entries = _get_ordered_component_prop_entries(serializable_props)
+ entries = [
+ (key, value)
+ for key, value in _get_ordered_component_prop_entries(serializable_props)
+ if _COMPONENT_PROP_NAME_REGEX.fullmatch(key)
+ ]
return "".join(f" {key}" if value is True else f" {key}={_serialize_prop_value(value)}" for key, value in entries)
diff --git a/products/notebooks/backend/markdown_migration.py b/products/notebooks/backend/markdown_migration.py
index 7483f4e44802..8bb0023b2571 100644
--- a/products/notebooks/backend/markdown_migration.py
+++ b/products/notebooks/backend/markdown_migration.py
@@ -1,6 +1,7 @@
from collections.abc import Callable
from datetime import timedelta
from typing import Any, cast
+from uuid import UUID
from django.db import transaction
from django.db.models import Q, QuerySet
@@ -16,11 +17,14 @@ from products.notebooks.backend.facade.contracts import (
MarkdownNotebookMigrationPreview,
MarkdownNotebookMigrationResult,
MarkdownNotebookMigrationStats,
+ NotebookContentNotConvertible,
)
from products.notebooks.backend.markdown_conversion import (
+ JSONContent,
NotebookMarkdownConversionOptions,
build_markdown_notebook_content,
convert_notebook_content_to_markdown,
+ get_markdown_notebook_markdown,
is_markdown_notebook_content,
notebook_content_has_comment_marks,
)
@@ -58,19 +62,16 @@ def migrate_notebooks_to_markdown(
queryset = queryset[:batch_size]
for notebook in queryset.iterator(chunk_size=100):
- if is_markdown_notebook_content(notebook.content):
- skipped += 1
- continue
-
try:
- markdown = convert_notebook_content_to_markdown(
+ next_content = to_markdown_notebook_content(
notebook.content,
- NotebookMarkdownConversionOptions(
- comment_replies_by_mark_id=_build_comment_replies_by_mark_id(notebook),
- get_mention_label=_build_mention_label_getter(notebook),
- ),
+ organization_id=notebook.team.organization_id,
+ comment_replies_by_mark_id=_build_comment_replies_by_mark_id(notebook),
)
- next_content = build_markdown_notebook_content(markdown)
+ if next_content is None:
+ skipped += 1
+ continue
+ markdown = get_markdown_notebook_markdown(next_content)
if dry_run:
converted += 1
if len(previews) < max_previews:
@@ -229,14 +230,43 @@ def _comment_to_reply(comment: Comment) -> dict[str, Any]:
}
-def _build_mention_label_getter(notebook: Notebook) -> Callable[[int], str | None]:
- user_ids = _collect_mention_user_ids(notebook.content)
+def to_markdown_notebook_content(
+ content: Any,
+ *,
+ organization_id: UUID,
+ comment_replies_by_mark_id: dict[str, list[Any]] | None = None,
+) -> JSONContent | None:
+ """Convert a rich-text notebook document into a markdown notebook document.
+
+ Returns None when the content already is a markdown notebook document. The admin migration and
+ notebook creation both call this, so a notebook created from rich text matches a migrated one.
+ Raises NotebookContentNotConvertible when the document is malformed, for example when a node's
+ marks are not a list.
+ """
+ if is_markdown_notebook_content(content):
+ return None
+ try:
+ # The mention scan walks the same caller-supplied tree as the converter, so its failures map to the same error.
+ options = NotebookMarkdownConversionOptions(
+ comment_replies_by_mark_id=comment_replies_by_mark_id,
+ get_mention_label=_build_mention_label_getter(content, organization_id),
+ )
+ markdown = convert_notebook_content_to_markdown(content, options)
+ except (AttributeError, KeyError, RecursionError, TypeError, ValueError) as err:
+ raise NotebookContentNotConvertible(
+ "Notebook content is not a valid rich-text document, so it cannot be stored as a markdown notebook."
+ ) from err
+ return build_markdown_notebook_content(markdown)
+
+
+def _build_mention_label_getter(content: Any, organization_id: UUID) -> Callable[[int], str | None]:
+ user_ids = _collect_mention_user_ids(content)
if not user_ids:
return lambda user_id: None
users = User.objects.filter(
id__in=user_ids,
- organization_membership__organization_id=notebook.team.organization_id,
+ organization_membership__organization_id=organization_id,
).only("id", "first_name", "email")
labels_by_user_id = {
user.id: f"@{user.first_name or user.email}" for user in users if user.first_name or user.email
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index ab3120d0b969..2f8f7f5f2f73 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -63,6 +63,7 @@ from products.notebooks.backend.analytics import (
notebook_node_count,
)
from products.notebooks.backend.collab import submit_steps
+from products.notebooks.backend.facade.api import to_markdown_notebook_content
from products.notebooks.backend.facade.compute_pricing import (
COMPUTE_PRESETS,
DEFAULT_COMPUTE_PRESET_KEY,
@@ -70,7 +71,11 @@ from products.notebooks.backend.facade.compute_pricing import (
find_matching_preset,
get_compute_rates,
)
-from products.notebooks.backend.facade.contracts import NotebookRunBusy, TeamRunCapacityFull
+from products.notebooks.backend.facade.contracts import (
+ NotebookContentNotConvertible,
+ NotebookRunBusy,
+ TeamRunCapacityFull,
+)
from products.notebooks.backend.facade.kernel_sandbox_usage import record_sandbox_ended_by_id
from products.notebooks.backend.facade.sql_v2 import acquire_run_slots, release_run_slots
from products.notebooks.backend.facade.widgets import (
@@ -304,7 +309,9 @@ class NotebookSerializer(NotebookMinimalSerializer):
]
extra_kwargs = {
**_NOTEBOOK_FIELD_HELP_TEXTS,
- "content": {"help_text": "Notebook content as a ProseMirror JSON document structure."},
+ "content": {
+ "help_text": "Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown."
+ },
"text_content": {"help_text": "Plain text representation of the notebook content for search."},
"version": {
"help_text": "Version number for optimistic concurrency control. Must match the current version when updating content."
@@ -344,6 +351,25 @@ class NotebookSerializer(NotebookMinimalSerializer):
)
validated_data["short_id"] = short_id
+ # Counted before conversion, so the event keeps reporting the size of the document the caller sent.
+ node_count = notebook_node_count(validated_data.get("content"))
+ # The cell tools and the editor work on markdown notebooks only, so a create never stores rich text.
+ try:
+ markdown_content = to_markdown_notebook_content(
+ validated_data.get("content"), organization_id=team.organization_id
+ )
+ except NotebookContentNotConvertible as err:
+ raise serializers.ValidationError({"content": str(err)})
+ if markdown_content is not None:
+ # validate_content counted cells before conversion, when rich text has none, so count the converted document.
+ try:
+ validate_cell_count(None, markdown_content)
+ except NotebookCellLimitExceeded as err:
+ raise serializers.ValidationError({"content": str(err)})
+ validated_data["content"] = markdown_content
+ # Search reads text_content, so it mirrors the stored markdown, as a markdown save does.
+ validated_data["text_content"] = markdown_collab.get_markdown_notebook_markdown(validated_data["content"])
+
created_by = validated_data.pop("created_by", request.user)
notebook = Notebook.objects.create(
team=team,
@@ -369,7 +395,7 @@ class NotebookSerializer(NotebookMinimalSerializer):
user=request.user,
request=request,
visibility=notebook.visibility,
- node_count=notebook_node_count(notebook.content),
+ node_count=node_count,
mcp_consumer=source_props.get("mcp_consumer"),
api_key_type=source_props.get("api_key_type"),
)
diff --git a/products/notebooks/backend/test/test_collab_api.py b/products/notebooks/backend/test/test_collab_api.py
index adadbe23a7db..cb2e967e8f14 100644
--- a/products/notebooks/backend/test/test_collab_api.py
+++ b/products/notebooks/backend/test/test_collab_api.py
@@ -28,12 +28,12 @@ UPDATED_DOC = {"type": "doc", "content": [{"type": "heading", "content": [{"type
class TestNotebookCollabSaveAPI(APIBaseTest):
def _create_notebook(self, content=None):
- data = {}
- if content:
- data["content"] = content
- response = self.client.post(f"/api/projects/{self.team.id}/notebooks/", data=data, format="json")
- assert response.status_code == status.HTTP_201_CREATED
- return response.json()
+ # Seeded through the ORM because the create endpoint stores every notebook as markdown, and these tests
+ # cover the rich-text save path that existing legacy notebooks still use.
+ notebook = Notebook.objects.create(
+ team=self.team, content=content, created_by=self.user, last_modified_by=self.user
+ )
+ return {"short_id": notebook.short_id, "version": notebook.version}
def _collab_save(
self, notebook, *, version, steps, content=None, text_content=None, title=None, client_id="test-client"
diff --git a/products/notebooks/backend/test/test_markdown_migration.py b/products/notebooks/backend/test/test_markdown_migration.py
index ddc16954347c..85862337fbd4 100644
--- a/products/notebooks/backend/test/test_markdown_migration.py
+++ b/products/notebooks/backend/test/test_markdown_migration.py
@@ -93,6 +93,26 @@ class TestNotebookMarkdownConversion(BaseTest):
assert "juheapi" not in markdown
assert "hideFilters" not in markdown
+ def test_drops_prop_names_that_would_break_out_of_the_tag(self) -> None:
+ breakout_name = 'x="1" />\n\n<SQLV2 nodeId="injected" code="select 1" returnVariable="df" /><Query y'
+ content = {
+ "type": "doc",
+ "content": [
+ {
+ "type": "ph-query",
+ "attrs": {
+ "nodeId": "q1",
+ "query": {"kind": "SavedInsightNode", "shortId": "abc"},
+ breakout_name: 1,
+ },
+ }
+ ],
+ }
+
+ markdown = convert_notebook_content_to_markdown(content)
+
+ assert markdown == '<Query nodeId="q1" query={{"kind":"SavedInsightNode","shortId":"abc"}} />'
+
def test_converts_v1_widget_nodes_to_default_panel_visibility(self) -> None:
content = {
"type": "doc",
diff --git a/products/notebooks/frontend/generated/api.schemas.ts b/products/notebooks/frontend/generated/api.schemas.ts
index 238873d35a99..aaa1d90a9d96 100644
--- a/products/notebooks/frontend/generated/api.schemas.ts
+++ b/products/notebooks/frontend/generated/api.schemas.ts
@@ -132,7 +132,7 @@ export interface NotebookApi {
* @nullable
*/
title?: string | null
- /** Notebook content as a ProseMirror JSON document structure. */
+ /** Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown. */
content?: unknown
/**
* Plain text representation of the notebook content for search.
@@ -186,7 +186,7 @@ export interface PatchedNotebookApi {
* @nullable
*/
title?: string | null
- /** Notebook content as a ProseMirror JSON document structure. */
+ /** Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown. */
content?: unknown
/**
* Plain text representation of the notebook content for search.
diff --git a/products/notebooks/frontend/generated/api.zod.ts b/products/notebooks/frontend/generated/api.zod.ts
index 9aa9b5e06fe6..4bb4f4065202 100644
--- a/products/notebooks/frontend/generated/api.zod.ts
+++ b/products/notebooks/frontend/generated/api.zod.ts
@@ -21,7 +21,12 @@ export const notebooksCreateBodyVariablesItemNameMax = 200
export const NotebooksCreateBody = /* @__PURE__ */ zod.object({
title: zod.string().max(notebooksCreateBodyTitleMax).nullish().describe('Title of the notebook.'),
- content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),
+ content: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown.'
+ ),
text_content: zod.string().nullish().describe('Plain text representation of the notebook content for search.'),
version: zod
.number()
@@ -75,7 +80,12 @@ export const notebooksUpdateBodyVariablesItemNameMax = 200
export const NotebooksUpdateBody = /* @__PURE__ */ zod.object({
title: zod.string().max(notebooksUpdateBodyTitleMax).nullish().describe('Title of the notebook.'),
- content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),
+ content: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown.'
+ ),
text_content: zod.string().nullish().describe('Plain text representation of the notebook content for search.'),
version: zod
.number()
@@ -129,7 +139,12 @@ export const notebooksPartialUpdateBodyVariablesItemNameMax = 200
export const NotebooksPartialUpdateBody = /* @__PURE__ */ zod.object({
title: zod.string().max(notebooksPartialUpdateBodyTitleMax).nullish().describe('Title of the notebook.'),
- content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),
+ content: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown.'
+ ),
text_content: zod.string().nullish().describe('Plain text representation of the notebook content for search.'),
version: zod
.number()
@@ -325,7 +340,12 @@ export const notebooksKernelExecuteCreateBodyVariablesItemNameMax = 200
export const NotebooksKernelExecuteCreateBody = /* @__PURE__ */ zod.object({
title: zod.string().max(notebooksKernelExecuteCreateBodyTitleMax).nullish().describe('Title of the notebook.'),
- content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),
+ content: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown.'
+ ),
text_content: zod.string().nullish().describe('Plain text representation of the notebook content for search.'),
version: zod
.number()
@@ -379,7 +399,12 @@ export const notebooksKernelRestartCreateBodyVariablesItemNameMax = 200
export const NotebooksKernelRestartCreateBody = /* @__PURE__ */ zod.object({
title: zod.string().max(notebooksKernelRestartCreateBodyTitleMax).nullish().describe('Title of the notebook.'),
- content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),
+ content: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown.'
+ ),
text_content: zod.string().nullish().describe('Plain text representation of the notebook content for search.'),
version: zod
.number()
@@ -433,7 +458,12 @@ export const notebooksKernelStartCreateBodyVariablesItemNameMax = 200
export const NotebooksKernelStartCreateBody = /* @__PURE__ */ zod.object({
title: zod.string().max(notebooksKernelStartCreateBodyTitleMax).nullish().describe('Title of the notebook.'),
- content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),
+ content: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown.'
+ ),
text_content: zod.string().nullish().describe('Plain text representation of the notebook content for search.'),
version: zod
.number()
@@ -487,7 +517,12 @@ export const notebooksKernelStopCreateBodyVariablesItemNameMax = 200
export const NotebooksKernelStopCreateBody = /* @__PURE__ */ zod.object({
title: zod.string().max(notebooksKernelStopCreateBodyTitleMax).nullish().describe('Title of the notebook.'),
- content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),
+ content: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown.'
+ ),
text_content: zod.string().nullish().describe('Plain text representation of the notebook content for search.'),
version: zod
.number()
diff --git a/products/notebooks/mcp/tools.yaml b/products/notebooks/mcp/tools.yaml
index 88fc77512d6c..4eb8132057e8 100644
--- a/products/notebooks/mcp/tools.yaml
+++ b/products/notebooks/mcp/tools.yaml
@@ -102,9 +102,10 @@ tools:
every embedded node a short `attrs.title` saying what it shows — it renders in the node's header and is what
a reader skims instead of the query.
- This creates a rich-text (ProseMirror) notebook — use it for document-style notebooks built around embedded
- charts and saved insights. For step-by-step data analysis with executable SQL/Python cells, use
- `notebooks-create-markdown` instead.
+ The server stores the notebook as a markdown notebook: it converts this document, embedded charts included,
+ into markdown with component tags. When you update the notebook later, notebooks-retrieve shows its content
+ as one ph-markdown-notebook node, so keep that structure and edit attrs.markdown. For step-by-step data
+ analysis with executable SQL/Python cells, use `notebooks-create-markdown` instead.
exclude_params:
- _create_in_folder
feature_flag: revamped-py-notebooks
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index dc372ed866c7..0cdcabe374ae 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -300,7 +300,7 @@
"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 the note body as Markdown via `text_content` — the server converts it into a formatted notebook (headings `#` through `######`, bullet lists `-`, ordered lists `1.`, fenced code blocks, `**bold**`, `*italic*`, `` `code` ``, and `[label](url)` links). Pass `content` (ProseMirror JSON) only if you already have a structured document; in most cases leave it unset and write Markdown in `text_content`. The notebook is created with internal visibility so it does not appear in the global notebooks list.",
+ "description": "Create a notebook attached to a Customer Analytics account. Use for persisting investigations, call notes, and other free-form context. Provide `title` and the note body as Markdown via `text_content` — the server converts it into a formatted notebook (headings `#` through `######`, bullet lists `-`, ordered lists `1.`, fenced code blocks, `**bold**`, `*italic*`, `` `code` ``, and `[label](url)` links). Pass `content` (ProseMirror JSON) only if you already have a structured document; the server converts it into the same markdown notebook format. In most cases leave it unset and write Markdown in `text_content`. 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",
@@ -8411,7 +8411,7 @@
"feature_flag": "revamped-py-notebooks"
},
"notebooks-create": {
- "description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id. Embedded charts use `{type: \"ph-query\", attrs: {nodeId, query}}` nodes. The `query` object must be one of: (a) `{kind: \"DataVisualizationNode\", source: {kind: \"HogQLQuery\", query: \"SELECT ...\"}, display: \"ActionsBar\", chartSettings: {...}}` for SQL charts — do NOT wrap this in an InsightVizNode; (b) `{kind: \"InsightVizNode\", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery>}` for product-analytics insights; or (c) `{kind: \"SavedInsightNode\", shortId: \"...\"}` to embed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode` wrapping a SQL chart. Give every embedded node a short `attrs.title` saying what it shows — it renders in the node's header and is what a reader skims instead of the query.\nThis creates a rich-text (ProseMirror) notebook — use it for document-style notebooks built around embedded charts and saved insights. For step-by-step data analysis with executable SQL/Python cells, use `notebooks-create-markdown` instead.",
+ "description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id. Embedded charts use `{type: \"ph-query\", attrs: {nodeId, query}}` nodes. The `query` object must be one of: (a) `{kind: \"DataVisualizationNode\", source: {kind: \"HogQLQuery\", query: \"SELECT ...\"}, display: \"ActionsBar\", chartSettings: {...}}` for SQL charts — do NOT wrap this in an InsightVizNode; (b) `{kind: \"InsightVizNode\", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery>}` for product-analytics insights; or (c) `{kind: \"SavedInsightNode\", shortId: \"...\"}` to embed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode` wrapping a SQL chart. Give every embedded node a short `attrs.title` saying what it shows — it renders in the node's header and is what a reader skims instead of the query.\nThe server stores the notebook as a markdown notebook: it converts this document, embedded charts included, into markdown with component tags. When you update the notebook later, notebooks-retrieve shows its content as one ph-markdown-notebook node, so keep that structure and edit attrs.markdown. For step-by-step data analysis with executable SQL/Python cells, use `notebooks-create-markdown` instead.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Create notebook",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 09c1288552b8..9f73270fcba5 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -300,7 +300,7 @@
"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 the note body as Markdown via `text_content` — the server converts it into a formatted notebook (headings `#` through `######`, bullet lists `-`, ordered lists `1.`, fenced code blocks, `**bold**`, `*italic*`, `` `code` ``, and `[label](url)` links). Pass `content` (ProseMirror JSON) only if you already have a structured document; in most cases leave it unset and write Markdown in `text_content`. The notebook is created with internal visibility so it does not appear in the global notebooks list.",
+ "description": "Create a notebook attached to a Customer Analytics account. Use for persisting investigations, call notes, and other free-form context. Provide `title` and the note body as Markdown via `text_content` — the server converts it into a formatted notebook (headings `#` through `######`, bullet lists `-`, ordered lists `1.`, fenced code blocks, `**bold**`, `*italic*`, `` `code` ``, and `[label](url)` links). Pass `content` (ProseMirror JSON) only if you already have a structured document; the server converts it into the same markdown notebook format. In most cases leave it unset and write Markdown in `text_content`. 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",
@@ -8838,7 +8838,7 @@
"feature_flag": "revamped-py-notebooks"
},
"notebooks-create": {
- "description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id. Embedded charts use `{type: \"ph-query\", attrs: {nodeId, query}}` nodes. The `query` object must be one of: (a) `{kind: \"DataVisualizationNode\", source: {kind: \"HogQLQuery\", query: \"SELECT ...\"}, display: \"ActionsBar\", chartSettings: {...}}` for SQL charts — do NOT wrap this in an InsightVizNode; (b) `{kind: \"InsightVizNode\", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery>}` for product-analytics insights; or (c) `{kind: \"SavedInsightNode\", shortId: \"...\"}` to embed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode` wrapping a SQL chart. Give every embedded node a short `attrs.title` saying what it shows — it renders in the node's header and is what a reader skims instead of the query.\nThis creates a rich-text (ProseMirror) notebook — use it for document-style notebooks built around embedded charts and saved insights. For step-by-step data analysis with executable SQL/Python cells, use `notebooks-create-markdown` instead.",
+ "description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id. Embedded charts use `{type: \"ph-query\", attrs: {nodeId, query}}` nodes. The `query` object must be one of: (a) `{kind: \"DataVisualizationNode\", source: {kind: \"HogQLQuery\", query: \"SELECT ...\"}, display: \"ActionsBar\", chartSettings: {...}}` for SQL charts — do NOT wrap this in an InsightVizNode; (b) `{kind: \"InsightVizNode\", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery>}` for product-analytics insights; or (c) `{kind: \"SavedInsightNode\", shortId: \"...\"}` to embed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode` wrapping a SQL chart. Give every embedded node a short `attrs.title` saying what it shows — it renders in the node's header and is what a reader skims instead of the query.\nThe server stores the notebook as a markdown notebook: it converts this document, embedded charts included, into markdown with component tags. When you update the notebook later, notebooks-retrieve shows its content as one ph-markdown-notebook node, so keep that structure and edit attrs.markdown. For step-by-step data analysis with executable SQL/Python cells, use `notebooks-create-markdown` instead.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Create notebook",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a4d2d3461bb3..ff3ff46979e0 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -859,7 +859,7 @@ export namespace Schemas {
* @nullable
*/
title?: string | null;
- /** Notebook content as a ProseMirror JSON document structure. */
+ /** Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook. */
content?: unknown;
/**
* Plain text representation of the notebook content for search.
@@ -54397,7 +54397,7 @@ export namespace Schemas {
* @nullable
*/
title?: string | null;
- /** Notebook content as a ProseMirror JSON document structure. */
+ /** Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown. */
content?: unknown;
/**
* Plain text representation of the notebook content for search.
@@ -67694,7 +67694,7 @@ export namespace Schemas {
* @nullable
*/
title?: string | null;
- /** Notebook content as a ProseMirror JSON document structure. */
+ /** Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown. */
content?: unknown;
/**
* Plain text representation of the notebook content for search.
diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.ts
index 97f2711b3d82..259ed3449998 100644
--- a/services/mcp/src/generated/customer_analytics/api.ts
+++ b/services/mcp/src/generated/customer_analytics/api.ts
@@ -279,7 +279,12 @@ export const AccountsNotebooksCreateBody = () => zod.object({
.max(accountsNotebooksCreateBodyTitleMax)
.nullish()
.describe('Human-readable title of the account notebook.'),
- content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),
+ content: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook.'
+ ),
text_content: zod.string().nullish().describe('Plain text representation of the notebook content for search.'),
})
diff --git a/services/mcp/src/generated/notebooks/api.ts b/services/mcp/src/generated/notebooks/api.ts
index be70524273c8..b0b6052b9fff 100644
--- a/services/mcp/src/generated/notebooks/api.ts
+++ b/services/mcp/src/generated/notebooks/api.ts
@@ -63,7 +63,12 @@ export const notebooksCreateBodyVariablesItemNameMax = 200
export const NotebooksCreateBody = () => zod.object({
title: zod.string().max(notebooksCreateBodyTitleMax).nullish().describe('Title of the notebook.'),
- content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),
+ content: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown.'
+ ),
text_content: zod.string().nullish().describe('Plain text representation of the notebook content for search.'),
version: zod
.number()
@@ -137,7 +142,12 @@ export const notebooksPartialUpdateBodyVariablesItemNameMax = 200
export const NotebooksPartialUpdateBody = () => zod.object({
title: zod.string().max(notebooksPartialUpdateBodyTitleMax).nullish().describe('Title of the notebook.'),
- content: zod.unknown().optional().describe('Notebook content as a ProseMirror JSON document structure.'),
+ content: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown.'
+ ),
text_content: zod.string().nullish().describe('Plain text representation of the notebook content for search.'),
version: zod
.number()
diff --git a/services/mcp/tests/tools/notebooks.integration.test.ts b/services/mcp/tests/tools/notebooks.integration.test.ts
index e8a3ec9e3662..d410544141bb 100644
--- a/services/mcp/tests/tools/notebooks.integration.test.ts
+++ b/services/mcp/tests/tools/notebooks.integration.test.ts
@@ -177,14 +177,15 @@ describe('Notebooks', { concurrent: false }, () => {
const retrieveTool = getToolByName('notebooks-retrieve')
const editTool = getToolByName('notebook-edit')
- it('should replace a paragraph by value and bump the version', async () => {
+ // notebooks-create stores rich-text content as a markdown notebook, so these edits target its markdown.
+ it('should replace a paragraph and bump the version', async () => {
const createResult = await createTool.handler(context, {
title: generateUniqueKey('Edit Test Notebook'),
content: {
type: 'doc',
content: [
{ type: 'heading', attrs: { level: 1 }, content: [{ type: 'text', text: 'Heading' }] },
- { type: 'paragraph', content: [{ type: 'text', text: 'Original paragraph.' }] },
+ { type: 'paragraph', content: [{ type: 'text', text: 'Original paragraph' }] },
],
},
})
@@ -193,16 +194,16 @@ describe('Notebooks', { concurrent: false }, () => {
const editResult = await editTool.handler(context, {
short_id: created.short_id,
- old_value: { type: 'paragraph', content: [{ type: 'text', text: 'Original paragraph.' }] },
- new_value: { type: 'paragraph', content: [{ type: 'text', text: 'Edited paragraph.' }] },
+ old_markdown: 'Original paragraph',
+ new_markdown: 'Edited paragraph',
})
const edited = parseToolResponse(editResult)
expect(edited.short_id).toBe(created.short_id)
expect(edited.version).toBe(created.version + 1)
const serialized = JSON.stringify(edited.content)
- expect(serialized).toContain('Edited paragraph.')
- expect(serialized).not.toContain('Original paragraph.')
+ expect(serialized).toContain('Edited paragraph')
+ expect(serialized).not.toContain('Original paragraph')
})
it('should replace every occurrence when replace_all is true', async () => {
@@ -221,18 +222,18 @@ describe('Notebooks', { concurrent: false }, () => {
const editResult = await editTool.handler(context, {
short_id: created.short_id,
- old_value: { type: 'text', text: 'duplicate' },
- new_value: { type: 'text', text: 'unique' },
+ old_markdown: 'duplicate',
+ new_markdown: 'unique',
replace_all: true,
})
const edited = parseToolResponse(editResult)
const serialized = JSON.stringify(edited.content)
- expect(serialized).not.toContain('"text":"duplicate"')
- expect((serialized.match(/"text":"unique"/g) || []).length).toBe(2)
+ expect(serialized).not.toContain('duplicate')
+ expect((serialized.match(/unique/g) || []).length).toBe(2)
})
- it('should error when old_value matches multiple places without replace_all', async () => {
+ it('should error when old_markdown matches multiple places without replace_all', async () => {
const createResult = await createTool.handler(context, {
title: generateUniqueKey('Edit Ambiguous Notebook'),
content: {
@@ -249,8 +250,8 @@ describe('Notebooks', { concurrent: false }, () => {
await expect(
editTool.handler(context, {
short_id: created.short_id,
- old_value: { type: 'text', text: 'duplicate' },
- new_value: { type: 'text', text: 'unique' },
+ old_markdown: 'duplicate',
+ new_markdown: 'unique',
})
).rejects.toThrow(/matches 2 places/)
@@ -260,7 +261,7 @@ describe('Notebooks', { concurrent: false }, () => {
expect(retrieved.version).toBe(created.version)
})
- it('should error when old_value is not found', async () => {
+ it('should error when old_markdown is not found', async () => {
const createResult = await createTool.handler(context, {
title: generateUniqueKey('Edit Missing Notebook'),
content: {
@@ -274,8 +275,8 @@ describe('Notebooks', { concurrent: false }, () => {
await expect(
editTool.handler(context, {
short_id: created.short_id,
- old_value: { type: 'text', text: 'Nope' },
- new_value: { type: 'text', text: 'Something' },
+ old_markdown: 'Nope',
+ new_markdown: 'Something',
})
).rejects.toThrow(/was not found/)
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-create.json
index 7ede9f21d2da..e7802044eba1 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-create.json
@@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"content": {
- "description": "Notebook content as a ProseMirror JSON document structure."
+ "description": "Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown."
},
"deleted": {
"description": "Whether the notebook has been soft-deleted.",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-partial-update.json
index cd0a9348bc7b..b52060709fc7 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-partial-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-partial-update.json
@@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"content": {
- "description": "Notebook content as a ProseMirror JSON document structure."
+ "description": "Notebook content as a ProseMirror JSON document. On create, the server stores it as a markdown notebook: one ph-markdown-notebook node that holds the converted markdown."
},
"deleted": {
"description": "Whether the notebook has been soft-deleted.",