@abraca/mcp 2.37.0 → 2.39.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/dist/abracadabra-mcp.cjs +348 -11
- package/dist/abracadabra-mcp.cjs.map +1 -1
- package/dist/abracadabra-mcp.esm.js +352 -12
- package/dist/abracadabra-mcp.esm.js.map +1 -1
- package/package.json +2 -2
- package/src/tools/content.ts +350 -4
- package/src/tools/tree.ts +70 -10
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@abraca/mcp",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.39.0",
|
|
4
4
|
"description": "MCP server for Abracadabra — AI agent collaboration on CRDT documents",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"y-protocols": "^1.0.6",
|
|
36
36
|
"yjs": "^13.6.8",
|
|
37
37
|
"zod": "^4.3.6",
|
|
38
|
-
"@abraca/convert": "2.
|
|
38
|
+
"@abraca/convert": "2.39.0"
|
|
39
39
|
},
|
|
40
40
|
"scripts": {
|
|
41
41
|
"test": "node --no-warnings --conditions=source --experimental-transform-types --test 'tests/*.test.ts'"
|
package/src/tools/content.ts
CHANGED
|
@@ -7,7 +7,93 @@ import { z } from 'zod'
|
|
|
7
7
|
import type { AbracadabraMCPServer } from '../server.ts'
|
|
8
8
|
import { populateYDocFromMarkdown, parseFrontmatter } from '../converters/markdownToYjs.ts'
|
|
9
9
|
import { yjsToMarkdown } from '../converters/yjsToMarkdown.ts'
|
|
10
|
-
import {
|
|
10
|
+
import { markdownToFragmentNodes, appendJsonNodes } from '@abraca/convert'
|
|
11
|
+
import { toPlain, patchEntry, reconcileDocCover, readEntries, normalizeRootId } from '@abraca/dabra'
|
|
12
|
+
import type { TreeEntry } from '@abraca/dabra'
|
|
13
|
+
|
|
14
|
+
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))
|
|
15
|
+
|
|
16
|
+
/** Clamp per-block streaming delay to a sane window. */
|
|
17
|
+
const STREAM_MS_DEFAULT = 90
|
|
18
|
+
const STREAM_MS_MAX = 2000
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Collect every body Y.XmlText in a fragment, skipping the `documentHeader`
|
|
22
|
+
* and `documentMeta` elements — the title/meta are synced to the tree entry
|
|
23
|
+
* elsewhere, so a surgical body edit must never touch them (it would desync
|
|
24
|
+
* the header from the tree `label`).
|
|
25
|
+
*/
|
|
26
|
+
export function collectBodyXmlText(frag: Y.XmlFragment, out: Y.XmlText[]): void {
|
|
27
|
+
for (const child of frag.toArray()) {
|
|
28
|
+
if (child instanceof Y.XmlText) out.push(child)
|
|
29
|
+
else if (child instanceof Y.XmlElement) {
|
|
30
|
+
const tag = child.nodeName
|
|
31
|
+
if (tag === 'documentHeader' || tag === 'documentMeta') continue
|
|
32
|
+
collectXmlTextDeep(child, out)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function collectXmlTextDeep(node: Y.XmlElement, out: Y.XmlText[]): void {
|
|
38
|
+
for (const child of node.toArray()) {
|
|
39
|
+
if (child instanceof Y.XmlText) out.push(child)
|
|
40
|
+
else if (child instanceof Y.XmlElement) collectXmlTextDeep(child, out)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Plain text of a Y.XmlText aligned with its Y character indices. Critically
|
|
46
|
+
* NOT `text.toString()` — that serialises marks as XML tags
|
|
47
|
+
* (`hello <bold>WORLD</bold>`), which throws off `indexOf` offsets. Each
|
|
48
|
+
* non-string embed (inline atom) counts as one character, matching how Yjs
|
|
49
|
+
* indexes them, so `delete`/`insert` offsets stay correct.
|
|
50
|
+
*/
|
|
51
|
+
function plainTextForIndex(text: Y.XmlText): string {
|
|
52
|
+
const delta = text.toDelta() as Array<{ insert: unknown }>
|
|
53
|
+
let s = ''
|
|
54
|
+
for (const op of delta) s += typeof op.insert === 'string' ? op.insert : ''
|
|
55
|
+
return s
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Marks/attributes active at a character offset inside a Y.XmlText, so a
|
|
59
|
+
* replacement can re-use the surrounding formatting (bold, link, etc.). */
|
|
60
|
+
function attrsAtOffset(text: Y.XmlText, offset: number): Record<string, unknown> | undefined {
|
|
61
|
+
const delta = text.toDelta() as Array<{ insert: unknown; attributes?: Record<string, unknown> }>
|
|
62
|
+
let pos = 0
|
|
63
|
+
for (const op of delta) {
|
|
64
|
+
const len = typeof op.insert === 'string' ? op.insert.length : 1
|
|
65
|
+
if (offset < pos + len) return op.attributes
|
|
66
|
+
pos += len
|
|
67
|
+
}
|
|
68
|
+
return undefined
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Replace `find` with `replace` inside a single Y.XmlText, preserving the
|
|
73
|
+
* formatting at each match's start. Splices right-to-left so earlier offsets
|
|
74
|
+
* stay valid. Returns the number of replacements made. Caller wraps the whole
|
|
75
|
+
* pass in one transaction.
|
|
76
|
+
*/
|
|
77
|
+
export function surgicalReplaceInText(text: Y.XmlText, find: string, replace: string, all: boolean): number {
|
|
78
|
+
const s = plainTextForIndex(text)
|
|
79
|
+
const offsets: number[] = []
|
|
80
|
+
let idx = s.indexOf(find)
|
|
81
|
+
while (idx !== -1) {
|
|
82
|
+
offsets.push(idx)
|
|
83
|
+
if (!all) break
|
|
84
|
+
idx = s.indexOf(find, idx + find.length)
|
|
85
|
+
}
|
|
86
|
+
for (let i = offsets.length - 1; i >= 0; i--) {
|
|
87
|
+
const at = offsets[i]
|
|
88
|
+
const attrs = attrsAtOffset(text, at)
|
|
89
|
+
text.delete(at, find.length)
|
|
90
|
+
if (replace.length > 0) {
|
|
91
|
+
if (attrs && Object.keys(attrs).length > 0) text.insert(at, replace, attrs)
|
|
92
|
+
else text.insert(at, replace)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return offsets.length
|
|
96
|
+
}
|
|
11
97
|
|
|
12
98
|
export function registerContentTools(mcp: McpServer, server: AbracadabraMCPServer) {
|
|
13
99
|
mcp.tool(
|
|
@@ -85,8 +171,10 @@ export function registerContentTools(mcp: McpServer, server: AbracadabraMCPServe
|
|
|
85
171
|
docId: z.string().describe('Document ID to write to.'),
|
|
86
172
|
markdown: z.string().describe('Markdown content to write. Can include YAML frontmatter with title and metadata fields.'),
|
|
87
173
|
mode: z.enum(['replace', 'append']).optional().describe('Write mode. "replace" clears existing content first (default). "append" adds to the end.'),
|
|
174
|
+
stream: z.boolean().optional().describe('When true, insert the content block-by-block (typewriter effect) so collaborators watching the document see it appear progressively, with the agent cursor advancing. The final document is identical to a non-streamed write. Default false.'),
|
|
175
|
+
streamMs: z.number().optional().describe('Delay in milliseconds between streamed blocks (only used when stream=true). Default 90, clamped to [0, 2000].'),
|
|
88
176
|
},
|
|
89
|
-
async ({ docId, markdown, mode }) => {
|
|
177
|
+
async ({ docId, markdown, mode, stream, streamMs }) => {
|
|
90
178
|
try {
|
|
91
179
|
server.setAutoStatus('writing', docId)
|
|
92
180
|
server.setActiveToolCall({ name: 'write_document', target: docId })
|
|
@@ -144,7 +232,33 @@ export function registerContentTools(mcp: McpServer, server: AbracadabraMCPServe
|
|
|
144
232
|
const contentToWrite = body || markdown
|
|
145
233
|
const existingLabel = server.getDocSummary(docId)?.label
|
|
146
234
|
const fallbackTitle = title || existingLabel || 'Untitled'
|
|
147
|
-
|
|
235
|
+
|
|
236
|
+
if (stream) {
|
|
237
|
+
// Streaming path: parse into the SAME canonical node tree the one-shot
|
|
238
|
+
// populate produces, then attach it block-by-block so collaborators see
|
|
239
|
+
// a typewriter effect. Final state is byte-identical to the non-stream
|
|
240
|
+
// path for `replace` mode. For `append` we only stream body blocks
|
|
241
|
+
// (the document already has a header/meta — don't duplicate them).
|
|
242
|
+
const { header, meta: metaNode, body: bodyNodes } = markdownToFragmentNodes(
|
|
243
|
+
contentToWrite,
|
|
244
|
+
fallbackTitle,
|
|
245
|
+
)
|
|
246
|
+
if (writeMode !== 'append') {
|
|
247
|
+
const lead = [header, metaNode].filter((n): n is NonNullable<typeof n> => !!n)
|
|
248
|
+
if (lead.length) appendJsonNodes(fragment, lead)
|
|
249
|
+
}
|
|
250
|
+
const delay = Math.max(0, Math.min(streamMs ?? STREAM_MS_DEFAULT, STREAM_MS_MAX))
|
|
251
|
+
for (const node of bodyNodes) {
|
|
252
|
+
appendJsonNodes(fragment, [node])
|
|
253
|
+
// Advance the agent cursor to the growing tail so watchers see the
|
|
254
|
+
// caret move as each block lands.
|
|
255
|
+
server.setFocusedDoc(docId)
|
|
256
|
+
server.setDocCursor(docId, fragment.length)
|
|
257
|
+
if (delay > 0) await sleep(delay)
|
|
258
|
+
}
|
|
259
|
+
} else {
|
|
260
|
+
populateYDocFromMarkdown(fragment, contentToWrite, fallbackTitle)
|
|
261
|
+
}
|
|
148
262
|
|
|
149
263
|
// Keep the persisted cover metadata in sync with the media blocks now
|
|
150
264
|
// in the body. Without this, removing an image via write_document left
|
|
@@ -159,7 +273,7 @@ export function registerContentTools(mcp: McpServer, server: AbracadabraMCPServe
|
|
|
159
273
|
|
|
160
274
|
|
|
161
275
|
return {
|
|
162
|
-
content: [{ type: 'text', text: `Document ${docId} updated (${writeMode} mode)` }],
|
|
276
|
+
content: [{ type: 'text', text: `Document ${docId} updated (${writeMode} mode${stream ? ', streamed' : ''})` }],
|
|
163
277
|
}
|
|
164
278
|
} catch (error: any) {
|
|
165
279
|
return {
|
|
@@ -169,4 +283,236 @@ export function registerContentTools(mcp: McpServer, server: AbracadabraMCPServe
|
|
|
169
283
|
}
|
|
170
284
|
}
|
|
171
285
|
)
|
|
286
|
+
|
|
287
|
+
mcp.tool(
|
|
288
|
+
'patch_document',
|
|
289
|
+
"Make a targeted edit to a document by find-and-replace on its markdown, WITHOUT resending the whole document. Reads the current content as markdown, replaces an exact substring, and writes it back. Use this for small/surgical edits (fix a typo, update one line, insert a paragraph next to an anchor) instead of read_document + write_document. The `find` string must match the current markdown exactly (whitespace included); the tool errors if it is not found so you never silently no-op.",
|
|
290
|
+
{
|
|
291
|
+
docId: z.string().describe('Document ID to patch.'),
|
|
292
|
+
find: z.string().describe('Exact substring of the current markdown to replace. Must be present verbatim. Returns an error listing nothing-matched if not found.'),
|
|
293
|
+
replace: z.string().describe('Replacement text. Use an empty string to delete the matched text.'),
|
|
294
|
+
all: z.boolean().optional().describe('Replace every occurrence (true) or only the first (false, default).'),
|
|
295
|
+
},
|
|
296
|
+
async ({ docId, find, replace, all }) => {
|
|
297
|
+
try {
|
|
298
|
+
server.setAutoStatus('writing', docId)
|
|
299
|
+
server.setActiveToolCall({ name: 'patch_document', target: docId })
|
|
300
|
+
|
|
301
|
+
if (find.length === 0) {
|
|
302
|
+
return {
|
|
303
|
+
content: [{ type: 'text', text: 'Error patching document: `find` must be a non-empty string.' }],
|
|
304
|
+
isError: true,
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
await server.ensureSpaceActive(docId)
|
|
309
|
+
const provider = await server.getChildProvider(docId)
|
|
310
|
+
const doc = provider.document
|
|
311
|
+
const fragment = doc.getXmlFragment('default')
|
|
312
|
+
|
|
313
|
+
// ── Fast path: surgical, CRDT-minimal edit ───────────────────────────
|
|
314
|
+
// When `find` appears as plain text inside a single body text run, splice
|
|
315
|
+
// just that span (preserving its marks). This leaves every other block —
|
|
316
|
+
// and other collaborators' selections — completely untouched, instead of
|
|
317
|
+
// re-rendering the whole fragment. Only the matched run changes.
|
|
318
|
+
const textNodes: Y.XmlText[] = []
|
|
319
|
+
collectBodyXmlText(fragment, textNodes)
|
|
320
|
+
let surgicalCount = 0
|
|
321
|
+
doc.transact(() => {
|
|
322
|
+
for (const tn of textNodes) {
|
|
323
|
+
surgicalCount += surgicalReplaceInText(tn, find, replace, !!all)
|
|
324
|
+
if (!all && surgicalCount > 0) break
|
|
325
|
+
}
|
|
326
|
+
})
|
|
327
|
+
if (surgicalCount > 0) {
|
|
328
|
+
server.setFocusedDoc(docId)
|
|
329
|
+
return {
|
|
330
|
+
content: [{ type: 'text', text: `Patched ${docId}: ${surgicalCount} replacement${surgicalCount === 1 ? '' : 's'} (surgical).` }],
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// ── Fallback: markdown-level find/replace + full re-render ────────────
|
|
335
|
+
// Reached when `find` spans block boundaries or includes markdown syntax
|
|
336
|
+
// (`**`, `# `, list markers) that isn't present in any single text run.
|
|
337
|
+
// Read current content as markdown, preserving the resolved label/meta/type
|
|
338
|
+
// so frontmatter round-trips (mirrors read_document).
|
|
339
|
+
const treeMap = server.getTreeMap()
|
|
340
|
+
let label = 'Untitled'
|
|
341
|
+
let type: string | undefined
|
|
342
|
+
let meta: Record<string, unknown> | undefined
|
|
343
|
+
if (treeMap) {
|
|
344
|
+
const entry = toPlain(treeMap.get(docId)) as any
|
|
345
|
+
if (entry && typeof entry === 'object') {
|
|
346
|
+
label = entry.label || label
|
|
347
|
+
type = entry.type
|
|
348
|
+
meta = entry.meta
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
const current = yjsToMarkdown(fragment, label, meta as any, type)
|
|
352
|
+
|
|
353
|
+
if (!current.includes(find)) {
|
|
354
|
+
return {
|
|
355
|
+
content: [{ type: 'text', text: `Error patching document: \`find\` text not present in ${docId}. Read the document first to see its exact current markdown.` }],
|
|
356
|
+
isError: true,
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
let count = 0
|
|
361
|
+
let next: string
|
|
362
|
+
if (all) {
|
|
363
|
+
next = current.split(find).join(replace)
|
|
364
|
+
count = current.split(find).length - 1
|
|
365
|
+
} else {
|
|
366
|
+
next = current.replace(find, replace)
|
|
367
|
+
count = 1
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// Re-render the whole fragment from the patched markdown. Final state is a
|
|
371
|
+
// normal write; the win is purely on the agent side (it sends only the
|
|
372
|
+
// small find/replace strings, not the whole document).
|
|
373
|
+
const { title, meta: fmMeta, body } = parseFrontmatter(next)
|
|
374
|
+
if (title || Object.keys(fmMeta).length > 0) {
|
|
375
|
+
const rootDoc = server.rootDocument
|
|
376
|
+
if (treeMap && rootDoc) {
|
|
377
|
+
const rawEntry = treeMap.get(docId)
|
|
378
|
+
if (rawEntry) {
|
|
379
|
+
const cur = toPlain(rawEntry) as { meta?: Record<string, unknown> }
|
|
380
|
+
rootDoc.transact(() => {
|
|
381
|
+
const patch: Record<string, unknown> = { updatedAt: Date.now() }
|
|
382
|
+
if (title) patch.label = title
|
|
383
|
+
if (Object.keys(fmMeta).length > 0) patch.meta = { ...(cur.meta ?? {}), ...fmMeta }
|
|
384
|
+
patchEntry(treeMap, docId, patch)
|
|
385
|
+
})
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
doc.transact(() => {
|
|
391
|
+
while (fragment.length > 0) fragment.delete(0)
|
|
392
|
+
})
|
|
393
|
+
const fallbackTitle = title || label || 'Untitled'
|
|
394
|
+
populateYDocFromMarkdown(fragment, body || next, fallbackTitle)
|
|
395
|
+
|
|
396
|
+
const coverTree = server.getTreeMap()
|
|
397
|
+
if (coverTree) reconcileDocCover(coverTree, docId, fragment)
|
|
398
|
+
|
|
399
|
+
server.setFocusedDoc(docId)
|
|
400
|
+
server.setDocCursor(docId, fragment.length)
|
|
401
|
+
|
|
402
|
+
return {
|
|
403
|
+
content: [{ type: 'text', text: `Patched ${docId}: ${count} replacement${count === 1 ? '' : 's'} (re-rendered).` }],
|
|
404
|
+
}
|
|
405
|
+
} catch (error: any) {
|
|
406
|
+
return {
|
|
407
|
+
content: [{ type: 'text', text: `Error patching document: ${error.message}` }],
|
|
408
|
+
isError: true,
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
mcp.tool(
|
|
415
|
+
'read_subtree',
|
|
416
|
+
"Read a document AND its descendants' markdown in ONE call, as a nested tree. Use this instead of repeated read_document + get_document_tree walks when you need the actual content of a board/outline/checklist and its children (e.g. \"summarize this kanban\"). Each node carries {id,label,type,meta,markdown,children[]}. Bounded by `depth` and `maxNodes` so it can't run away on huge trees — nodes past the cap are listed with their label/type but `markdown:null` and `truncated:true`.",
|
|
417
|
+
{
|
|
418
|
+
rootId: z.string().describe('Document ID to read from (its own content is included as the tree root).'),
|
|
419
|
+
depth: z.number().optional().describe('How many levels of descendants to include. Default 2. Use 0 for just the root doc, -1 for unlimited (still capped by maxNodes).'),
|
|
420
|
+
maxNodes: z.number().optional().describe('Maximum number of documents whose content is loaded. Default 40, hard cap 200. Protects against loading hundreds of child providers.'),
|
|
421
|
+
},
|
|
422
|
+
async ({ rootId, depth, maxNodes }) => {
|
|
423
|
+
try {
|
|
424
|
+
server.setAutoStatus('reading', rootId)
|
|
425
|
+
server.setActiveToolCall({ name: 'read_subtree', target: rootId })
|
|
426
|
+
|
|
427
|
+
await server.ensureSpaceActive(rootId)
|
|
428
|
+
const treeMap = server.getTreeMap()
|
|
429
|
+
if (!treeMap) {
|
|
430
|
+
return { content: [{ type: 'text', text: 'Not connected' }], isError: true }
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
const targetId = normalizeRootId(rootId, server.rootDocId)
|
|
434
|
+
const maxDepth = depth ?? 2
|
|
435
|
+
const cap = Math.max(1, Math.min(maxNodes ?? 40, 200))
|
|
436
|
+
const entries = readEntries(treeMap, server.rootDocId)
|
|
437
|
+
const byParent = new Map<string | null, TreeEntry[]>()
|
|
438
|
+
for (const e of entries) {
|
|
439
|
+
const list = byParent.get(e.parentId) ?? []
|
|
440
|
+
list.push(e)
|
|
441
|
+
byParent.set(e.parentId, list)
|
|
442
|
+
}
|
|
443
|
+
const childrenOf = (id: string | null): TreeEntry[] =>
|
|
444
|
+
(byParent.get(id) ?? []).slice().sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
|
|
445
|
+
|
|
446
|
+
let loaded = 0
|
|
447
|
+
const visited = new Set<string>()
|
|
448
|
+
|
|
449
|
+
// Load one doc's markdown via its child provider. Counts against the cap;
|
|
450
|
+
// once exhausted we still report the node but skip the (expensive) load.
|
|
451
|
+
const readMarkdown = async (
|
|
452
|
+
id: string,
|
|
453
|
+
label: string,
|
|
454
|
+
meta: unknown,
|
|
455
|
+
type: string | undefined,
|
|
456
|
+
): Promise<{ markdown: string | null; truncated?: boolean }> => {
|
|
457
|
+
if (loaded >= cap) return { markdown: null, truncated: true }
|
|
458
|
+
loaded++
|
|
459
|
+
const provider = await server.getChildProvider(id)
|
|
460
|
+
const fragment = provider.document.getXmlFragment('default')
|
|
461
|
+
return { markdown: yjsToMarkdown(fragment, label, meta as any, type) }
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const build = async (id: string | null, curDepth: number): Promise<any[]> => {
|
|
465
|
+
if (maxDepth >= 0 && curDepth > maxDepth) return []
|
|
466
|
+
const out: any[] = []
|
|
467
|
+
for (const child of childrenOf(id)) {
|
|
468
|
+
if (visited.has(child.id)) continue
|
|
469
|
+
visited.add(child.id)
|
|
470
|
+
const { markdown, truncated } = await readMarkdown(child.id, child.label, child.meta, child.type)
|
|
471
|
+
out.push({
|
|
472
|
+
id: child.id,
|
|
473
|
+
label: child.label,
|
|
474
|
+
type: child.type,
|
|
475
|
+
meta: child.meta,
|
|
476
|
+
markdown,
|
|
477
|
+
...(truncated ? { truncated: true } : {}),
|
|
478
|
+
children: await build(child.id, curDepth + 1),
|
|
479
|
+
})
|
|
480
|
+
}
|
|
481
|
+
return out
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// The root node itself (resolve its entry; the normalized root may be a
|
|
485
|
+
// space root that isn't a child of anything).
|
|
486
|
+
const rootEntry = toPlain(treeMap.get(targetId ?? '')) as any
|
|
487
|
+
const rootLabel = (rootEntry && rootEntry.label) || 'Untitled'
|
|
488
|
+
const rootType = rootEntry?.type as string | undefined
|
|
489
|
+
const rootMeta = rootEntry?.meta
|
|
490
|
+
visited.add(targetId ?? rootId)
|
|
491
|
+
const rootContent =
|
|
492
|
+
targetId === null
|
|
493
|
+
? { markdown: null } // server/space root has no body of its own
|
|
494
|
+
: await readMarkdown(targetId, rootLabel, rootMeta, rootType)
|
|
495
|
+
|
|
496
|
+
const result = {
|
|
497
|
+
id: targetId ?? rootId,
|
|
498
|
+
label: rootLabel,
|
|
499
|
+
type: rootType,
|
|
500
|
+
meta: rootMeta,
|
|
501
|
+
markdown: rootContent.markdown,
|
|
502
|
+
...((rootContent as any).truncated ? { truncated: true } : {}),
|
|
503
|
+
children: await build(targetId, 1),
|
|
504
|
+
...(loaded >= cap ? { note: `Stopped loading content after ${cap} nodes (maxNodes). Increase maxNodes or narrow rootId to see more.` } : {}),
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
return {
|
|
508
|
+
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
509
|
+
}
|
|
510
|
+
} catch (error: any) {
|
|
511
|
+
return {
|
|
512
|
+
content: [{ type: 'text', text: `Error reading subtree: ${error.message}` }],
|
|
513
|
+
isError: true,
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
)
|
|
172
518
|
}
|
package/src/tools/tree.ts
CHANGED
|
@@ -53,6 +53,51 @@ function descendantsOf(entries: TreeEntry[], id: string | null): TreeEntry[] {
|
|
|
53
53
|
return result
|
|
54
54
|
}
|
|
55
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
|
+
|
|
56
101
|
export function buildTree(entries: TreeEntry[], rootId: string | null, maxDepth: number, currentDepth = 0, visited = new Set<string>()): any[] {
|
|
57
102
|
if (maxDepth >= 0 && currentDepth >= maxDepth) return []
|
|
58
103
|
const children = childrenOf(entries, rootId)
|
|
@@ -133,14 +178,24 @@ export function registerTreeTools(
|
|
|
133
178
|
|
|
134
179
|
mcp.tool(
|
|
135
180
|
'find_document',
|
|
136
|
-
'Search for documents by name
|
|
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.',
|
|
137
182
|
{
|
|
138
|
-
query: z.string().describe('
|
|
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"}.'),
|
|
139
185
|
rootId: z.string().optional().describe('Restrict search to descendants of this document. Omit to search the entire tree.'),
|
|
140
186
|
},
|
|
141
|
-
async ({ query, rootId }) => {
|
|
187
|
+
async ({ query, where, rootId }) => {
|
|
188
|
+
const label = query ?? (where ? Object.keys(where).join(',') : 'find')
|
|
142
189
|
server.setAutoStatus('searching')
|
|
143
|
-
server.setActiveToolCall({ name: 'find_document', target:
|
|
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
|
+
|
|
144
199
|
await server.ensureSpaceActive(rootId)
|
|
145
200
|
const treeMap = server.getTreeMap()
|
|
146
201
|
if (!treeMap) {
|
|
@@ -148,16 +203,20 @@ export function registerTreeTools(
|
|
|
148
203
|
}
|
|
149
204
|
|
|
150
205
|
const entries = readEntries(treeMap, server.rootDocId)
|
|
151
|
-
const lowerQuery = query
|
|
206
|
+
const lowerQuery = query?.toLowerCase()
|
|
152
207
|
|
|
153
208
|
// If rootId specified, restrict to descendants only
|
|
154
209
|
const normalizedRoot = normalizeRootId(rootId, server)
|
|
155
210
|
const searchSet = normalizedRoot ? descendantsOf(entries, normalizedRoot) : entries
|
|
156
211
|
|
|
157
|
-
// Find matches
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
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
|
+
})
|
|
161
220
|
|
|
162
221
|
// Build ancestor path for each match
|
|
163
222
|
const byId = new Map(entries.map(e => [e.id, e]))
|
|
@@ -182,8 +241,9 @@ export function registerTreeTools(
|
|
|
182
241
|
})
|
|
183
242
|
|
|
184
243
|
if (results.length === 0) {
|
|
244
|
+
const crit = [query ? `label~"${query}"` : null, where ? `where=${JSON.stringify(where)}` : null].filter(Boolean).join(' AND ')
|
|
185
245
|
return {
|
|
186
|
-
content: [{ type: 'text', text: `No documents found matching
|
|
246
|
+
content: [{ type: 'text', text: `No documents found matching ${crit}. Try get_document_tree to see the full hierarchy.` }],
|
|
187
247
|
}
|
|
188
248
|
}
|
|
189
249
|
|