Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(mcp): safely delete empty notebook trees (#509)

tianma-if53869bd3f8e2
diff --git a/apps/api/src/mcp-notebook-delete.test.mjs b/apps/api/src/mcp-notebook-delete.test.mjs
new file mode 100644
index 00000000..6db0dc37
--- /dev/null
+++ b/apps/api/src/mcp-notebook-delete.test.mjs
@@ -0,0 +1,124 @@
+import { describe, expect, test } from "bun:test";
+import { Database } from "bun:sqlite";
+import { globSync, readFileSync } from "node:fs";
+import { callMcpTool } from "./index.ts";
+import { createSelfHostedStorageAdapter } from "./self-hosted-storage-adapter.ts";
+import { MCP_TOOLS } from "./mcp-tools.ts";
+
+const fixture = () => {
+ const sqlite = new Database(":memory:");
+ for (const path of globSync("migrations/*.sql").sort()) sqlite.exec(readFileSync(path, "utf8"));
+ sqlite.exec(`
+ INSERT INTO workspaces (id, name) VALUES ('ws_delete', 'Delete test'), ('ws_other', 'Other');
+ INSERT INTO notebooks (id, workspace_id, parent_id, name) VALUES
+ ('parent', 'ws_delete', NULL, 'Imports'), ('child', 'ws_delete', 'parent', 'Flomo'),
+ ('other', 'ws_other', NULL, 'Other'), ('ws_delete_inbox', 'ws_delete', NULL, 'Renamed inbox');
+ UPDATE notebooks SET slug = 'inbox' WHERE id = 'ws_delete_inbox';
+ `);
+ const auth = { kind: "agent", actorType: "agent", actorId: "tok_delete", username: "agent",
+ displayName: null, scopes: ["read:notebooks", "write:notebooks"], workspaceId: "ws_delete", role: "member" };
+ const db = createSelfHostedStorageAdapter(sqlite, "/tmp/edgeever-mcp-delete-unused").db;
+ const context = { env: { storage: { db } }, get: key => key === "auth" ? auth : undefined };
+ const call = args => callMcpTool(context, auth, "delete_notebook", args);
+ return { sqlite, auth, db, context, call };
+};
+
+const auditCount = sqlite => sqlite.query("SELECT COUNT(*) AS count FROM audit_events WHERE action = 'notebook.delete'").get().count;
+const insertNote = sqlite => sqlite.exec("INSERT INTO memos (id, workspace_id, notebook_id, title) VALUES ('note', 'ws_delete', 'child', 'Keep')");
+
+describe("MCP empty notebook deletion", () => {
+ test("advertises a destructive, idempotent tool with explicit ID and preview", () => {
+ const tool = MCP_TOOLS.find(tool => tool.name === "delete_notebook");
+ expect(tool.annotations).toMatchObject({ readOnlyHint: false, destructiveHint: true, idempotentHint: true });
+ expect(tool.inputSchema.required).toEqual(["notebookId"]);
+ expect(tool.inputSchema.properties.dryRun.type).toBe("boolean");
+ });
+
+ test("resolves paths, previews without writes, deletes the empty subtree and retries safely", async () => {
+ const f = fixture();
+ try {
+ const resolved = await callMcpTool(f.context, f.auth, "resolve_notebook_path", { path: "Imports" });
+ const args = { notebookId: resolved.notebook.id };
+ expect(await f.call({ ...args, dryRun: true })).toMatchObject({ dryRun: true, deleted: false, notebookCount: 2 });
+ expect(auditCount(f.sqlite)).toBe(0);
+ expect(f.sqlite.query("SELECT is_deleted FROM notebooks WHERE id = 'parent'").get().is_deleted).toBe(0);
+ const result = await f.call(args);
+ expect(result).toMatchObject({ deleted: true, dryRun: false, notebookCount: 2 });
+ expect(result.notebookIds.sort()).toEqual(["child", "parent"]);
+ expect(f.sqlite.query("SELECT id FROM notebooks WHERE workspace_id = 'ws_delete' AND is_deleted = 1 ORDER BY id").all()).toEqual([{ id: "child" }, { id: "parent" }]);
+ expect(auditCount(f.sqlite)).toBe(1);
+ expect(await f.call(args)).toMatchObject({ deleted: true, notebookCount: 0 });
+ expect(auditCount(f.sqlite)).toBe(1);
+ } finally { f.sqlite.close(); }
+ });
+
+ test("rejects notes anywhere in the subtree for preview and execution, but preserves trashed notes", async () => {
+ const f = fixture();
+ try {
+ insertNote(f.sqlite);
+ for (const dryRun of [true, false]) await expect(f.call({ notebookId: "parent", dryRun })).rejects.toMatchObject({ code: "notebook_not_empty" });
+ expect(auditCount(f.sqlite)).toBe(0);
+ f.sqlite.exec("UPDATE memos SET is_deleted = 1 WHERE id = 'note'");
+ await f.call({ notebookId: "parent" });
+ expect(f.sqlite.query("SELECT notebook_id, is_deleted FROM memos WHERE id = 'note'").get()).toEqual({ notebook_id: "child", is_deleted: 1 });
+ } finally { f.sqlite.close(); }
+ });
+
+ test("protects inboxes, workspace isolation and write permissions", async () => {
+ const f = fixture();
+ try {
+ for (const notebookId of ["other", "missing"]) await expect(f.call({ notebookId })).rejects.toMatchObject({ code: "not_found" });
+ await expect(f.call({ notebookId: "ws_delete_inbox" })).rejects.toMatchObject({ code: "bad_request" });
+ f.auth.scopes = ["read:notebooks"];
+ for (const dryRun of [true, false]) await expect(f.call({ notebookId: "parent", dryRun })).rejects.toMatchObject({ code: "forbidden" });
+ expect(auditCount(f.sqlite)).toBe(0);
+ } finally { f.sqlite.close(); }
+ });
+
+ test("does not guess an ambiguous path or accept a truthy preview value", async () => {
+ const f = fixture();
+ try {
+ f.sqlite.exec("INSERT INTO notebooks (id, workspace_id, name) VALUES ('duplicate', 'ws_delete', 'Imports')");
+ expect(await callMcpTool(f.context, f.auth, "resolve_notebook_path", { path: "Imports" })).toMatchObject({ resolved: false, reason: "ambiguous" });
+ await expect(f.call({ notebookId: "parent", dryRun: "true" })).rejects.toMatchObject({ code: "invalid_params" });
+ await expect(f.call({ notebookId: "parent", recursive: true })).rejects.toMatchObject({ code: "invalid_params" });
+ await expect(f.call({ notebookId: "" })).rejects.toMatchObject({ code: "invalid_params" });
+ expect(auditCount(f.sqlite)).toBe(0);
+ } finally { f.sqlite.close(); }
+ });
+
+ test.each(["note", "child", "move", "delete"])("rejects a concurrent %s change without partial deletion or audit", async change => {
+ const f = fixture();
+ try {
+ f.context.env.storage.db = { prepare: sql => f.db.prepare(sql), batch: async statements => {
+ if (change === "note") insertNote(f.sqlite);
+ if (change === "child") f.sqlite.exec("INSERT INTO notebooks (id, workspace_id, parent_id, name) VALUES ('new', 'ws_delete', 'child', 'New')");
+ if (change === "move") f.sqlite.exec("UPDATE notebooks SET parent_id = NULL WHERE id = 'child'");
+ if (change === "delete") f.sqlite.exec("UPDATE notebooks SET is_deleted = 1 WHERE id = 'child'");
+ return f.db.batch(statements);
+ } };
+ await expect(f.call({ notebookId: "parent" })).rejects.toMatchObject({ code: "notebook_changed" });
+ expect(f.sqlite.query("SELECT is_deleted FROM notebooks WHERE id = 'parent'").get().is_deleted).toBe(0);
+ expect(auditCount(f.sqlite)).toBe(0);
+ } finally { f.sqlite.close(); }
+ });
+
+ test("deletes a large empty subtree without exceeding SQL binding limits", async () => {
+ const f = fixture();
+ try {
+ const insert = f.sqlite.query("INSERT INTO notebooks (id, workspace_id, parent_id, name) VALUES (?, 'ws_delete', 'child', ?)");
+ for (let i = 0; i < 150; i++) insert.run(`leaf_${i}`, `Leaf ${i}`);
+ expect(await f.call({ notebookId: "parent" })).toMatchObject({ notebookCount: 152, deleted: true });
+ expect(auditCount(f.sqlite)).toBe(1);
+ } finally { f.sqlite.close(); }
+ });
+
+ test("rolls back the deletion if writing the audit fails", async () => {
+ const f = fixture();
+ try {
+ f.sqlite.exec("CREATE TRIGGER reject_audit BEFORE INSERT ON audit_events BEGIN SELECT RAISE(ABORT, 'audit unavailable'); END");
+ await expect(f.call({ notebookId: "parent" })).rejects.toThrow("audit unavailable");
+ expect(f.sqlite.query("SELECT COUNT(*) AS count FROM notebooks WHERE workspace_id = 'ws_delete' AND is_deleted = 1").get().count).toBe(0);
+ } finally { f.sqlite.close(); }
+ });
+});
diff --git a/apps/api/src/mcp-tool-service.ts b/apps/api/src/mcp-tool-service.ts
index 79265468..ea242c23 100644
--- a/apps/api/src/mcp-tool-service.ts
+++ b/apps/api/src/mcp-tool-service.ts
@@ -71,6 +71,7 @@ import {
} from "./memo-revision-service";
import {
createNotebookRecord,
+ deleteNotebookTree,
findNotebooks,
getNotebook,
listNotebooks,
@@ -849,6 +850,18 @@ export const callMcpTool = async (
return { notebook };
}
+ case "delete_notebook": {
+ assertScope(auth, "write:notebooks");
+ if (Object.keys(args).some((key) => key !== "notebookId" && key !== "dryRun")) {
+ throw new AppError("invalid_params", "Only notebookId and dryRun are supported; recursive note deletion is not available", 400);
+ }
+ if (args.dryRun !== undefined && typeof args.dryRun !== "boolean") {
+ throw new AppError("invalid_params", "dryRun must be a boolean", 400);
+ }
+ return deleteNotebookTree(c.env.storage.db, auth.workspaceId,
+ getRequiredString(args.notebookId, "notebookId"), getAuditActor(c),
+ { dryRun: args.dryRun === true, guardConcurrentChanges: true });
+ }
case "create_notebook": {
assertScope(auth, "write:notebooks");
const actor = getAuditActor(c);
diff --git a/apps/api/src/mcp-tools.ts b/apps/api/src/mcp-tools.ts
index 5ad9b131..d0c6d1ce 100644
--- a/apps/api/src/mcp-tools.ts
+++ b/apps/api/src/mcp-tools.ts
@@ -697,6 +697,19 @@ const MCP_TOOL_DEFINITIONS = [
},
},
},
+ {
+ name: "delete_notebook",
+ description: "Soft-delete a notebook and all its empty descendants. Refuses deletion if any active note exists in the subtree; never deletes notes. The default inbox is protected. Resolve paths with resolve_notebook_path first and use the exact notebookId. Use dryRun to preview affected notebook IDs without changes. Concurrent changes require a fresh preview and retry.",
+ inputSchema: {
+ type: "object",
+ required: ["notebookId"],
+ additionalProperties: false,
+ properties: {
+ notebookId: { type: "string", minLength: 1, description: "Exact EdgeEver notebook ID obtained from a unique path resolution or lookup." },
+ dryRun: { type: "boolean", description: "Preview the empty subtree without deleting it." },
+ },
+ },
+ },
{
name: "create_notebook",
description: "Create a notebook at the root or under another notebook.",
@@ -1002,6 +1015,7 @@ const NON_DESTRUCTIVE_MCP_TOOLS = new Set([
"restore_default_ai_instructions",
]);
const IDEMPOTENT_MCP_TOOLS = new Set([
+ "delete_notebook",
"restore_memos",
"move_memos",
"add_tags_to_memos",
diff --git a/apps/api/src/notebook-service.ts b/apps/api/src/notebook-service.ts
index b6e4729c..a0931b55 100644
--- a/apps/api/src/notebook-service.ts
+++ b/apps/api/src/notebook-service.ts
@@ -263,11 +263,11 @@ const listActiveNotebookTree = async (db: DatabaseAdapter, workspaceId: string,
INNER JOIN tree t ON n.parent_id = t.id
WHERE n.workspace_id = ?
)
- SELECT n.id, n.slug
+ SELECT n.id, n.slug, n.parent_id
FROM notebooks n
INNER JOIN tree t ON t.id = n.id
WHERE n.workspace_id = ? AND n.is_deleted = 0`
- ).bind(workspaceId, id, workspaceId, workspaceId).all<{ id: string; slug: string | null }>();
+ ).bind(workspaceId, id, workspaceId, workspaceId).all<{ id: string; slug: string | null; parent_id: string | null }>();
return rows.results;
};
@@ -284,23 +284,28 @@ const countActiveMemosInNotebooks = async (db: DatabaseAdapter, workspaceId: str
return total;
};
-export const deleteNotebookRecord = async (
+export const deleteNotebookTree = async (
db: DatabaseAdapter,
workspaceId: string,
id: string,
- actor: AuditActor
+ actor: AuditActor,
+ options: { dryRun?: boolean; guardConcurrentChanges?: boolean } = {},
) => {
+ const result = (notebookIds: string[]) => ({
+ notebookId: id, notebookIds, notebookCount: notebookIds.length,
+ dryRun: options.dryRun === true, deleted: options.dryRun !== true,
+ });
const current = await db.prepare(
`SELECT id, slug, is_deleted FROM notebooks WHERE id = ? AND workspace_id = ?`
).bind(id, workspaceId).first<{ id: string; slug: string | null; is_deleted: number }>();
if (!current) throw new AppError("not_found", "Notebook not found", 404);
if (isInboxNotebook(current, workspaceId)) {
- if (current.is_deleted) return;
+ if (current.is_deleted) return result([]);
throw new AppError("bad_request", "等待分类不能删除。", 400);
}
const tree = await listActiveNotebookTree(db, workspaceId, id);
- if (tree.length === 0) return;
+ if (tree.length === 0) return result([]);
if (tree.some((notebook) => isInboxNotebook(notebook, workspaceId))) {
throw new AppError("bad_request", "等待分类不能删除。", 400);
}
@@ -316,8 +321,53 @@ export const deleteNotebookRecord = async (
);
}
+ if (options.dryRun) return result(notebookIds);
+
const now = isoNow();
const inboxId = workspaceInboxId(workspaceId);
+ if (options.guardConcurrentChanges) {
+ // One guarded UPDATE prevents a note inserted after the emptiness check
+ // from being hidden. Require the same active subtree, including parent
+ // links, so concurrent moves/creates/deletes require a fresh attempt.
+ const serializedSnapshot = JSON.stringify(tree.map(({ id, parent_id }) => ({ id, parent_id })));
+ const update = db.prepare(`
+ WITH RECURSIVE tree(id) AS (
+ SELECT id FROM notebooks WHERE workspace_id = ? AND id = ?
+ UNION
+ SELECT n.id FROM notebooks n JOIN tree t ON n.parent_id = t.id WHERE n.workspace_id = ?
+ ), active_tree AS MATERIALIZED (
+ SELECT n.* FROM notebooks n JOIN tree t ON n.id = t.id
+ WHERE n.workspace_id = ? AND n.is_deleted = 0
+ ), expected AS (
+ SELECT json_extract(value, '$.id') AS id, json_extract(value, '$.parent_id') AS parent_id
+ FROM json_each(?)
+ )
+ UPDATE notebooks SET is_deleted = 1, deleted_at = ?, updated_at = ?
+ WHERE workspace_id = ? AND is_deleted = 0 AND id IN (SELECT id FROM active_tree)
+ AND (SELECT COUNT(*) FROM active_tree) = ?
+ AND NOT EXISTS (
+ SELECT 1 FROM active_tree n LEFT JOIN expected e ON e.id = n.id
+ WHERE e.id IS NULL OR n.parent_id IS NOT e.parent_id
+ )
+ AND NOT EXISTS (SELECT 1 FROM active_tree WHERE slug = 'inbox' OR id = 'nb_inbox' OR id = ?)
+ AND NOT EXISTS (
+ SELECT 1 FROM memos WHERE workspace_id = ? AND is_deleted = 0
+ AND notebook_id IN (SELECT id FROM active_tree)
+ )
+ `).bind(workspaceId, id, workspaceId, workspaceId, serializedSnapshot,
+ now, now, workspaceId, notebookIds.length, inboxId, workspaceId);
+ const auditDelete = db.prepare(`
+ INSERT INTO audit_events (id, actor_type, actor_id, action, entity_type, entity_id, metadata_json, created_at)
+ SELECT ?, ?, ?, 'notebook.delete', 'notebook', ?, ?, ? WHERE changes() = ?
+ `).bind(createId("audit"), actor.actorType, actor.actorId, id, JSON.stringify({ notebookIds }), now, notebookIds.length);
+ const [, audited] = await db.batch([update, auditDelete]);
+ // Adapter UPDATE metadata may include sync-trigger writes. The conditional
+ // audit uses SQLite changes(), which counts only the notebook rows.
+ if (!(Number(audited?.meta.changes) > 0)) {
+ throw new AppError("notebook_changed", "Notebook contents or hierarchy changed. Preview again before retrying deletion.", 409);
+ }
+ return result(notebookIds);
+ }
const statements = chunkValues(notebookIds, NOTEBOOK_DELETE_ID_CHUNK).map((chunk) => {
const placeholders = chunk.map(() => "?").join(", ");
return db.prepare(
@@ -331,6 +381,14 @@ export const deleteNotebookRecord = async (
notebookIds,
}));
await db.batch(statements);
+ return result(notebookIds);
+};
+
+// Preserve the existing REST deletion contract and mechanism.
+export const deleteNotebookRecord = async (
+ db: DatabaseAdapter, workspaceId: string, id: string, actor: AuditActor,
+) => {
+ await deleteNotebookTree(db, workspaceId, id, actor);
};
export const restoreNotebookRecord = async (