@abraca/mcp 2.38.0 → 2.40.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.
@@ -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 { toPlain, patchEntry, reconcileDocCover } from '@abraca/dabra'
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
- populateYDocFromMarkdown(fragment, contentToWrite, fallbackTitle)
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
  }
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Server tools — manage and switch between multiple Abracadabra servers.
3
+ *
4
+ * `connect_server` is policy-aware: it probes the target before committing, so
5
+ * an open server connects silently while an invite-only / closed server returns
6
+ * an actionable message that the agent relays to the user — including this
7
+ * agent's public key, so an admin can authorize it by hand when no token exists.
8
+ */
9
+
10
+ import {
11
+ addServer,
12
+ resolveServer,
13
+ saveServerRegistry,
14
+ } from "@abraca/dabra";
15
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
16
+ import { z } from "zod";
17
+ import type { ServerManager } from "../server-manager.ts";
18
+
19
+ function text(s: string, isError = false) {
20
+ return { content: [{ type: "text" as const, text: s }], isError };
21
+ }
22
+
23
+ /** Render a connected summary including any read-only promotion hint. */
24
+ function connectedMessage(
25
+ manager: ServerManager,
26
+ alias: string,
27
+ url: string,
28
+ publicKey: string,
29
+ role: string | undefined,
30
+ needsPromotion: boolean,
31
+ ): string {
32
+ const active = manager.active;
33
+ const spaceCount = active?.spaces.length ?? 0;
34
+ const lines = [
35
+ `Connected to "${alias}" (${url}) as ${publicKey.slice(0, 12)}…`,
36
+ `Role: ${role ?? "unknown"}. Spaces visible: ${spaceCount}.`,
37
+ ];
38
+ if (needsPromotion) {
39
+ lines.push(
40
+ `Note: this account is read-only (observer). For write access, ask the server admin to grant a write role to public key:\n ${publicKey}`,
41
+ );
42
+ }
43
+ lines.push("Use list_spaces / get_document_tree to start working.");
44
+ return lines.join("\n");
45
+ }
46
+
47
+ /** Render the "can't connect yet" message for invite-only / closed servers. */
48
+ function blockedMessage(
49
+ status: "needs_invite" | "registration_closed",
50
+ serverName: string | undefined,
51
+ url: string,
52
+ publicKey: string,
53
+ ): string {
54
+ const who = serverName ? `"${serverName}" (${url})` : url;
55
+ const header =
56
+ status === "needs_invite"
57
+ ? `Server ${who} is invite-only and this agent is not yet registered.`
58
+ : `Server ${who} has open registration disabled, so this agent cannot self-register.`;
59
+ return [
60
+ header,
61
+ "",
62
+ "Two ways forward (no connection was made):",
63
+ ` 1. Provide a token: re-run connect_server with invite_code="…".`,
64
+ ` 2. No token? Ask the server admin to authorize/promote this agent's public key by hand, then re-run connect_server (no token needed):`,
65
+ ` ${publicKey}`,
66
+ ].join("\n");
67
+ }
68
+
69
+ export function registerServerTools(mcp: McpServer, manager: ServerManager) {
70
+ mcp.tool(
71
+ "list_servers",
72
+ "List the Abracadabra servers known to this agent and which one is currently active. Use connect_server / switch_server to change the active server.",
73
+ {},
74
+ async () => {
75
+ const servers = manager.listServers();
76
+ if (servers.length === 0) {
77
+ return text(
78
+ 'No servers configured yet. Connect to one with connect_server (e.g. server="https://your-server.example").',
79
+ );
80
+ }
81
+ const rows = servers.map(
82
+ (s) =>
83
+ `${s.active ? "●" : "○"} ${s.alias}${s.isDefault ? " (default)" : ""} — ${s.url}${s.active ? " [active]" : ""}`,
84
+ );
85
+ return text(rows.join("\n"));
86
+ },
87
+ );
88
+
89
+ mcp.tool(
90
+ "connect_server",
91
+ 'Connect to an Abracadabra server by alias or full URL and make it the active connection. Open servers connect immediately; invite-only/closed servers return instructions (provide a token, or have an admin authorize this agent\'s public key). On success the server is remembered for next time.',
92
+ {
93
+ server: z
94
+ .string()
95
+ .describe('Server alias (from list_servers) or a full URL like "https://coop.cou.sh".'),
96
+ invite_code: z
97
+ .string()
98
+ .optional()
99
+ .describe("Invite/registration token, if the server requires one."),
100
+ name: z
101
+ .string()
102
+ .optional()
103
+ .describe("Display name to present to this server (presence/registration)."),
104
+ },
105
+ async ({ server, invite_code, name }) => {
106
+ try {
107
+ const outcome = await manager.connectServer(server, {
108
+ inviteCode: invite_code,
109
+ name,
110
+ });
111
+ const { result, profile } = outcome;
112
+
113
+ if (result.status === "connected") {
114
+ // Remember the server so switch_server works later.
115
+ try {
116
+ const reg = addServer(manager.registry, profile);
117
+ manager.setRegistry(reg);
118
+ await saveServerRegistry(reg);
119
+ } catch {
120
+ /* registry persistence is best-effort */
121
+ }
122
+ return text(
123
+ connectedMessage(
124
+ manager,
125
+ profile.alias,
126
+ profile.url,
127
+ result.publicKey,
128
+ result.role,
129
+ result.needsPromotion,
130
+ ),
131
+ );
132
+ }
133
+
134
+ return text(
135
+ blockedMessage(
136
+ result.status,
137
+ result.serverName,
138
+ profile.url,
139
+ result.publicKey,
140
+ ),
141
+ );
142
+ } catch (error: any) {
143
+ return text(`Error connecting to "${server}": ${error.message}`, true);
144
+ }
145
+ },
146
+ );
147
+
148
+ mcp.tool(
149
+ "switch_server",
150
+ "Switch the active connection to an already-known server (see list_servers). Equivalent to connect_server for a remembered alias.",
151
+ {
152
+ server: z.string().describe("Server alias to switch to."),
153
+ },
154
+ async ({ server }) => {
155
+ try {
156
+ const profile = await resolveServer(manager.registry, server);
157
+ if (!profile || !manager.registry.servers[profile.alias]) {
158
+ return text(
159
+ `Unknown server "${server}". Use list_servers to see known servers, or connect_server with a full URL.`,
160
+ true,
161
+ );
162
+ }
163
+ const outcome = await manager.connectServer(server);
164
+ const { result } = outcome;
165
+ if (result.status === "connected") {
166
+ return text(
167
+ connectedMessage(
168
+ manager,
169
+ profile.alias,
170
+ profile.url,
171
+ result.publicKey,
172
+ result.role,
173
+ result.needsPromotion,
174
+ ),
175
+ );
176
+ }
177
+ return text(
178
+ blockedMessage(result.status, result.serverName, profile.url, result.publicKey),
179
+ );
180
+ } catch (error: any) {
181
+ return text(`Error switching to "${server}": ${error.message}`, true);
182
+ }
183
+ },
184
+ );
185
+
186
+ mcp.tool(
187
+ "current_server",
188
+ "Show which server is currently active (alias, URL, identity).",
189
+ {},
190
+ async () => {
191
+ const active = manager.active;
192
+ if (!active) {
193
+ return text("No server is currently connected. Use connect_server.");
194
+ }
195
+ const alias = manager.activeAlias ?? "(url)";
196
+ return text(
197
+ `Active server: ${alias} — ${active.serverInfo?.name ?? ""} ${active.config.url}\nIdentity: ${active.userId ?? "unknown"}\nSpaces visible: ${active.spaces.length}`,
198
+ );
199
+ },
200
+ );
201
+
202
+ mcp.tool(
203
+ "disconnect_server",
204
+ "Disconnect from the active server without connecting another. Tools will report 'no server connected' until you connect again.",
205
+ {},
206
+ async () => {
207
+ await manager.disconnect();
208
+ return text("Disconnected. Use connect_server to connect to a server.");
209
+ },
210
+ );
211
+ }