@abraca/mcp 2.90.0 → 2.92.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.
@@ -1,518 +0,0 @@
1
- /**
2
- * Content tools — read/write document content via markdown ↔ Y.js conversion.
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 { populateYDocFromMarkdown, parseFrontmatter } from '../converters/markdownToYjs.ts'
9
- import { yjsToMarkdown } from '../converters/yjsToMarkdown.ts'
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
- }
97
-
98
- export function registerContentTools(mcp: McpServer, server: AbracadabraMCPServer) {
99
- mcp.tool(
100
- 'read_document',
101
- 'Read a document\'s content as markdown, along with its immediate children. IMPORTANT: A document\'s full content is its body text PLUS all its children. An empty body does not mean empty content — the children ARE the content (sub-docs, kanban columns, table columns, calendar events, etc.). Always check the returned "children" array and read child documents too.',
102
- {
103
- docId: z.string().describe('Document ID to read.'),
104
- },
105
- async ({ docId }) => {
106
- try {
107
- server.setAutoStatus('reading', docId)
108
- server.setActiveToolCall({ name: 'read_document', target: docId })
109
-
110
- await server.ensureSpaceActive(docId)
111
- const provider = await server.getChildProvider(docId)
112
- const fragment = provider.document.getXmlFragment('default')
113
-
114
- // Auto-update presence: mark this doc as focused and place cursor at start
115
- server.setFocusedDoc(docId)
116
- server.setDocCursor(docId, 0)
117
-
118
- // Get tree metadata + immediate children
119
- const treeMap = server.getTreeMap()
120
- let label = 'Untitled'
121
- let type: string | undefined
122
- let meta: Record<string, unknown> | undefined
123
- let children: Array<{ id: string; label: string; type?: string; meta?: unknown }> = []
124
- if (treeMap) {
125
- // Entries are nested Y.Map values — raw field access returns
126
- // undefined; resolve via toPlain first (mirrors tree.ts:readEntries).
127
- const entry = toPlain(treeMap.get(docId)) as any
128
- if (entry && typeof entry === 'object') {
129
- label = entry.label || label
130
- type = entry.type
131
- meta = entry.meta
132
- }
133
- // Collect immediate children sorted by order
134
- const collected: Array<{ id: string; label: string; type?: string; meta?: unknown; order: number }> = []
135
- treeMap.forEach((raw: any, id: string) => {
136
- const value = toPlain(raw) as any
137
- if (typeof value !== 'object' || value === null) return // skip non-entry keys (e.g. ":updatedAt")
138
- if (value.parentId === docId) {
139
- collected.push({ id, label: value.label || 'Untitled', type: value.type, meta: value.meta, order: value.order ?? 0 })
140
- }
141
- })
142
- collected.sort((a, b) => a.order - b.order)
143
- children = collected.map(({ order, ...rest }) => rest)
144
- }
145
-
146
- // yjsToMarkdown returns a string and takes the resolved label/meta/type
147
- // so frontmatter round-trips. (Older code destructured an object and
148
- // passed only the fragment — that silently produced `undefined`.)
149
- const markdown = yjsToMarkdown(fragment, label, meta as any, type)
150
-
151
- const result: Record<string, unknown> = { label, type, meta, markdown, children }
152
- return {
153
- content: [{
154
- type: 'text',
155
- text: JSON.stringify(result, null, 2),
156
- }],
157
- }
158
- } catch (error: any) {
159
- return {
160
- content: [{ type: 'text', text: `Error reading document: ${error.message}` }],
161
- isError: true,
162
- }
163
- }
164
- }
165
- )
166
-
167
- mcp.tool(
168
- 'write_document',
169
- 'Write markdown content to a document. Parses the markdown and writes it to the Y.js CRDT document, which syncs in real-time to all connected clients. Supports optional YAML frontmatter for title and metadata. Use ![[docId]] to embed another document as a block, or [[docId|label]] for inline doc links.',
170
- {
171
- docId: z.string().describe('Document ID to write to.'),
172
- markdown: z.string().describe('Markdown content to write. Can include YAML frontmatter with title and metadata fields.'),
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].'),
176
- },
177
- async ({ docId, markdown, mode, stream, streamMs }) => {
178
- try {
179
- server.setAutoStatus('writing', docId)
180
- server.setActiveToolCall({ name: 'write_document', target: docId })
181
-
182
- await server.ensureSpaceActive(docId)
183
- const writeMode = mode ?? 'replace'
184
- const provider = await server.getChildProvider(docId)
185
- const doc = provider.document
186
- const fragment = doc.getXmlFragment('default')
187
-
188
- // Parse optional frontmatter
189
- const { title, meta, body } = parseFrontmatter(markdown)
190
-
191
- // Update tree metadata if frontmatter provided title or meta
192
- if (title || Object.keys(meta).length > 0) {
193
- const treeMap = server.getTreeMap()
194
- const rootDoc = server.rootDocument
195
- if (treeMap && rootDoc) {
196
- const rawEntry = treeMap.get(docId)
197
- if (rawEntry) {
198
- const cur = toPlain(rawEntry) as { meta?: Record<string, unknown> }
199
- rootDoc.transact(() => {
200
- const patch: Record<string, unknown> = { updatedAt: Date.now() }
201
- if (title) patch.label = title
202
- if (Object.keys(meta).length > 0) {
203
- patch.meta = { ...(cur.meta ?? {}), ...meta }
204
- }
205
- patchEntry(treeMap, docId, patch)
206
- })
207
- }
208
- }
209
- }
210
-
211
- if (writeMode === 'replace') {
212
- // Clear existing content
213
- doc.transact(() => {
214
- while (fragment.length > 0) {
215
- fragment.delete(0)
216
- }
217
- })
218
- }
219
-
220
- // Write new content.
221
- //
222
- // ROOT-CAUSE FIX for the "card title silently becomes Untitled" bug:
223
- // when the markdown carries neither a frontmatter `title:` nor a
224
- // leading `# H1`, populateYDocFromMarkdown seeds the body
225
- // `documentHeader` with `fallbackTitle`. Passing the literal
226
- // 'Untitled' baked the placeholder string into the header — which a
227
- // client's title-sync (cou-sh) then read back and propagated into
228
- // the tree `label`, destroying the real title. Seed from the doc's
229
- // ACTUAL label instead so the header agrees with the tree from the
230
- // start (header === label → title-sync is a no-op). Only fall back
231
- // to 'Untitled' when the doc genuinely has no label yet.
232
- const contentToWrite = body || markdown
233
- const existingLabel = server.getDocSummary(docId)?.label
234
- const fallbackTitle = title || existingLabel || 'Untitled'
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
- }
262
-
263
- // Keep the persisted cover metadata in sync with the media blocks now
264
- // in the body. Without this, removing an image via write_document left
265
- // an orphaned cover on the kanban/gallery card (image gone from the
266
- // body, coverUploadId still pointing at the upload).
267
- const coverTree = server.getTreeMap()
268
- if (coverTree) reconcileDocCover(coverTree, docId, fragment)
269
-
270
- // Auto-update presence: mark this doc as focused and place cursor at end
271
- server.setFocusedDoc(docId)
272
- server.setDocCursor(docId, fragment.length)
273
-
274
-
275
- return {
276
- content: [{ type: 'text', text: `Document ${docId} updated (${writeMode} mode${stream ? ', streamed' : ''})` }],
277
- }
278
- } catch (error: any) {
279
- return {
280
- content: [{ type: 'text', text: `Error writing document: ${error.message}` }],
281
- isError: true,
282
- }
283
- }
284
- }
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
- )
518
- }
@@ -1,118 +0,0 @@
1
- /**
2
- * File tools — upload/download/list/delete files via the REST API.
3
- */
4
- import * as fs from 'node:fs'
5
- import * as path from 'node:path'
6
- import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
7
- import { z } from 'zod'
8
- import type { AbracadabraMCPServer } from '../server.ts'
9
-
10
- export function registerFileTools(mcp: McpServer, server: AbracadabraMCPServer) {
11
- mcp.tool(
12
- 'list_uploads',
13
- 'List file attachments for a document.',
14
- {
15
- docId: z.string().describe('Document ID.'),
16
- },
17
- async ({ docId }) => {
18
- server.setAutoStatus('reading', docId)
19
- server.setActiveToolCall({ name: 'list_uploads', target: docId })
20
- try {
21
- const uploads = await server.client.listUploads(docId)
22
- return {
23
- content: [{
24
- type: 'text',
25
- text: JSON.stringify(uploads, null, 2),
26
- }],
27
- }
28
- } catch (error: any) {
29
- return {
30
- content: [{ type: 'text', text: `Error listing uploads: ${error.message}` }],
31
- isError: true,
32
- }
33
- }
34
- }
35
- )
36
-
37
- mcp.tool(
38
- 'upload_file',
39
- 'Upload a local file to a document.',
40
- {
41
- docId: z.string().describe('Document ID to attach the file to.'),
42
- filePath: z.string().describe('Absolute path to the local file to upload.'),
43
- filename: z.string().optional().describe('Override filename (defaults to basename of filePath).'),
44
- },
45
- async ({ docId, filePath, filename }) => {
46
- server.setAutoStatus('uploading', docId)
47
- server.setActiveToolCall({ name: 'upload_file', target: path.basename(filePath) })
48
- try {
49
- const resolvedPath = path.resolve(filePath)
50
- const data = fs.readFileSync(resolvedPath)
51
- const name = filename ?? path.basename(resolvedPath)
52
- const blob = new Blob([data])
53
- const result = await server.client.upload(docId, blob, name)
54
- return {
55
- content: [{
56
- type: 'text',
57
- text: JSON.stringify(result, null, 2),
58
- }],
59
- }
60
- } catch (error: any) {
61
- return {
62
- content: [{ type: 'text', text: `Error uploading file: ${error.message}` }],
63
- isError: true,
64
- }
65
- }
66
- }
67
- )
68
-
69
- mcp.tool(
70
- 'download_file',
71
- 'Download a file attachment from a document to a local path.',
72
- {
73
- docId: z.string().describe('Document ID.'),
74
- uploadId: z.string().describe('Upload ID to download.'),
75
- saveTo: z.string().describe('Absolute local file path to save the download.'),
76
- },
77
- async ({ docId, uploadId, saveTo }) => {
78
- server.setAutoStatus('reading', docId)
79
- server.setActiveToolCall({ name: 'download_file', target: path.basename(saveTo) })
80
- try {
81
- const blob = await server.client.getUpload(docId, uploadId)
82
- const buffer = Buffer.from(await blob.arrayBuffer())
83
- const resolvedPath = path.resolve(saveTo)
84
- fs.writeFileSync(resolvedPath, buffer)
85
- return {
86
- content: [{ type: 'text', text: `Downloaded to ${resolvedPath} (${buffer.length} bytes)` }],
87
- }
88
- } catch (error: any) {
89
- return {
90
- content: [{ type: 'text', text: `Error downloading file: ${error.message}` }],
91
- isError: true,
92
- }
93
- }
94
- }
95
- )
96
-
97
- mcp.tool(
98
- 'delete_file',
99
- 'Delete a file attachment from a document.',
100
- {
101
- docId: z.string().describe('Document ID.'),
102
- uploadId: z.string().describe('Upload ID to delete.'),
103
- },
104
- async ({ docId, uploadId }) => {
105
- server.setAutoStatus('writing', docId)
106
- server.setActiveToolCall({ name: 'delete_file', target: uploadId })
107
- try {
108
- await server.client.deleteUpload(docId, uploadId)
109
- return { content: [{ type: 'text', text: `Deleted upload ${uploadId}` }] }
110
- } catch (error: any) {
111
- return {
112
- content: [{ type: 'text', text: `Error deleting file: ${error.message}` }],
113
- isError: true,
114
- }
115
- }
116
- }
117
- )
118
- }
@@ -1,51 +0,0 @@
1
- /**
2
- * Hook tools — provides Claude Code hook configuration for activity bridging.
3
- */
4
- import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
- import type { HookBridge } from "../hook-bridge.ts";
6
-
7
- export function registerHookTools(mcp: McpServer, hookBridge: HookBridge) {
8
- mcp.tool(
9
- "get_hook_config",
10
- 'Returns Claude Code hook configuration JSON for bridging activity to the Abracadabra dashboard. Copy the "hooks" object into your .claude/settings.json (or settings.local.json) to enable real-time tool-call activity cards in the chat, visible to all connected users.',
11
- {},
12
- async () => {
13
- const config = { hooks: buildHookConfig(hookBridge.portFile) };
14
- return {
15
- content: [
16
- {
17
- type: "text",
18
- text: JSON.stringify(config, null, 2),
19
- },
20
- ],
21
- };
22
- },
23
- );
24
- }
25
-
26
- /**
27
- * Build the Claude Code `hooks` object. We use a `command` hook (not `http`)
28
- * that reads the bridge's port file at execution time and POSTs the event
29
- * JSON (received on stdin) to it. This survives MCP restarts that pick a new
30
- * random port — the URL is resolved fresh each call instead of being baked in.
31
- *
32
- * The command is a no-op (`exit 0`) when the port file is missing or curl
33
- * fails, so a stopped bridge never blocks a tool call.
34
- */
35
- export function buildHookConfig(portFile: string): Record<string, unknown> {
36
- const cmd = `P=$(cat ${JSON.stringify(portFile)} 2>/dev/null); [ -n "$P" ] && curl -s -m 3 -X POST "http://127.0.0.1:$P/hook" --data-binary @- >/dev/null 2>&1; exit 0`;
37
- const hookEntry = { type: "command", command: cmd, timeout: 5 };
38
- const events = [
39
- "UserPromptSubmit",
40
- "PreToolUse",
41
- "PostToolUse",
42
- "SubagentStart",
43
- "SubagentStop",
44
- "Stop",
45
- ];
46
- const hooks: Record<string, unknown> = {};
47
- for (const ev of events) {
48
- hooks[ev] = [{ hooks: [hookEntry] }];
49
- }
50
- return hooks;
51
- }