:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(notebooks): MCP notebook-edit tool for collaborative editing (#59288)
Alex Lider412e05a6c279
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 69ff544af47c..bca4c0776e14 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3636,6 +3636,15 @@ importers:prom-client:specifier: ^14.2.0version: 14.2.0+ prosemirror-collab:+ specifier: ^1.3.1+ version: 1.3.1+ prosemirror-model:+ specifier: ^1.25.2+ version: 1.25.2+ prosemirror-transform:+ specifier: ^1.10.4+ version: 1.10.4uuid:specifier: ^11.1.0version: 11.1.0diff --git a/products/notebooks/mcp/tools.yaml b/products/notebooks/mcp/tools.yamlindex 2f6bcdb7bd16..7e9c27373a91 100644--- a/products/notebooks/mcp/tools.yaml+++ b/products/notebooks/mcp/tools.yaml@@ -123,6 +123,8 @@ tools:Retrieve the notebook first to get the latest version.exclude_params:- _create_in_folder+ feature_flag: notebooks-collaboration+ feature_flag_behavior: disablenotebooks-recording-comments-retrieve:operation: notebooks_recording_comments_retrieveenabled: falsediff --git a/services/mcp/package.json b/services/mcp/package.jsonindex 50c8cf6c9232..04822e720e6b 100644--- a/services/mcp/package.json+++ b/services/mcp/package.json@@ -57,6 +57,9 @@"posthog-js-lite": "4.2.2","posthog-node": "^5.25.0","prom-client": "^14.2.0",+ "prosemirror-collab": "^1.3.1",+ "prosemirror-model": "^1.25.2",+ "prosemirror-transform": "^1.10.4","uuid": "^11.1.0","yaml": "^2.8.2","zod": "^4.3.6"diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex c444627ee3aa..d0b7bfc49f91 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3953,7 +3953,9 @@"idempotentHint": true,"openWorldHint": true,"readOnlyHint": false- }+ },+ "feature_flag": "notebooks-collaboration",+ "feature_flag_behavior": "disable"},"notebooks-retrieve": {"description": "Get a specific notebook by its short_id. Returns the full notebook including title, content, version, and creation/modification metadata.",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex cc452c10614e..ec41d8c017c8 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -4208,6 +4208,22 @@"readOnlyHint": true}},+ "notebook-edit": {+ "description": "Edit part of a notebook's content. Use this for any change inside a notebook — text, headings, attributes, whole paragraphs. Call `notebooks-retrieve` first to see what to target.\n\nMatching is by content. The tool finds `old_value` anywhere in the notebook and swaps it for `new_value` in place.\n\nOn success, returns the updated notebook with the new content and bumped version. On a 409 or 410 error, the notebook has changed since you loaded it — call `notebooks-retrieve` and re-apply your edit against the latest content.",+ "category": "Notebooks",+ "feature": "notebooks",+ "summary": "Edit part of a notebook's content.",+ "title": "Edit notebook",+ "required_scopes": ["notebook:write"],+ "new_mcp": true,+ "feature_flag": "notebooks-collaboration",+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"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.","category": "Notebooks",@@ -4266,7 +4282,9 @@"idempotentHint": true,"openWorldHint": true,"readOnlyHint": false- }+ },+ "feature_flag": "notebooks-collaboration",+ "feature_flag_behavior": "disable"},"notebooks-retrieve": {"description": "Get a specific notebook by its short_id. Returns the full notebook including title, content, version, and creation/modification metadata.",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex 6ea6e3042f58..7c5379943e94 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -227,6 +227,22 @@"readOnlyHint": true}},+ "notebook-edit": {+ "description": "Edit part of a notebook's content. Use this for any change inside a notebook — text, headings, attributes, whole paragraphs. Call `notebooks-retrieve` first to see what to target.\n\nMatching is by content. The tool finds `old_value` anywhere in the notebook and swaps it for `new_value` in place.\n\nOn success, returns the updated notebook with the new content and bumped version. On a 409 or 410 error, the notebook has changed since you loaded it — call `notebooks-retrieve` and re-apply your edit against the latest content.",+ "category": "Notebooks",+ "feature": "notebooks",+ "summary": "Edit part of a notebook's content.",+ "title": "Edit notebook",+ "required_scopes": ["notebook:write"],+ "new_mcp": true,+ "feature_flag": "notebooks-collaboration",+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"get-llm-total-costs-for-project": {"description": "Fetches the total LLM daily costs for each model for a project over a given number of days. If no number of days is provided, it defaults to 7. The results are sorted by model name. The total cost is rounded to 4 decimal places. The query is executed against the project's data warehouse. Show the results as a Markdown formatted table with the following information for each model: Model name, Total cost in USD, Each day's date, Each day's cost in USD. Write in bold the model name with the highest total cost. Properly render the markdown table in the response.","category": "AI observability",diff --git a/services/mcp/src/lib/prosemirror/schema.ts b/services/mcp/src/lib/prosemirror/schema.tsnew file mode 100644index 000000000000..8daf3ab5c1ef--- /dev/null+++ b/services/mcp/src/lib/prosemirror/schema.ts@@ -0,0 +1,185 @@+/**+ * Builds a permissive ProseMirror schema dynamically from a document so we+ * can parse it without maintaining a hand-rolled list of supported node and+ * mark types.+ */+import { type MarkSpec, type NodeSpec, Schema } from 'prosemirror-model'++export interface ProseMirrorNodeJSON {+ type: string+ content?: ProseMirrorNodeJSON[]+ text?: string+ attrs?: Record<string, unknown>+ marks?: Array<{ type: string; attrs?: Record<string, unknown> }>+}++interface DiscoveredTypes {+ nodes: Map<string, { hasContent: boolean; hasText: boolean }>+ marks: Set<string>+}++function discover(node: ProseMirrorNodeJSON, out: DiscoveredTypes): void {+ const name = typeof node.type === 'string' ? node.type : '_unknown'+ const existing = out.nodes.get(name) ?? { hasContent: false, hasText: false }+ if (Array.isArray(node.content) && node.content.length > 0) {+ existing.hasContent = true+ }+ if (typeof node.text === 'string') {+ existing.hasText = true+ }+ out.nodes.set(name, existing)+ for (const mark of node.marks ?? []) {+ if (mark && typeof mark.type === 'string') {+ out.marks.add(mark.type)+ }+ }+ for (const child of node.content ?? []) {+ discover(child, out)+ }+}++const TEXT_NODE = 'text'++/**+ * Build a ProseMirror Schema that accepts the given doc's full node/mark+ * vocabulary. Always includes `doc` and `text` even if the doc is empty.+ * Each non-text node accepts a single `attrs` object passthrough — attribute+ * keys aren't introspected, so attrs flow through unchanged.+ */+export function buildSchemaForDoc(doc: ProseMirrorNodeJSON | ProseMirrorNodeJSON[]): Schema {+ const discovered: DiscoveredTypes = { nodes: new Map(), marks: new Set() }+ const roots = Array.isArray(doc) ? doc : [doc]+ for (const root of roots) {+ discover(root, discovered)+ }++ // Always ensure foundational types exist even if the doc is degenerate.+ if (!discovered.nodes.has('doc')) {+ discovered.nodes.set('doc', { hasContent: true, hasText: false })+ }+ if (!discovered.nodes.has(TEXT_NODE)) {+ discovered.nodes.set(TEXT_NODE, { hasContent: false, hasText: true })+ }++ const nodes: Record<string, NodeSpec> = {}++ for (const [name, info] of discovered.nodes) {+ if (name === TEXT_NODE) {+ nodes[name] = { group: 'inline' }+ continue+ }++ if (name === 'doc') {+ // Doc is open-ended: any number of block children including zero,+ // which mirrors what happens when an agent deletes every block.+ nodes[name] = { content: 'block*' }+ continue+ }++ const passthroughAttrs: NodeSpec['attrs'] = { attrs: { default: null } }++ if (info.hasText) {+ // Inline-content block (paragraph, heading, code_block, ...).+ // Allow zero children so trailing-paragraph-like nodes parse.+ nodes[name] = {+ content: 'inline*',+ group: 'block',+ attrs: passthroughAttrs,+ marks: '_',+ }+ continue+ }++ if (info.hasContent) {+ // Container block (blockquote, bullet_list, list_item, table, ...).+ nodes[name] = {+ content: 'block*',+ group: 'block',+ attrs: passthroughAttrs,+ marks: '_',+ }+ continue+ }++ // Atomic leaf (ph-recording, image, horizontal_rule, ...).+ nodes[name] = {+ group: 'block',+ atom: true,+ attrs: passthroughAttrs,+ }+ }++ const marks: Record<string, MarkSpec> = {}+ for (const name of discovered.marks) {+ marks[name] = { attrs: { attrs: { default: null } } }+ }++ return new Schema({ nodes, marks })+}++/**+ * Pre-process a document JSON so it can be parsed by a schema that declares+ * a single `attrs` passthrough attribute. Our schema declares one `attrs`+ * attribute that carries each node's original attrs object verbatim, so we+ * wrap `{ level: 1 }` into `{ attrs: { level: 1 } }`. Marks get the same+ * wrapping.+ */+export function packDocAttrs(json: ProseMirrorNodeJSON): ProseMirrorNodeJSON {+ const out: ProseMirrorNodeJSON = { type: json.type }+ if (json.type !== TEXT_NODE) {+ // Carry the original attrs object verbatim under our single passthrough key+ // so we never have to enumerate product-specific attribute names.+ if (json.attrs !== undefined) {+ out.attrs = { attrs: json.attrs as unknown as Record<string, unknown> }+ } else {+ out.attrs = { attrs: null as unknown as Record<string, unknown> }+ }+ }+ if (json.text !== undefined) {+ out.text = json.text+ }+ if (json.marks && json.marks.length > 0) {+ out.marks = json.marks.map((m) => ({+ type: m.type,+ attrs: m.attrs !== undefined ? { attrs: m.attrs } : { attrs: null as unknown as Record<string, unknown> },+ }))+ }+ if (json.content && json.content.length > 0) {+ out.content = json.content.map(packDocAttrs)+ }+ return out+}++/**+ * Inverse of `packDocAttrs` — recover the wire-format attribute shape so the+ * resulting `content` payload that we POST to `collab/save` matches what the+ * frontend would have produced.+ */+export function unpackDocAttrs(json: ProseMirrorNodeJSON): ProseMirrorNodeJSON {+ const out: ProseMirrorNodeJSON = { type: json.type }+ if (json.type !== TEXT_NODE) {+ const wrapped = json.attrs as { attrs?: unknown } | undefined+ const inner = wrapped && 'attrs' in wrapped ? wrapped.attrs : undefined+ if (inner !== undefined && inner !== null) {+ out.attrs = inner as Record<string, unknown>+ }+ }+ if (json.text !== undefined) {+ out.text = json.text+ }+ if (json.marks && json.marks.length > 0) {+ out.marks = json.marks.map((m) => {+ const wrappedMark = m.attrs as { attrs?: unknown } | undefined+ const innerMark = wrappedMark && 'attrs' in wrappedMark ? wrappedMark.attrs : undefined+ const result: { type: string; attrs?: Record<string, unknown> } = { type: m.type }+ if (innerMark !== undefined && innerMark !== null) {+ result.attrs = innerMark as Record<string, unknown>+ }+ return result+ })+ }+ if (json.content && json.content.length > 0) {+ out.content = json.content.map(unpackDocAttrs)+ }+ return out+}diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.tsindex be61371416af..202e3be7c489 100644--- a/services/mcp/src/tools/index.ts+++ b/services/mcp/src/tools/index.ts@@ -13,6 +13,8 @@ import { GENERATED_TOOL_MAP } from './generated'import queryInsight from './insights/query'// AI observabilityimport getLLMCosts from './llmAnalytics/getLLMCosts'+// Notebooks (edit is hand-written — generated CRUD lives in generated/notebooks.ts)+import notebookEdit from './notebooks/edit'// Organizationsimport setActiveOrganization from './organizations/setActive'// PostHog AI tools@@ -76,6 +78,9 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {// AI observability'get-llm-total-costs-for-project': getLLMCosts,+ // Notebooks+ 'notebook-edit': notebookEdit,+// Search'entity-search': entitySearch,diff --git a/services/mcp/src/tools/notebooks/edit.ts b/services/mcp/src/tools/notebooks/edit.tsnew file mode 100644index 000000000000..49e4c2bc293b--- /dev/null+++ b/services/mcp/src/tools/notebooks/edit.ts@@ -0,0 +1,272 @@+/**+ * `notebook-edit` tool.+ *+ * Subtree replacement against the notebook's content tree. The caller supplies+ * `{ short_id, old_value, new_value, replace_all? }` where `old_value` and+ * `new_value` are JSON values describing the subtree to find and the subtree+ * to put in its place. Match is by deep equality of the parsed values, so+ * whitespace, key order, and indentation do not matter — the agent never has+ * to imagine the tool's serialization format.+ *+ * The diff is expressed as a single ProseMirror ReplaceStep and POSTed to+ * `/collab/save` so the edit streams live to other connected clients over SSE.+ *+ * Server errors (409 concurrent edit, 410 stale buffer, etc.) flow through+ * `context.api.request` → PostHogApiError → `handleToolError`, which surfaces+ * the URL, status, and Django response body verbatim to the agent. The 409+ * body already includes the latest version + rebased steps, which the agent+ * can use to retry without an extra read.+ */+import { isDeepStrictEqual } from 'node:util'+import { Fragment, Node } from 'prosemirror-model'+import { type Step, Transform } from 'prosemirror-transform'+import { v4 as uuidv4 } from 'uuid'+import { z } from 'zod'++import type { Schemas } from '@/api/generated'+import { buildSchemaForDoc, packDocAttrs, type ProseMirrorNodeJSON, unpackDocAttrs } from '@/lib/prosemirror/schema'+import type { Context, ToolBase } from '@/tools/types'++const Subtree = z.union([z.record(z.string(), z.unknown()), z.array(z.unknown())])++export const NotebookEditSchema = z+ .object({+ short_id: z.string().describe('The notebook short_id (the public id in the URL, e.g. `aBcD1234`).'),+ old_value: Subtree.describe(+ 'The piece of content to find. Copy it straight out of the response from ' ++ '`notebooks-retrieve` — typically a single node like a text node or a whole ' ++ 'paragraph. Must be a JSON object or array, not a primitive. Must match exactly ' ++ 'one place in the notebook unless `replace_all` is true; if it appears in more ' ++ 'than one place, include more surrounding structure (e.g. pass the parent ' ++ 'paragraph instead of just the text node) to make it unique. To append to the ' ++ 'end of a notebook, pass the last paragraph with content — trailing empty ' ++ 'paragraphs are often identical and will cause an ambiguity error.'+ ),+ new_value: Subtree.describe(+ 'What to put in place of `old_value`. Pass a JSON value of the same shape — the whole ' ++ 'matched piece is replaced, so include every key you want preserved. Must be a JSON ' ++ 'object or array, not a primitive. Must differ from `old_value`.'+ ),+ replace_all: z+ .boolean()+ .optional()+ .describe(+ 'Replace every place `old_value` matches. Default false — the tool errors out if ' ++ '`old_value` is not unique, so you can either narrow `old_value` to a single match ' ++ 'or set `replace_all` to true.'+ ),+ })+ .refine((v) => !isDeepStrictEqual(v.old_value, v.new_value), {+ message: 'old_value and new_value must differ',+ path: ['new_value'],+ })++type Params = z.infer<typeof NotebookEditSchema>++/** Counts subtrees deep-equal to `target`; lets the handler reject bad inputs before mutating. */+function countMatches(tree: unknown, target: unknown): number {+ let count = 0+ const walk = (node: unknown): void => {+ if (isDeepStrictEqual(node, target)) {+ count+++ return+ }+ if (Array.isArray(node)) {+ node.forEach(walk)+ } else if (node !== null && typeof node === 'object') {+ Object.values(node).forEach(walk)+ }+ }+ walk(tree)+ return count+}++/**+ * Walks `tree` and replaces every subtree that deep-equals `target`.+ * When `replaceAll` is false, only the first match is replaced.+ */+function deepReplace<T>(tree: T, target: unknown, replacement: unknown, replaceAll: boolean): T {+ let replaced = 0+ const walk = (node: unknown): unknown => {+ if (isDeepStrictEqual(node, target)) {+ if (!replaceAll && replaced > 0) {+ return node+ }+ replaced+++ return structuredClone(replacement)+ }+ if (Array.isArray(node)) {+ return node.map(walk)+ }+ if (node !== null && typeof node === 'object') {+ return Object.fromEntries(Object.entries(node).map(([k, v]) => [k, walk(v)]))+ }+ return node+ }+ return walk(tree) as T+}++/**+ * Single ReplaceStep covering the smallest top-level block range that differs.+ * Block-level (not character-level).+ */+function buildMinimalSteps(oldDoc: Node, newDoc: Node): Step[] {+ const oldContent = oldDoc.content+ const newContent = newDoc.content+ const oldCount = oldContent.childCount+ const newCount = newContent.childCount++ // Walk in from the start until blocks diverge.+ let startIdx = 0+ while (startIdx < oldCount && startIdx < newCount && oldContent.child(startIdx).eq(newContent.child(startIdx))) {+ startIdx+++ }++ // Walk in from the end until blocks diverge (without crossing startIdx).+ let oldEndIdx = oldCount+ let newEndIdx = newCount+ while (+ oldEndIdx > startIdx &&+ newEndIdx > startIdx &&+ oldContent.child(oldEndIdx - 1).eq(newContent.child(newEndIdx - 1))+ ) {+ oldEndIdx--+ newEndIdx--+ }++ // Identical docs — nothing to send.+ if (startIdx === oldEndIdx && startIdx === newEndIdx) {+ return []+ }++ // Convert block indices to doc positions.+ let fromPos = 0+ for (let i = 0; i < startIdx; i++) {+ fromPos += oldContent.child(i).nodeSize+ }+ let toPos = fromPos+ for (let i = startIdx; i < oldEndIdx; i++) {+ toPos += oldContent.child(i).nodeSize+ }++ // Replacement is the slice of new blocks in [startIdx, newEndIdx).+ const replacementBlocks: Node[] = []+ for (let i = startIdx; i < newEndIdx; i++) {+ replacementBlocks.push(newContent.child(i))+ }++ return new Transform(oldDoc).replaceWith(fromPos, toPos, Fragment.from(replacementBlocks)).steps+}++/**+ * Plain-text view for the search index.+ * Mirrors what the frontend's `editor.getText()` produces.+ */+function buildTextContent(doc: Node): string {+ const parts: string[] = []+ doc.forEach((child) => {+ if (child.isAtom || (child.content.size === 0 && !child.isTextblock)) {+ return+ }+ const text = child.textBetween(0, child.content.size, '\n', ' ')+ if (text.length > 0) {+ parts.push(text)+ }+ })+ return parts.join('\n')+}++export const editHandler: ToolBase<typeof NotebookEditSchema, Schemas.Notebook>['handler'] = async (+ context: Context,+ params: Params+) => {+ const projectId = await context.stateManager.getProjectId()+ const notebookPath = `/api/projects/${encodeURIComponent(projectId)}/notebooks/${encodeURIComponent(params.short_id)}/`++ // Load current notebook.+ const notebook = await context.api.request<Schemas.Notebook>({ method: 'GET', path: notebookPath })++ if (notebook.content === null || typeof notebook.content !== 'object' || Array.isArray(notebook.content)) {+ throw new Error(+ `Notebook ${params.short_id} has no editable content. ` ++ 'Create one with `notebooks-create` or initialise its content first.'+ )+ }++ if (typeof notebook.version !== 'number') {+ throw new Error(`Notebook ${params.short_id} has no numeric version — required for optimistic concurrency.`)+ }++ // Find target subtree(s) and apply the replacement.+ const matches = countMatches(notebook.content, params.old_value)+ if (matches === 0) {+ throw new Error(+ 'old_value was not found in the notebook content. ' ++ 'Matching compares every key, value, and array index — extra or missing fields will ' ++ 'prevent a match. Common causes: an explicit `attrs: null` vs. omitted attrs; content ' ++ 'has changed since you last read it (call `notebooks-retrieve` to refresh); or you ' ++ 'passed only part of the value where the full one is stored.\n\nCurrent notebook ' ++ 'content:\n' ++ JSON.stringify(notebook.content, null, 2)+ )+ }++ if (matches > 1 && params.replace_all !== true) {+ throw new Error(+ `old_value matches ${matches} places in the notebook content. ` ++ 'Either include more surrounding structure to make it unique (e.g. pass the parent ' ++ 'paragraph instead of just a text node), or set `replace_all: true` to replace every match.'+ )+ }++ const newContent = deepReplace(notebook.content, params.old_value, params.new_value, params.replace_all === true)+ if (newContent === null || typeof newContent !== 'object' || Array.isArray(newContent)) {+ throw new Error(+ 'Replacement produced a non-object root. A ProseMirror doc must be `{"type":"doc","content":[...]}` at the top level.'+ )+ }++ const rawContent = notebook.content as unknown as ProseMirrorNodeJSON+ const newContentObj = newContent as unknown as ProseMirrorNodeJSON+ const schema = buildSchemaForDoc([rawContent, newContentObj])++ const oldDoc = Node.fromJSON(schema, packDocAttrs(rawContent))+ let newDoc: Node+ try {+ newDoc = Node.fromJSON(schema, packDocAttrs(newContentObj))+ } catch (e) {+ throw new Error(+ `After applying the replacement, the notebook content does not parse as a valid ProseMirror document: ${+ e instanceof Error ? e.message : String(e)+ }. Check node \`type\` strings, attrs shapes, and that text nodes have a \`text\` field.`+ )+ }++ // Build steps via ProseMirror Transform API+ const steps = buildMinimalSteps(oldDoc, newDoc)+ if (steps.length === 0) {+ return notebook+ }++ // POST to collab/save. Non-2xx responses are thrown as PostHogApiError by `request()`.+ const unpackedContent = unpackDocAttrs(newDoc.toJSON() as ProseMirrorNodeJSON)+ return await context.api.request<Schemas.Notebook>({+ method: 'POST',+ path: `${notebookPath}collab/save/`,+ body: {+ client_id: uuidv4(),+ version: notebook.version,+ steps: steps.map((s) => s.toJSON()),+ content: unpackedContent as unknown as Record<string, unknown>,+ text_content: buildTextContent(newDoc),+ },+ })+}++const tool = (): ToolBase<typeof NotebookEditSchema, Schemas.Notebook> => ({+ name: 'notebook-edit',+ schema: NotebookEditSchema,+ handler: editHandler,+})++export default tooldiff --git a/services/mcp/tests/tools/notebooks.integration.test.ts b/services/mcp/tests/tools/notebooks.integration.test.tsindex 874efd4b801a..e8a3ec9e3662 100644--- a/services/mcp/tests/tools/notebooks.integration.test.ts+++ b/services/mcp/tests/tools/notebooks.integration.test.ts@@ -172,6 +172,115 @@ describe('Notebooks', { concurrent: false }, () => {})})+ describe('notebook-edit tool', () => {+ const createTool = getToolByName('notebooks-create')+ const retrieveTool = getToolByName('notebooks-retrieve')+ const editTool = getToolByName('notebook-edit')++ it('should replace a paragraph by value 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.' }] },+ ],+ },+ })+ const created = parseToolResponse(createResult)+ createdNotebookShortIds.push(created.short_id)++ 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.' }] },+ })+ 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.')+ })++ it('should replace every occurrence when replace_all is true', async () => {+ const createResult = await createTool.handler(context, {+ title: generateUniqueKey('Edit Replace-All Notebook'),+ content: {+ type: 'doc',+ content: [+ { type: 'paragraph', content: [{ type: 'text', text: 'duplicate' }] },+ { type: 'paragraph', content: [{ type: 'text', text: 'duplicate' }] },+ ],+ },+ })+ const created = parseToolResponse(createResult)+ createdNotebookShortIds.push(created.short_id)++ const editResult = await editTool.handler(context, {+ short_id: created.short_id,+ old_value: { type: 'text', text: 'duplicate' },+ new_value: { type: 'text', text: '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)+ })++ it('should error when old_value matches multiple places without replace_all', async () => {+ const createResult = await createTool.handler(context, {+ title: generateUniqueKey('Edit Ambiguous Notebook'),+ content: {+ type: 'doc',+ content: [+ { type: 'paragraph', content: [{ type: 'text', text: 'duplicate' }] },+ { type: 'paragraph', content: [{ type: 'text', text: 'duplicate' }] },+ ],+ },+ })+ const created = parseToolResponse(createResult)+ createdNotebookShortIds.push(created.short_id)++ await expect(+ editTool.handler(context, {+ short_id: created.short_id,+ old_value: { type: 'text', text: 'duplicate' },+ new_value: { type: 'text', text: 'unique' },+ })+ ).rejects.toThrow(/matches 2 places/)++ // Notebook untouched.+ const retrieveResult = await retrieveTool.handler(context, { short_id: created.short_id })+ const retrieved = parseToolResponse(retrieveResult)+ expect(retrieved.version).toBe(created.version)+ })++ it('should error when old_value is not found', async () => {+ const createResult = await createTool.handler(context, {+ title: generateUniqueKey('Edit Missing Notebook'),+ content: {+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Hello' }] }],+ },+ })+ const created = parseToolResponse(createResult)+ createdNotebookShortIds.push(created.short_id)++ await expect(+ editTool.handler(context, {+ short_id: created.short_id,+ old_value: { type: 'text', text: 'Nope' },+ new_value: { type: 'text', text: 'Something' },+ })+ ).rejects.toThrow(/was not found/)+ })+ })+describe('notebooks-destroy tool', () => {const createTool = getToolByName('notebooks-create')const destroyTool = getToolByName('notebooks-destroy')diff --git a/services/mcp/tests/unit/notebook-edit.test.ts b/services/mcp/tests/unit/notebook-edit.test.tsnew file mode 100644index 000000000000..1495c5e5435d--- /dev/null+++ b/services/mcp/tests/unit/notebook-edit.test.ts@@ -0,0 +1,341 @@+import { describe, expect, it, vi } from 'vitest'++import { PostHogApiError } from '@/lib/errors'+import { editHandler, NotebookEditSchema } from '@/tools/notebooks/edit'+import type { Context } from '@/tools/types'++const sampleDoc = {+ type: 'doc',+ content: [+ { type: 'heading', attrs: { level: 1 }, content: [{ type: 'text', text: 'Sample Notebook' }] },+ { type: 'paragraph', content: [{ type: 'text', text: 'First paragraph.' }] },+ { type: 'paragraph', content: [{ type: 'text', text: 'Second paragraph.' }] },+ { type: 'ph-recording', attrs: { id: 'sess-123' } },+ ],+}++// ---------- Input schema -----------------------------------------------------++describe('NotebookEditSchema', () => {+ it('rejects identical old_value and new_value (deep-equal)', () => {+ const result = NotebookEditSchema.safeParse({+ short_id: 'abc',+ old_value: { type: 'text', text: 'same' },+ // Different key order, same value — must still be rejected as deep-equal.+ new_value: { text: 'same', type: 'text' },+ })+ expect(result.success).toBe(false)+ })++ it('accepts a minimal valid payload', () => {+ const result = NotebookEditSchema.safeParse({+ short_id: 'abc',+ old_value: { type: 'text', text: 'a' },+ new_value: { type: 'text', text: 'b' },+ })+ expect(result.success).toBe(true)+ })++ it('accepts replace_all', () => {+ const result = NotebookEditSchema.safeParse({+ short_id: 'abc',+ old_value: { type: 'text', text: 'a' },+ new_value: { type: 'text', text: 'b' },+ replace_all: true,+ })+ expect(result.success).toBe(true)+ })+})++// ---------- editHandler — handler-level smoke test --------------------------++interface MockState {+ notebookContent: typeof sampleDoc | Record<string, unknown> | null+ version: number+ saveCalls: Array<{ body: any }>+ getCalls: number+ /**+ * Queued POST responses. Each entry is either a successful body (returned+ * as-is) or an error to throw (e.g. PostHogApiError for 409/410).+ */+ saveResponses: Array<{ ok: true; body: unknown } | { ok: false; error: Error }>+}++function createMockContext(state: MockState): Context {+ const requestMock = vi.fn(async (opts: { method: string; body?: any }) => {+ if (opts.method === 'GET') {+ state.getCalls+++ return {+ short_id: 'aBcD1234',+ content: state.notebookContent,+ version: state.version,+ title: 'Original',+ }+ }+ // POST → collab/save+ state.saveCalls.push({ body: opts.body })+ const response = state.saveResponses.shift()+ if (!response) {+ throw new Error('No queued response for save call')+ }+ if (!response.ok) {+ throw response.error+ }+ return response.body+ })+ return {+ api: { request: requestMock } as any,+ stateManager: { getProjectId: vi.fn().mockResolvedValue('42') } as any,+ env: {} as any,+ sessionManager: {} as any,+ cache: {} as any,+ getDistinctId: async () => 'test',+ trackEvent: async () => {},+ }+}++describe('editHandler', () => {+ it('happy path: replaces a text node by value and returns the updated notebook', async () => {+ const updatedNotebook = {+ short_id: 'aBcD1234',+ content: sampleDoc,+ version: 8,+ title: 'Original',+ }+ const state: MockState = {+ notebookContent: sampleDoc,+ version: 7,+ saveCalls: [],+ getCalls: 0,+ saveResponses: [{ ok: true, body: updatedNotebook }],+ }+ const context = createMockContext(state)++ const result = await editHandler(context, {+ short_id: 'aBcD1234',+ old_value: { type: 'text', text: 'First paragraph.' },+ new_value: { type: 'text', text: 'First paragraph EDITED.' },+ })++ // Returns the full notebook from the server (already includes new content + bumped version).+ expect(result).toEqual(updatedNotebook)+ expect(state.saveCalls).toHaveLength(1)+ expect(state.saveCalls[0]!.body.version).toBe(7)+ expect(JSON.stringify(state.saveCalls[0]!.body.content)).toContain('First paragraph EDITED.')+ })++ it('emits a step trimmed to the changed block, not a full-doc replace', async () => {+ // Position math for `sampleDoc` (each open/close token is one position):+ // heading "Sample Notebook" (15 text chars + 2 wrap) → 17 positions [0, 17)+ // paragraph "First paragraph." (16 text chars + 2 wrap) → 18 positions [17, 35)+ // paragraph "Second paragraph." (17 text chars + 2 wrap) → 19 positions [35, 54)+ // ph-recording atom → 1 position [54, 55)+ // ⇒ doc.content.size = 55+ //+ // Editing "First paragraph." → "First paragraph EDITED." only changes+ // the second top-level block. The trimmed step replaces just that block's+ // range [17, 35] with one new paragraph, instead of overwriting [0, 55]+ const updatedNotebook = {+ short_id: 'aBcD1234',+ content: sampleDoc,+ version: 8,+ title: 'Original',+ }+ const state: MockState = {+ notebookContent: sampleDoc,+ version: 7,+ saveCalls: [],+ getCalls: 0,+ saveResponses: [{ ok: true, body: updatedNotebook }],+ }+ const context = createMockContext(state)++ await editHandler(context, {+ short_id: 'aBcD1234',+ old_value: { type: 'text', text: 'First paragraph.' },+ new_value: { type: 'text', text: 'First paragraph EDITED.' },+ })++ const steps = state.saveCalls[0]!.body.steps as Array<{+ stepType: string+ from: number+ to: number+ slice?: { content: Array<{ type: string; content?: Array<{ type: string; text?: string }> }> }+ }>+ expect(steps).toHaveLength(1)+ expect(steps[0]!.stepType).toBe('replace')+ expect(steps[0]!.from).toBe(17)+ expect(steps[0]!.to).toBe(35)+ // Slice contains exactly one paragraph block with the edited text.+ const sliceBlocks = steps[0]!.slice?.content ?? []+ expect(sliceBlocks).toHaveLength(1)+ expect(sliceBlocks[0]!.type).toBe('paragraph')+ expect(sliceBlocks[0]!.content?.[0]).toMatchObject({ type: 'text', text: 'First paragraph EDITED.' })+ })++ it('matches by deep equality regardless of key order in the agent input', async () => {+ const updatedNotebook = {+ short_id: 'aBcD1234',+ content: sampleDoc,+ version: 8,+ title: 'Original',+ }+ const state: MockState = {+ notebookContent: sampleDoc,+ version: 7,+ saveCalls: [],+ getCalls: 0,+ saveResponses: [{ ok: true, body: updatedNotebook }],+ }+ const context = createMockContext(state)++ const result = await editHandler(context, {+ short_id: 'aBcD1234',+ // Reverse key order from how the doc stores it (`type` then `text`):+ old_value: { text: 'First paragraph.', type: 'text' },+ new_value: { type: 'text', text: 'First paragraph EDITED.' },+ })++ expect(result).toEqual(updatedNotebook)+ expect(JSON.stringify(state.saveCalls[0]!.body.content)).toContain('First paragraph EDITED.')+ })++ it('throws not-found error when old_value matches no subtree', async () => {+ const state: MockState = {+ notebookContent: sampleDoc,+ version: 7,+ saveCalls: [],+ getCalls: 0,+ saveResponses: [],+ }+ const context = createMockContext(state)+ await expect(+ editHandler(context, {+ short_id: 'aBcD1234',+ old_value: { type: 'text', text: 'This text does not exist anywhere' },+ new_value: { type: 'text', text: 'replacement' },+ })+ ).rejects.toThrow(/old_value was not found/)+ expect(state.saveCalls).toHaveLength(0)+ })++ it('throws ambiguous error when old_value matches more than one subtree without replace_all', async () => {+ const dupDoc = {+ type: 'doc',+ content: [+ { type: 'paragraph', content: [{ type: 'text', text: 'duplicate' }] },+ { type: 'paragraph', content: [{ type: 'text', text: 'duplicate' }] },+ ],+ }+ const state: MockState = {+ notebookContent: dupDoc as unknown as typeof sampleDoc,+ version: 7,+ saveCalls: [],+ getCalls: 0,+ saveResponses: [],+ }+ const context = createMockContext(state)+ await expect(+ editHandler(context, {+ short_id: 'aBcD1234',+ old_value: { type: 'text', text: 'duplicate' },+ new_value: { type: 'text', text: 'unique' },+ })+ ).rejects.toThrow(/matches 2 places/)+ expect(state.saveCalls).toHaveLength(0)+ })++ it('replaces every matching subtree when replace_all is true', async () => {+ const dupDoc = {+ type: 'doc',+ content: [+ { type: 'paragraph', content: [{ type: 'text', text: 'duplicate' }] },+ { type: 'paragraph', content: [{ type: 'text', text: 'duplicate' }] },+ ],+ }+ const updated = { short_id: 'aBcD1234', content: dupDoc, version: 8, title: 'x' }+ const state: MockState = {+ notebookContent: dupDoc as unknown as typeof sampleDoc,+ version: 7,+ saveCalls: [],+ getCalls: 0,+ saveResponses: [{ ok: true, body: updated }],+ }+ const context = createMockContext(state)+ const result = await editHandler(context, {+ short_id: 'aBcD1234',+ old_value: { type: 'text', text: 'duplicate' },+ new_value: { type: 'text', text: 'unique' },+ replace_all: true,+ })+ expect(result).toEqual(updated)+ expect(JSON.stringify(state.saveCalls[0]!.body.content)).toContain('"text":"unique"')+ expect(JSON.stringify(state.saveCalls[0]!.body.content)).not.toContain('"text":"duplicate"')+ })++ it('lets server errors (e.g. 409 conflict) propagate verbatim for handleToolError to format', async () => {+ // The Django collab/save handler returns a 409 body that already+ // contains the latest version + the rebased steps the agent needs to+ // retry. We rely on PostHogApiError carrying status + body through to+ // handleToolError, which surfaces them to the agent — no bespoke+ // refetch / re-render in the tool itself.+ const conflictBody = JSON.stringify({+ code: 'conflict',+ version: 8,+ steps: [{ stepType: 'replace', from: 0, to: 5 }],+ client_ids: ['someone-else'],+ })+ const state: MockState = {+ notebookContent: sampleDoc,+ version: 7,+ saveCalls: [],+ getCalls: 0,+ saveResponses: [+ {+ ok: false,+ error: new PostHogApiError({+ status: 409,+ statusText: 'Conflict',+ body: conflictBody,+ url: 'http://test/api/projects/42/notebooks/aBcD1234/collab/save/',+ method: 'POST',+ }),+ },+ ],+ }+ const context = createMockContext(state)++ await expect(+ editHandler(context, {+ short_id: 'aBcD1234',+ old_value: { type: 'text', text: 'First paragraph.' },+ new_value: { type: 'text', text: 'First paragraph EDITED.' },+ })+ ).rejects.toMatchObject({+ name: 'PostHogApiError',+ status: 409,+ body: conflictBody,+ })+ // POST attempted exactly once — no client-side retry, no extra GET.+ expect(state.saveCalls).toHaveLength(1)+ expect(state.getCalls).toBe(1)+ })++ it('throws when the notebook has no editable content', async () => {+ const state: MockState = {+ notebookContent: null,+ version: 7,+ saveCalls: [],+ getCalls: 0,+ saveResponses: [],+ }+ const context = createMockContext(state)+ await expect(+ editHandler(context, {+ short_id: 'aBcD1234',+ old_value: { type: 'text', text: 'a' },+ new_value: { type: 'text', text: 'b' },+ })+ ).rejects.toThrow(/no editable content/)+ })+})diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 2dd377c1c844..f162d1785210 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -671,6 +671,19 @@ describe('Tool Filtering - Feature Flags', () => {expect(withFlags).toEqual(withoutFlags)})+ it('notebooks-collaboration flag flips the active notebook edit tool', () => {+ // When the flag is OFF, the legacy non-streaming PATCH tool is exposed.+ // When the flag is ON, it's hidden and the streaming collab edit tool+ // takes its place. The model never sees both at once.+ const off = getToolsForFeatures({ featureFlags: { 'notebooks-collaboration': false } })+ expect(off).toContain('notebooks-partial-update')+ expect(off).not.toContain('notebook-edit')++ const on = getToolsForFeatures({ featureFlags: { 'notebooks-collaboration': true } })+ expect(on).toContain('notebook-edit')+ expect(on).not.toContain('notebooks-partial-update')+ })+it('getRequiredFeatureFlags should return flags used by current definitions', () => {const flags = getRequiredFeatureFlags()// Includes the gating flag for agent-feedback alongside the other gated tools.@@ -683,10 +696,11 @@ describe('Tool Filtering - Feature Flags', () => {'mcp-feedback-tool','user-interviews','customer-analytics-csp',+ 'notebooks-collaboration','replay-vision',]))- expect(flags).toHaveLength(8)+ expect(flags).toHaveLength(9)})// Test the filtering logic with a direct unit test approach using