@abraca/mcp 2.88.0 → 2.91.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tools/tree.ts DELETED
@@ -1,682 +0,0 @@
1
- /**
2
- * Document tree tools — operate on the root Y.Doc's "doc-tree" Y.Map.
3
- */
4
- import * as Y from 'yjs'
5
- import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
6
- import { z } from 'zod'
7
- import type { AbracadabraMCPServer } from '../server.ts'
8
- import type { SchemaBundleValidator } from '../schema/validator.ts'
9
- import {
10
- makeEntryMap,
11
- normalizeRootId as normalizeRootIdImpl,
12
- patchEntry,
13
- readEntries,
14
- toPlain,
15
- PAGE_TYPES,
16
- TYPE_ALIASES,
17
- resolvePageType,
18
- } from '@abraca/dabra'
19
- import type { TreeEntry, PageMeta } from '@abraca/dabra'
20
-
21
- // `readEntries` now lives in @abraca/dabra (provider DocUtils). Re-exported for
22
- // any in-package consumer that imported it from here.
23
- export { readEntries }
24
-
25
- /**
26
- * Normalize a document ID so the hub/root doc ID is treated as the tree root
27
- * (null). This lets callers pass the hub doc_id from list_spaces as
28
- * parentId/rootId and get the expected root-level results instead of an empty
29
- * set. Thin adapter over `@abraca/dabra`'s `normalizeRootId`.
30
- */
31
- function normalizeRootId(id: string | null | undefined, server: AbracadabraMCPServer): string | null {
32
- return normalizeRootIdImpl(id, server.rootDocId)
33
- }
34
-
35
- function childrenOf(entries: TreeEntry[], parentId: string | null): TreeEntry[] {
36
- return entries
37
- .filter(e => e.parentId === parentId)
38
- .sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
39
- }
40
-
41
- function descendantsOf(entries: TreeEntry[], id: string | null): TreeEntry[] {
42
- const result: TreeEntry[] = []
43
- const visited = new Set<string>()
44
- function collect(pid: string) {
45
- if (visited.has(pid)) return
46
- visited.add(pid)
47
- for (const child of childrenOf(entries, pid)) {
48
- result.push(child)
49
- collect(child.id)
50
- }
51
- }
52
- collect(id)
53
- return result
54
- }
55
-
56
- /**
57
- * Evaluate one `where` predicate value against a doc's actual value. The
58
- * predicate is a small string DSL so agents can filter on meta without a
59
- * structured query language:
60
- * - `>=N` `<=N` `>N` `<N` → numeric comparison (value coerced to number)
61
- * - `contains:X` → array membership OR string substring
62
- * - `exists` / `!exists` → presence / absence (null counts as absent)
63
- * - `=X` or bare `X` → loose equality (string-coerced)
64
- */
65
- export function matchPredicate(actual: unknown, pred: string): boolean {
66
- const p = pred.trim()
67
- if (p === 'exists') return actual !== undefined && actual !== null
68
- if (p === '!exists') return actual === undefined || actual === null
69
- const cmp = p.match(/^(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/)
70
- if (cmp) {
71
- const n = Number(actual)
72
- if (Number.isNaN(n)) return false
73
- const rhs = Number(cmp[2])
74
- switch (cmp[1]) {
75
- case '>=': return n >= rhs
76
- case '<=': return n <= rhs
77
- case '>': return n > rhs
78
- case '<': return n < rhs
79
- }
80
- }
81
- if (p.startsWith('contains:')) {
82
- const needle = p.slice('contains:'.length)
83
- if (Array.isArray(actual)) return actual.map(String).includes(needle)
84
- if (typeof actual === 'string') return actual.toLowerCase().includes(needle.toLowerCase())
85
- return false
86
- }
87
- const want = p.startsWith('=') ? p.slice(1) : p
88
- return String(actual) === want
89
- }
90
-
91
- /** True when an entry satisfies EVERY predicate in `where`. The special key
92
- * `type` matches the entry's page type; every other key matches `entry.meta[key]`. */
93
- export function matchesWhere(entry: TreeEntry, where: Record<string, string>): boolean {
94
- for (const [key, pred] of Object.entries(where)) {
95
- const actual = key === 'type' ? entry.type : (entry.meta as Record<string, unknown> | undefined)?.[key]
96
- if (!matchPredicate(actual, pred)) return false
97
- }
98
- return true
99
- }
100
-
101
- export function buildTree(entries: TreeEntry[], rootId: string | null, maxDepth: number, currentDepth = 0, visited = new Set<string>()): any[] {
102
- if (maxDepth >= 0 && currentDepth >= maxDepth) return []
103
- const children = childrenOf(entries, rootId)
104
- return children.filter(e => !visited.has(e.id)).map(entry => {
105
- const next = new Set(visited)
106
- next.add(entry.id)
107
- return {
108
- id: entry.id,
109
- label: entry.label,
110
- type: entry.type,
111
- meta: entry.meta,
112
- order: entry.order,
113
- children: buildTree(entries, entry.id, maxDepth, currentDepth + 1, next),
114
- }
115
- })
116
- }
117
-
118
- export function registerTreeTools(
119
- mcp: McpServer,
120
- server: AbracadabraMCPServer,
121
- validator: SchemaBundleValidator | null = null,
122
- ) {
123
- mcp.tool(
124
- 'list_documents',
125
- 'List direct children of a document (defaults to root). Returns id, label, type, meta, order. NOTE: Only returns ONE level. Use find_document to search by name across the full tree, or get_document_tree to see the complete hierarchy.',
126
- { parentId: z.string().optional().describe('Parent document ID. Omit for root-level documents.') },
127
- async ({ parentId }) => {
128
- server.setAutoStatus('reading')
129
- server.setActiveToolCall({ name: 'list_documents' })
130
- await server.ensureSpaceActive(parentId)
131
- const treeMap = server.getTreeMap()
132
- if (!treeMap) {
133
- return { content: [{ type: 'text', text: 'Not connected' }] }
134
- }
135
-
136
- const targetId = normalizeRootId(parentId, server)
137
- const entries = readEntries(treeMap, server.rootDocId)
138
- const children = childrenOf(entries, targetId)
139
-
140
- return {
141
- content: [{
142
- type: 'text',
143
- text: JSON.stringify(children, null, 2),
144
- }],
145
- }
146
- }
147
- )
148
-
149
- mcp.tool(
150
- 'get_document_tree',
151
- 'Get the full document tree as nested JSON. Call this FIRST when exploring a space or looking for documents — it shows the complete hierarchy including all nested documents. Use rootId to scope to a subtree.',
152
- {
153
- rootId: z.string().optional().describe('Root document ID to start from. Omit for the entire tree.'),
154
- depth: z.number().optional().describe('Maximum depth to traverse. Default 3. Use -1 for unlimited.'),
155
- },
156
- async ({ rootId, depth }) => {
157
- server.setAutoStatus('reading')
158
- server.setActiveToolCall({ name: 'get_document_tree' })
159
- await server.ensureSpaceActive(rootId)
160
- const treeMap = server.getTreeMap()
161
- if (!treeMap) {
162
- return { content: [{ type: 'text', text: 'Not connected' }] }
163
- }
164
-
165
- const targetId = normalizeRootId(rootId, server)
166
- const maxDepth = depth ?? 3
167
- const entries = readEntries(treeMap, server.rootDocId)
168
- const tree = buildTree(entries, targetId, maxDepth)
169
-
170
- return {
171
- content: [{
172
- type: 'text',
173
- text: JSON.stringify(tree, null, 2),
174
- }],
175
- }
176
- }
177
- )
178
-
179
- mcp.tool(
180
- 'find_document',
181
- 'Search for documents across the tree by name and/or metadata. Returns matching documents with their full ancestor path. Use this when looking for a document and you don\'t know where it is. At least one of `query` or `where` is required. `where` filters on metadata — e.g. find every high-priority card or every doc tagged "bug" without knowing labels.',
182
- {
183
- query: z.string().optional().describe('Case-insensitive substring match against document labels. Optional when `where` is given.'),
184
- where: z.record(z.string(), z.string()).optional().describe('Metadata predicates, ALL of which must match. Key is a meta field (or the special key "type" for page type); value is a tiny predicate: ">=3" / "<=1" (numeric, e.g. priority), "contains:bug" (array membership or string substring, e.g. tags), "exists" / "!exists", or a bare/"=value" for equality. Example: {"priority":">=3","type":"kanban"}.'),
185
- rootId: z.string().optional().describe('Restrict search to descendants of this document. Omit to search the entire tree.'),
186
- },
187
- async ({ query, where, rootId }) => {
188
- const label = query ?? (where ? Object.keys(where).join(',') : 'find')
189
- server.setAutoStatus('searching')
190
- server.setActiveToolCall({ name: 'find_document', target: label })
191
-
192
- if (!query && (!where || Object.keys(where).length === 0)) {
193
- return {
194
- content: [{ type: 'text', text: 'find_document needs at least one of `query` (label substring) or `where` (metadata predicates).' }],
195
- isError: true,
196
- }
197
- }
198
-
199
- await server.ensureSpaceActive(rootId)
200
- const treeMap = server.getTreeMap()
201
- if (!treeMap) {
202
- return { content: [{ type: 'text', text: 'Not connected' }] }
203
- }
204
-
205
- const entries = readEntries(treeMap, server.rootDocId)
206
- const lowerQuery = query?.toLowerCase()
207
-
208
- // If rootId specified, restrict to descendants only
209
- const normalizedRoot = normalizeRootId(rootId, server)
210
- const searchSet = normalizedRoot ? descendantsOf(entries, normalizedRoot) : entries
211
-
212
- // Find matches — label substring (when `query` given) AND every `where`
213
- // predicate (when given). Both are optional individually but the tool
214
- // requires at least one (guarded above).
215
- const matches = searchSet.filter(e => {
216
- if (lowerQuery !== undefined && !e.label.toLowerCase().includes(lowerQuery)) return false
217
- if (where && !matchesWhere(e, where)) return false
218
- return true
219
- })
220
-
221
- // Build ancestor path for each match
222
- const byId = new Map(entries.map(e => [e.id, e]))
223
- const results = matches.map(entry => {
224
- const path: string[] = []
225
- let current = entry.parentId
226
- const visited = new Set<string>()
227
- while (current && !visited.has(current)) {
228
- visited.add(current)
229
- const parent = byId.get(current)
230
- if (!parent) break
231
- path.unshift(parent.label)
232
- current = parent.parentId
233
- }
234
- return {
235
- id: entry.id,
236
- label: entry.label,
237
- type: entry.type,
238
- meta: entry.meta,
239
- path,
240
- }
241
- })
242
-
243
- if (results.length === 0) {
244
- const crit = [query ? `label~"${query}"` : null, where ? `where=${JSON.stringify(where)}` : null].filter(Boolean).join(' AND ')
245
- return {
246
- content: [{ type: 'text', text: `No documents found matching ${crit}. Try get_document_tree to see the full hierarchy.` }],
247
- }
248
- }
249
-
250
- return {
251
- content: [{ type: 'text', text: JSON.stringify(results, null, 2) }],
252
- }
253
- }
254
- )
255
-
256
- mcp.tool(
257
- 'query_documents',
258
- 'Find documents by structural predicate across every space the user can read (POST /docs/query, v1). v1 filters on type (kanban, doc, calendar, etc.), parent doc, and label substring. Meta-field predicates (priority >= 3, dateStart in range) arrive in v2. Use this instead of find_document when you want to scope by page-type rather than label, or list every doc of a given kind across the server.',
259
- {
260
- type: z.string().optional().describe('Match documents.kind exactly. Examples: "kanban", "doc", "calendar", "table", "gallery". Omit to range across kinds.'),
261
- parentId: z.string().optional().describe('Narrow to direct children of this doc.'),
262
- labelContains: z.string().optional().describe('Case-insensitive substring match on the document label.'),
263
- limit: z.number().optional().describe('Maximum results returned. Default 50; hard cap 500 server-side.'),
264
- },
265
- async ({ type, parentId, labelContains, limit }) => {
266
- server.setAutoStatus('searching')
267
- server.setActiveToolCall({ name: 'query_documents', target: type ?? labelContains ?? parentId ?? 'query' })
268
-
269
- if (type == null && parentId == null && labelContains == null) {
270
- return {
271
- content: [{
272
- type: 'text',
273
- text: 'At least one of `type`, `parentId`, or `labelContains` is required — the server refuses to scan the full document set. (Use list_documents for root-level listing, or find_document for full-tree label search.)',
274
- }],
275
- }
276
- }
277
-
278
- try {
279
- const docs = await server.client.queryDocs({ type, parentId, labelContains, limit })
280
- if (docs.length === 0) {
281
- return {
282
- content: [{
283
- type: 'text',
284
- text: `No documents matched (type=${type ?? '*'}, parentId=${parentId ?? '*'}, labelContains=${labelContains ?? '*'}). Try widening the predicate.`,
285
- }],
286
- }
287
- }
288
- return {
289
- content: [{ type: 'text', text: JSON.stringify(docs, null, 2) }],
290
- }
291
- } catch (err) {
292
- return {
293
- content: [{
294
- type: 'text',
295
- text: `query_documents failed: ${err instanceof Error ? err.message : String(err)}`,
296
- }],
297
- }
298
- }
299
- }
300
- )
301
-
302
- mcp.tool(
303
- 'create_document',
304
- 'Create a new document in the tree. Returns the new document ID.',
305
- {
306
- parentId: z.string().optional().describe('Parent document ID. Omit for top-level pages. Use a document ID for nested/child pages.'),
307
- label: z.string().describe('Display name / title for the document.'),
308
- type: z.string().optional().describe('Page type — sets how this document renders. Core types (always available): "doc" (rich text), "kanban" (columns → cards), "table" (columns → rows, positional), "calendar" (events with datetimeStart/End), "timeline" (epics → tasks with dateStart/End + taskProgress), "checklist" (tasks with checked/priority, unlimited nesting), "outline" (nested items, unlimited depth), "gallery" (visual grid with covers/ratings), "map" (markers/lines with geoLat/geoLng), "graph" (force-directed knowledge graph), "dashboard" (positioned widgets with deskX/deskY/deskMode), "slides" (slides → sub-slides with transitions), "chart" (bar/stacked bar/line/donut/treemap from data points or aggregation), "sheets" (spreadsheet with formulas and formatting), "overview" (space home — activity and stats), "call" (video call room, no children). Plugin types (require plugin enabled on the server): "spatial" (3D scene with spShape/spX/spY/spZ + universal color, plugin: spatial), "media" (audio/video player with playlists, plugin: media), "coder" (collaborative multi-file coding env with fileType/entry, plugin: coder). Alias: "desktop" → "dashboard". Omit to inherit parent view. Only set on the parent page, NEVER on child items.'),
309
- meta: z.record(z.string(), z.unknown()).optional().describe('Initial metadata (PageMeta fields: color as hex string, icon as Lucide kebab-case name like "star"/"code-2"/"users" — never emoji, dateStart, dateEnd, priority 0-4, tags array, etc). Omit icon entirely to use page type default.'),
310
- },
311
- async ({ parentId, label, type, meta }) => {
312
- server.setAutoStatus('creating')
313
- server.setActiveToolCall({ name: 'create_document', target: label })
314
-
315
- // Activate the space that owns `parentId` first, so the new doc lands in
316
- // the right space's tree instead of being orphaned into whatever space
317
- // happened to be active (the silent data-loss path).
318
- await server.ensureSpaceActive(parentId)
319
-
320
- const treeMap = server.getTreeMap()
321
- const rootDoc = server.rootDocument
322
- if (!treeMap || !rootDoc) {
323
- return { content: [{ type: 'text', text: 'Not connected' }] }
324
- }
325
-
326
- if (validator && type && meta) {
327
- const result = validator.validateMeta(type, meta)
328
- if (!result.ok) {
329
- const detail = result.errors.map((e) => `${e.path} ${e.message}`).join('; ')
330
- return {
331
- content: [{
332
- type: 'text',
333
- text: `Metadata validation failed for type "${type}": ${detail}`,
334
- }],
335
- isError: true,
336
- }
337
- }
338
- }
339
-
340
- const id = crypto.randomUUID()
341
- const normalizedParent = normalizeRootId(parentId, server)
342
- const now = Date.now()
343
-
344
- // Guard: never write under a parent that doesn't exist in the resolved
345
- // space's tree — that silently orphans the doc (it would be invisible in
346
- // the intended space forever). Refuse with actionable guidance instead.
347
- if (normalizedParent && !treeMap.has(normalizedParent)) {
348
- return {
349
- content: [{
350
- type: 'text',
351
- text: `Parent "${parentId}" was not found in any space the MCP can currently reach (active space: ${server.rootDocId}). Refusing to create — writing here would orphan the document. If the parent lives in another space, call switch_space to that space first, then retry.`,
352
- }],
353
- isError: true,
354
- }
355
- }
356
-
357
- // Register the SQL `documents` row BEFORE writing the Yjs tree entry.
358
- // The RBAC cascade seeds from `documents WHERE id=?`, so a doc with no
359
- // row can't walk up to inherit its parent's permissions — it falls to
360
- // the flat `[access].authenticated` floor and is missing from
361
- // `GET /docs` + FTS. `createChild` registers the row under the right
362
- // parent (the current space root when no explicit parent is given) so
363
- // permissions inherit. Doing it first means a failure here doesn't leave
364
- // a permission-orphaned Yjs ghost.
365
- const restParent = normalizedParent ?? server.rootDocId
366
- if (restParent) {
367
- try {
368
- await server.client.createChild(restParent, {
369
- child_id: id,
370
- label,
371
- doc_type: type,
372
- kind: 'page',
373
- })
374
- } catch (e) {
375
- return {
376
- content: [{
377
- type: 'text',
378
- text: `Failed to register document ${id} under ${restParent}: ${e instanceof Error ? e.message : String(e)}`,
379
- }],
380
- isError: true,
381
- }
382
- }
383
- }
384
-
385
- rootDoc.transact(() => {
386
- treeMap.set(
387
- id,
388
- makeEntryMap({
389
- label,
390
- parentId: normalizedParent,
391
- order: now,
392
- type,
393
- meta: meta as PageMeta,
394
- createdAt: now,
395
- updatedAt: now,
396
- }),
397
- )
398
- })
399
-
400
- server.setFocusedDoc(id)
401
-
402
- return {
403
- content: [{
404
- type: 'text',
405
- text: JSON.stringify({ id, label, parentId, type }, null, 2),
406
- }],
407
- }
408
- }
409
- )
410
-
411
- mcp.tool(
412
- 'rename_document',
413
- 'Rename a document (updates its display label everywhere).',
414
- {
415
- id: z.string().describe('Document ID to rename.'),
416
- label: z.string().describe('New display name.'),
417
- },
418
- async ({ id, label }) => {
419
- server.setAutoStatus('writing')
420
- server.setActiveToolCall({ name: 'rename_document', target: id })
421
- await server.ensureSpaceActive(id)
422
- const treeMap = server.getTreeMap()
423
- if (!treeMap) {
424
- return { content: [{ type: 'text', text: 'Not connected' }] }
425
- }
426
-
427
- const raw = treeMap.get(id)
428
- if (!raw) {
429
- return { content: [{ type: 'text', text: `Document ${id} not found` }] }
430
- }
431
-
432
- patchEntry(treeMap, id, { label, updatedAt: Date.now() })
433
- // Keep the SQL `documents.label` registry in step with the Yjs label so
434
- // `list_spaces` / `GET /docs` / FTS reflect the rename. Critical for
435
- // SPACE docs: the server-side label reconcile deliberately skips
436
- // `kind='space'` rows (their name is REST-canonical) and cou-sh renders
437
- // the registry name for space roots — so without this a renamed space
438
- // would keep its old name everywhere but the Yjs self-entry (the exact
439
- // "Health shows as Development" bug). Best-effort: a purely-Yjs (no-row)
440
- // doc PATCHes to a harmless no-op.
441
- let restNote = ''
442
- try {
443
- await server.client.updateDocumentMeta(id, { label })
444
- } catch (e) {
445
- restNote = ` (registry update failed: ${e instanceof Error ? e.message : String(e)})`
446
- }
447
- return { content: [{ type: 'text', text: `Renamed to "${label}"${restNote}` }] }
448
- }
449
- )
450
-
451
- mcp.tool(
452
- 'move_document',
453
- 'Move a document to a new parent and/or reorder it.',
454
- {
455
- id: z.string().describe('Document ID to move.'),
456
- newParentId: z.string().optional().describe('New parent document ID. Omit to move to top level.'),
457
- order: z.number().optional().describe('New sort order. Defaults to Date.now() (append to end).'),
458
- },
459
- async ({ id, newParentId, order }) => {
460
- server.setAutoStatus('writing')
461
- server.setActiveToolCall({ name: 'move_document', target: id })
462
- await server.ensureSpaceActive(id)
463
- const treeMap = server.getTreeMap()
464
- if (!treeMap) {
465
- return { content: [{ type: 'text', text: 'Not connected' }] }
466
- }
467
-
468
- const raw = treeMap.get(id)
469
- if (!raw) {
470
- return { content: [{ type: 'text', text: `Document ${id} not found` }] }
471
- }
472
-
473
- const normalizedParent = normalizeRootId(newParentId, server)
474
- // Cross-space moves aren't supported through a single tree map: the new
475
- // parent must live in the same space as the doc being moved. Refuse
476
- // rather than reparent onto a non-node (which would orphan the doc).
477
- if (normalizedParent && !treeMap.has(normalizedParent)) {
478
- return {
479
- content: [{
480
- type: 'text',
481
- text: `New parent "${newParentId}" is not in the same space as "${id}" (active space: ${server.rootDocId}). Cross-space moves aren't supported — refusing to avoid orphaning the document.`,
482
- }],
483
- isError: true,
484
- }
485
- }
486
- patchEntry(treeMap, id, {
487
- parentId: normalizedParent,
488
- order: order ?? Date.now(),
489
- updatedAt: Date.now(),
490
- })
491
- // Mirror the reparent into the SQL `documents` row via the
492
- // permission-checked REST path. The RBAC cascade walks `documents.parent_id`,
493
- // so a Yjs-only move would leave permission resolution on the OLD ancestry.
494
- // PATCH enforces manage-on-new-parent + cycle checks server-side (we never
495
- // project Yjs parentId straight to SQL — that would be an escalation hole).
496
- // REST parent for "top level" is the current space root. No-op for a
497
- // purely-Yjs (no-row) doc.
498
- const restParent = normalizedParent ?? server.rootDocId
499
- let restNote = ''
500
- if (restParent) {
501
- try {
502
- await server.client.updateDocumentMeta(id, { parent_id: restParent })
503
- } catch (e) {
504
- restNote = ` (registry reparent failed: ${e instanceof Error ? e.message : String(e)})`
505
- }
506
- }
507
- return { content: [{ type: 'text', text: `Moved ${id} to parent ${newParentId}${restNote}` }] }
508
- }
509
- )
510
-
511
- mcp.tool(
512
- 'delete_document',
513
- 'Soft-delete a document and its descendants (moves to trash).',
514
- {
515
- id: z.string().describe('Document ID to delete.'),
516
- },
517
- async ({ id }) => {
518
- server.setAutoStatus('writing')
519
- server.setActiveToolCall({ name: 'delete_document', target: id })
520
- await server.ensureSpaceActive(id)
521
- const treeMap = server.getTreeMap()
522
- const trashMap = server.getTrashMap()
523
- const rootDoc = server.rootDocument
524
- if (!treeMap || !trashMap || !rootDoc) {
525
- return { content: [{ type: 'text', text: 'Not connected' }] }
526
- }
527
-
528
- const entries = readEntries(treeMap, server.rootDocId)
529
- const toDelete = [id, ...descendantsOf(entries, id).map(e => e.id)]
530
-
531
- const now = Date.now()
532
- rootDoc.transact(() => {
533
- for (const nid of toDelete) {
534
- const raw = treeMap.get(nid)
535
- if (!raw) continue
536
- const entry = toPlain(raw) as any
537
- trashMap.set(nid, {
538
- label: entry.label || 'Untitled',
539
- parentId: entry.parentId ?? null,
540
- order: entry.order ?? 0,
541
- type: entry.type,
542
- meta: entry.meta,
543
- deletedAt: now,
544
- })
545
- treeMap.delete(nid)
546
- }
547
- })
548
-
549
- // Soft-delete the SQL `documents` row too (server cascades to descendants),
550
- // else the row stays live and the doc keeps showing up in `GET /docs` + FTS
551
- // search while hidden from the tree. Best-effort; no-op for a no-row doc.
552
- let restNote = ''
553
- try {
554
- await server.client.deleteDoc(id)
555
- } catch (e) {
556
- restNote = ` (registry delete failed: ${e instanceof Error ? e.message : String(e)})`
557
- }
558
-
559
- return { content: [{ type: 'text', text: `Deleted ${toDelete.length} document(s)${restNote}` }] }
560
- }
561
- )
562
-
563
- mcp.tool(
564
- 'change_document_type',
565
- 'Change the page type view of a document (data is preserved).',
566
- {
567
- id: z.string().describe('Document ID.'),
568
- type: z.string().describe('New page type. Core: "doc", "kanban", "table", "calendar", "timeline", "checklist", "outline", "gallery", "map", "graph", "dashboard", "slides", "chart", "sheets", "overview", "call". Plugin (require plugin enabled): "spatial", "media", "coder". Switching preserves the tree — children, labels, and meta are all retained; only the view changes.'),
569
- },
570
- async ({ id, type }) => {
571
- server.setAutoStatus('writing')
572
- server.setActiveToolCall({ name: 'change_document_type', target: id })
573
- await server.ensureSpaceActive(id)
574
- const treeMap = server.getTreeMap()
575
- if (!treeMap) {
576
- return { content: [{ type: 'text', text: 'Not connected' }] }
577
- }
578
-
579
- const raw = treeMap.get(id)
580
- if (!raw) {
581
- return { content: [{ type: 'text', text: `Document ${id} not found` }] }
582
- }
583
-
584
- patchEntry(treeMap, id, { type, updatedAt: Date.now() })
585
- return { content: [{ type: 'text', text: `Changed type to "${type}"` }] }
586
- }
587
- )
588
-
589
- mcp.tool(
590
- 'list_spaces',
591
- 'List all Spaces available on the server. Spaces are top-level documents (direct children of the server root) tagged with kind="space". Returns id, label, public_access, and active flag. Use switch_space to navigate.',
592
- {},
593
- async () => {
594
- server.setActiveToolCall({ name: 'list_spaces' })
595
- // Refresh from the server first — `_spaces` is otherwise a connect-time
596
- // snapshot, so a space seeded/created (or removed) after connect would
597
- // stay stale until a full reconnect (the "space disappeared" bug).
598
- const spaces = await server.refreshSpaces()
599
- if (!spaces.length) {
600
- return { content: [{ type: 'text', text: 'No spaces available — create one to get started.' }] }
601
- }
602
- const active = server.rootDocId
603
- const annotated = spaces.map(s => ({ ...s, active: s.id === active }))
604
- return { content: [{ type: 'text', text: JSON.stringify(annotated, null, 2) }] }
605
- }
606
- )
607
-
608
- mcp.tool(
609
- 'switch_space',
610
- 'Switch the active Space. All subsequent tree operations will target the new Space. Use list_spaces to discover available ids.',
611
- { docId: z.string().describe('The id of the Space to switch to (from list_spaces).') },
612
- async ({ docId }) => {
613
- server.setActiveToolCall({ name: 'switch_space', target: docId })
614
- await server.switchSpace(docId)
615
- const space = server.spaces.find(s => s.id === docId)
616
- const name = space?.label ?? docId
617
- return { content: [{ type: 'text', text: `Switched to space "${name}" (${docId})` }] }
618
- }
619
- )
620
-
621
- mcp.tool(
622
- 'duplicate_document',
623
- 'Shallow-clone a document with " (copy)" suffix. Returns new document ID.',
624
- {
625
- id: z.string().describe('Document ID to duplicate.'),
626
- },
627
- async ({ id }) => {
628
- server.setActiveToolCall({ name: 'duplicate_document', target: id })
629
- await server.ensureSpaceActive(id)
630
- const treeMap = server.getTreeMap()
631
- if (!treeMap) return { content: [{ type: 'text', text: 'Not connected' }] }
632
-
633
- const raw = treeMap.get(id)
634
- if (!raw) return { content: [{ type: 'text', text: `Document ${id} not found` }] }
635
-
636
- const entry = toPlain(raw) as any
637
- const newId = crypto.randomUUID()
638
- treeMap.set(
639
- newId,
640
- makeEntryMap({
641
- ...entry,
642
- label: (entry.label || 'Untitled') + ' (copy)',
643
- order: Date.now(),
644
- }),
645
- )
646
-
647
- server.setFocusedDoc(newId)
648
-
649
- return {
650
- content: [{
651
- type: 'text',
652
- text: JSON.stringify({ id: newId, label: entry.label + ' (copy)' }, null, 2),
653
- }],
654
- }
655
- }
656
- )
657
-
658
- mcp.tool(
659
- 'list_page_types',
660
- 'Enumerate all known Abracadabra page types with their metadata schemas. Returns an array of { key, label, icon, description, core, plugin, supportsChildren, childLabel, grandchildLabel, defaultDepth, metaSchema, defaultMetaFields }. `metaSchema` describes fields that apply to DESCENDANTS (children, grandchildren, ...) of a page of this type. `defaultMetaFields` are view-config fields on the page doc itself. Plugin types (core: false) require the named plugin to be enabled on the server. Use this to discover what meta keys a given renderer supports instead of guessing.',
661
- {
662
- key: z.string().optional().describe('Filter to a single type by key (e.g. "kanban", "calendar"). Aliases are resolved (e.g. "desktop" → "dashboard"). Omit to list all types.'),
663
- },
664
- async ({ key }) => {
665
- server.setActiveToolCall({ name: 'list_page_types', target: key })
666
- if (key) {
667
- const resolved = resolvePageType(key)
668
- if (!resolved) {
669
- return { content: [{ type: 'text', text: `Unknown page type "${key}". Call list_page_types with no args to see all types.` }] }
670
- }
671
- return { content: [{ type: 'text', text: JSON.stringify(resolved, null, 2) }] }
672
- }
673
- const all = Object.values(PAGE_TYPES)
674
- return {
675
- content: [{
676
- type: 'text',
677
- text: JSON.stringify({ types: all, aliases: TYPE_ALIASES }, null, 2),
678
- }],
679
- }
680
- }
681
- )
682
- }