@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.
@@ -28,6 +28,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  }) : target, mod));
29
29
 
30
30
  //#endregion
31
+ let _abraca_dabra = require("@abraca/dabra");
31
32
  let ajv = require("ajv");
32
33
  ajv = __toESM(ajv);
33
34
  let ajv_formats = require("ajv-formats");
@@ -43,7 +44,6 @@ let node_os = require("node:os");
43
44
  node_os = __toESM(node_os);
44
45
  let node_path = require("node:path");
45
46
  node_path = __toESM(node_path);
46
- let _abraca_dabra = require("@abraca/dabra");
47
47
  let yjs = require("yjs");
48
48
  yjs = __toESM(yjs);
49
49
  let _abraca_convert = require("@abraca/convert");
@@ -12794,6 +12794,60 @@ var StdioServerTransport = class {
12794
12794
  }
12795
12795
  };
12796
12796
 
12797
+ //#endregion
12798
+ //#region packages/mcp/src/active-server.ts
12799
+ const NOT_CONNECTED = "No server connected. Use connect_server (or list_servers) first.";
12800
+ /**
12801
+ * Safe defaults used while no server is active. Mirrors the slice of the
12802
+ * `AbracadabraMCPServer` surface that tools + the hook-bridge actually touch
12803
+ * (see the `server.*` usage survey). Data getters/methods return empty/null so
12804
+ * existing guards trip; void status methods no-op; genuine data ops that need a
12805
+ * live connection throw a clear message.
12806
+ */
12807
+ const DISCONNECTED = {
12808
+ client: void 0,
12809
+ serverInfo: null,
12810
+ rootDocId: null,
12811
+ rootDocument: null,
12812
+ rootYProvider: null,
12813
+ spaces: [],
12814
+ userId: null,
12815
+ agentName: "AI Assistant",
12816
+ agentColor: "hsl(270, 80%, 60%)",
12817
+ getTreeMap: () => null,
12818
+ getTrashMap: () => null,
12819
+ getDocSummary: () => null,
12820
+ getEnabledPluginNames: () => [],
12821
+ setActiveToolCall: () => {},
12822
+ setAutoStatus: () => {},
12823
+ setWritingStatus: () => {},
12824
+ sendTypingIndicator: () => {},
12825
+ recordToolDetail: () => {},
12826
+ clearAiTask: () => {},
12827
+ setFocusedDoc: () => {},
12828
+ setDocCursor: () => {},
12829
+ startChannelNotifications: () => {},
12830
+ ensureConnected: async () => {},
12831
+ ensureSpaceActive: async () => false,
12832
+ getChildProvider: async () => {
12833
+ throw new Error(NOT_CONNECTED);
12834
+ },
12835
+ switchSpace: async () => {
12836
+ throw new Error(NOT_CONNECTED);
12837
+ }
12838
+ };
12839
+ /**
12840
+ * Build the forwarding proxy. Pass this everywhere a tool/hook-bridge expects an
12841
+ * `AbracadabraMCPServer`; it transparently tracks `manager.active`.
12842
+ */
12843
+ function createActiveServerProxy(manager) {
12844
+ return new Proxy({}, { get(_target, prop) {
12845
+ const target = manager.active ?? DISCONNECTED;
12846
+ const value = target[prop];
12847
+ return typeof value === "function" ? value.bind(target) : value;
12848
+ } });
12849
+ }
12850
+
12797
12851
  //#endregion
12798
12852
  //#region packages/mcp/src/hook-bridge.ts
12799
12853
  /**
@@ -21061,6 +21115,125 @@ var AbracadabraMCPServer = class AbracadabraMCPServer {
21061
21115
  }
21062
21116
  };
21063
21117
 
21118
+ //#endregion
21119
+ //#region packages/mcp/src/server-manager.ts
21120
+ /**
21121
+ * ServerManager — owns the registry of known servers and the single *active*
21122
+ * live connection (one-active model: switching tears down the previous one).
21123
+ *
21124
+ * The heavy per-server lifecycle (auth, space discovery, inbox observer,
21125
+ * heartbeat, channel notifications, awareness) stays in {@link
21126
+ * AbracadabraMCPServer}; the manager just decides *which* one is live and
21127
+ * brokers connect/switch/disconnect. Tools reach the live connection through the
21128
+ * forwarding proxy in `active-server.ts`, so they never hold a stale reference.
21129
+ *
21130
+ * The connect path is policy-aware: it probes the server first (see
21131
+ * {@link loginOrRegisterWithPolicy}) so an un-registered key yields an
21132
+ * actionable outcome (`needs_invite` / `registration_closed`) instead of an
21133
+ * opaque error — and, crucially, surfaces the agent's public key so an admin can
21134
+ * authorize it by hand when no invite token is available.
21135
+ */
21136
+ var ServerManager = class {
21137
+ constructor(registry, defaults = {}) {
21138
+ this._active = null;
21139
+ this._activeAlias = null;
21140
+ this._mcp = null;
21141
+ this._registry = registry;
21142
+ this._defaults = defaults;
21143
+ }
21144
+ /** The currently live connection, or null when nothing is connected. */
21145
+ get active() {
21146
+ return this._active;
21147
+ }
21148
+ get activeAlias() {
21149
+ return this._activeAlias;
21150
+ }
21151
+ get registry() {
21152
+ return this._registry;
21153
+ }
21154
+ /** Provide the MCP server so channel notifications can be (re)wired on switch. */
21155
+ attachMcp(mcp) {
21156
+ this._mcp = mcp;
21157
+ if (this._active) this._active.startChannelNotifications(mcp);
21158
+ }
21159
+ /**
21160
+ * Resolve, probe, and (if authorized) connect to a server. On success the
21161
+ * previous active connection is torn down and the new one becomes active.
21162
+ * On `needs_invite` / `registration_closed` nothing changes — the caller
21163
+ * relays the actionable message (including this agent's public key).
21164
+ */
21165
+ async connectServer(target, opts = {}) {
21166
+ const profile = await (0, _abraca_dabra.resolveServer)(this._registry, target);
21167
+ if (!profile) throw new Error(`Unknown server "${target}". Pass a full URL (http[s]://…) or add it to the registry first.`);
21168
+ if (this._active && this._activeAlias === profile.alias) return {
21169
+ profile,
21170
+ switched: false,
21171
+ result: {
21172
+ status: "connected",
21173
+ token: "",
21174
+ publicKey: this._active.userId ?? "",
21175
+ serverName: profile.displayName,
21176
+ needsPromotion: false
21177
+ }
21178
+ };
21179
+ const agentName = opts.name ?? profile.displayName ?? this._defaults.agentName;
21180
+ const inviteCode = opts.inviteCode ?? profile.inviteCode ?? this._defaults.inviteCode;
21181
+ const result = await (0, _abraca_dabra.loginOrRegisterWithPolicy)(new _abraca_dabra.AbracadabraClient({
21182
+ url: profile.url,
21183
+ persistAuth: false
21184
+ }), await (0, _abraca_dabra.loadOrCreateKeyFile)(profile.keyFile, { defaultFileName: "agent.key" }), {
21185
+ displayName: agentName,
21186
+ deviceName: "MCP Agent",
21187
+ inviteCode
21188
+ });
21189
+ if (result.status !== "connected") return {
21190
+ profile,
21191
+ switched: false,
21192
+ result
21193
+ };
21194
+ const conn = new AbracadabraMCPServer({
21195
+ url: profile.url,
21196
+ agentName,
21197
+ agentColor: profile.color ?? this._defaults.agentColor,
21198
+ inviteCode,
21199
+ keyFile: profile.keyFile,
21200
+ triggerMode: this._defaults.triggerMode,
21201
+ mentionAliases: this._defaults.mentionAliases
21202
+ });
21203
+ await conn.connect();
21204
+ const prev = this._active;
21205
+ this._active = conn;
21206
+ this._activeAlias = profile.alias;
21207
+ if (this._mcp) conn.startChannelNotifications(this._mcp);
21208
+ if (prev) await prev.destroy().catch(() => {});
21209
+ return {
21210
+ profile,
21211
+ switched: true,
21212
+ result
21213
+ };
21214
+ }
21215
+ /** Tear down the active connection (no-op when none). */
21216
+ async disconnect() {
21217
+ const prev = this._active;
21218
+ this._active = null;
21219
+ this._activeAlias = null;
21220
+ if (prev) await prev.destroy().catch(() => {});
21221
+ }
21222
+ /** Snapshot of known servers + which is active, for `list_servers`. */
21223
+ listServers() {
21224
+ return Object.values(this._registry.servers).map((p) => ({
21225
+ alias: p.alias,
21226
+ url: p.url,
21227
+ active: p.alias === this._activeAlias,
21228
+ isDefault: p.alias === this._registry.defaultAlias
21229
+ }));
21230
+ }
21231
+ /** Replace the in-memory registry (e.g. after a CLI edit reload). */
21232
+ setRegistry(registry) {
21233
+ this._registry = registry;
21234
+ }
21235
+ };
21236
+
21064
21237
  //#endregion
21065
21238
  //#region packages/mcp/src/tool-detail.ts
21066
21239
  /**
@@ -21405,6 +21578,76 @@ function registerChannelTools(mcp, server) {
21405
21578
  /**
21406
21579
  * Content tools — read/write document content via markdown ↔ Y.js conversion.
21407
21580
  */
21581
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
21582
+ /** Clamp per-block streaming delay to a sane window. */
21583
+ const STREAM_MS_DEFAULT = 90;
21584
+ const STREAM_MS_MAX = 2e3;
21585
+ /**
21586
+ * Collect every body Y.XmlText in a fragment, skipping the `documentHeader`
21587
+ * and `documentMeta` elements — the title/meta are synced to the tree entry
21588
+ * elsewhere, so a surgical body edit must never touch them (it would desync
21589
+ * the header from the tree `label`).
21590
+ */
21591
+ function collectBodyXmlText(frag, out) {
21592
+ for (const child of frag.toArray()) if (child instanceof yjs.XmlText) out.push(child);
21593
+ else if (child instanceof yjs.XmlElement) {
21594
+ const tag = child.nodeName;
21595
+ if (tag === "documentHeader" || tag === "documentMeta") continue;
21596
+ collectXmlTextDeep(child, out);
21597
+ }
21598
+ }
21599
+ function collectXmlTextDeep(node, out) {
21600
+ for (const child of node.toArray()) if (child instanceof yjs.XmlText) out.push(child);
21601
+ else if (child instanceof yjs.XmlElement) collectXmlTextDeep(child, out);
21602
+ }
21603
+ /**
21604
+ * Plain text of a Y.XmlText aligned with its Y character indices. Critically
21605
+ * NOT `text.toString()` — that serialises marks as XML tags
21606
+ * (`hello <bold>WORLD</bold>`), which throws off `indexOf` offsets. Each
21607
+ * non-string embed (inline atom) counts as one character, matching how Yjs
21608
+ * indexes them, so `delete`/`insert` offsets stay correct.
21609
+ */
21610
+ function plainTextForIndex(text) {
21611
+ const delta = text.toDelta();
21612
+ let s = "";
21613
+ for (const op of delta) s += typeof op.insert === "string" ? op.insert : "";
21614
+ return s;
21615
+ }
21616
+ /** Marks/attributes active at a character offset inside a Y.XmlText, so a
21617
+ * replacement can re-use the surrounding formatting (bold, link, etc.). */
21618
+ function attrsAtOffset(text, offset) {
21619
+ const delta = text.toDelta();
21620
+ let pos = 0;
21621
+ for (const op of delta) {
21622
+ const len = typeof op.insert === "string" ? op.insert.length : 1;
21623
+ if (offset < pos + len) return op.attributes;
21624
+ pos += len;
21625
+ }
21626
+ }
21627
+ /**
21628
+ * Replace `find` with `replace` inside a single Y.XmlText, preserving the
21629
+ * formatting at each match's start. Splices right-to-left so earlier offsets
21630
+ * stay valid. Returns the number of replacements made. Caller wraps the whole
21631
+ * pass in one transaction.
21632
+ */
21633
+ function surgicalReplaceInText(text, find, replace, all) {
21634
+ const s = plainTextForIndex(text);
21635
+ const offsets = [];
21636
+ let idx = s.indexOf(find);
21637
+ while (idx !== -1) {
21638
+ offsets.push(idx);
21639
+ if (!all) break;
21640
+ idx = s.indexOf(find, idx + find.length);
21641
+ }
21642
+ for (let i = offsets.length - 1; i >= 0; i--) {
21643
+ const at = offsets[i];
21644
+ const attrs = attrsAtOffset(text, at);
21645
+ text.delete(at, find.length);
21646
+ if (replace.length > 0) if (attrs && Object.keys(attrs).length > 0) text.insert(at, replace, attrs);
21647
+ else text.insert(at, replace);
21648
+ }
21649
+ return offsets.length;
21650
+ }
21408
21651
  function registerContentTools(mcp, server) {
21409
21652
  mcp.tool("read_document", "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.", { docId: zod.z.string().describe("Document ID to read.") }, async ({ docId }) => {
21410
21653
  try {
@@ -21469,8 +21712,10 @@ function registerContentTools(mcp, server) {
21469
21712
  mcp.tool("write_document", "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.", {
21470
21713
  docId: zod.z.string().describe("Document ID to write to."),
21471
21714
  markdown: zod.z.string().describe("Markdown content to write. Can include YAML frontmatter with title and metadata fields."),
21472
- mode: zod.z.enum(["replace", "append"]).optional().describe("Write mode. \"replace\" clears existing content first (default). \"append\" adds to the end.")
21473
- }, async ({ docId, markdown, mode }) => {
21715
+ mode: zod.z.enum(["replace", "append"]).optional().describe("Write mode. \"replace\" clears existing content first (default). \"append\" adds to the end."),
21716
+ stream: zod.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."),
21717
+ streamMs: zod.z.number().optional().describe("Delay in milliseconds between streamed blocks (only used when stream=true). Default 90, clamped to [0, 2000].")
21718
+ }, async ({ docId, markdown, mode, stream, streamMs }) => {
21474
21719
  try {
21475
21720
  server.setAutoStatus("writing", docId);
21476
21721
  server.setActiveToolCall({
@@ -21506,14 +21751,28 @@ function registerContentTools(mcp, server) {
21506
21751
  });
21507
21752
  const contentToWrite = body || markdown;
21508
21753
  const existingLabel = server.getDocSummary(docId)?.label;
21509
- (0, _abraca_convert.populateYDocFromMarkdown)(fragment, contentToWrite, title || existingLabel || "Untitled");
21754
+ const fallbackTitle = title || existingLabel || "Untitled";
21755
+ if (stream) {
21756
+ const { header, meta: metaNode, body: bodyNodes } = (0, _abraca_convert.markdownToFragmentNodes)(contentToWrite, fallbackTitle);
21757
+ if (writeMode !== "append") {
21758
+ const lead = [header, metaNode].filter((n) => !!n);
21759
+ if (lead.length) (0, _abraca_convert.appendJsonNodes)(fragment, lead);
21760
+ }
21761
+ const delay = Math.max(0, Math.min(streamMs ?? STREAM_MS_DEFAULT, STREAM_MS_MAX));
21762
+ for (const node of bodyNodes) {
21763
+ (0, _abraca_convert.appendJsonNodes)(fragment, [node]);
21764
+ server.setFocusedDoc(docId);
21765
+ server.setDocCursor(docId, fragment.length);
21766
+ if (delay > 0) await sleep(delay);
21767
+ }
21768
+ } else (0, _abraca_convert.populateYDocFromMarkdown)(fragment, contentToWrite, fallbackTitle);
21510
21769
  const coverTree = server.getTreeMap();
21511
21770
  if (coverTree) (0, _abraca_dabra.reconcileDocCover)(coverTree, docId, fragment);
21512
21771
  server.setFocusedDoc(docId);
21513
21772
  server.setDocCursor(docId, fragment.length);
21514
21773
  return { content: [{
21515
21774
  type: "text",
21516
- text: `Document ${docId} updated (${writeMode} mode)`
21775
+ text: `Document ${docId} updated (${writeMode} mode${stream ? ", streamed" : ""})`
21517
21776
  }] };
21518
21777
  } catch (error) {
21519
21778
  return {
@@ -21525,6 +21784,204 @@ function registerContentTools(mcp, server) {
21525
21784
  };
21526
21785
  }
21527
21786
  });
21787
+ mcp.tool("patch_document", "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.", {
21788
+ docId: zod.z.string().describe("Document ID to patch."),
21789
+ find: zod.z.string().describe("Exact substring of the current markdown to replace. Must be present verbatim. Returns an error listing nothing-matched if not found."),
21790
+ replace: zod.z.string().describe("Replacement text. Use an empty string to delete the matched text."),
21791
+ all: zod.z.boolean().optional().describe("Replace every occurrence (true) or only the first (false, default).")
21792
+ }, async ({ docId, find, replace, all }) => {
21793
+ try {
21794
+ server.setAutoStatus("writing", docId);
21795
+ server.setActiveToolCall({
21796
+ name: "patch_document",
21797
+ target: docId
21798
+ });
21799
+ if (find.length === 0) return {
21800
+ content: [{
21801
+ type: "text",
21802
+ text: "Error patching document: `find` must be a non-empty string."
21803
+ }],
21804
+ isError: true
21805
+ };
21806
+ await server.ensureSpaceActive(docId);
21807
+ const doc = (await server.getChildProvider(docId)).document;
21808
+ const fragment = doc.getXmlFragment("default");
21809
+ const textNodes = [];
21810
+ collectBodyXmlText(fragment, textNodes);
21811
+ let surgicalCount = 0;
21812
+ doc.transact(() => {
21813
+ for (const tn of textNodes) {
21814
+ surgicalCount += surgicalReplaceInText(tn, find, replace, !!all);
21815
+ if (!all && surgicalCount > 0) break;
21816
+ }
21817
+ });
21818
+ if (surgicalCount > 0) {
21819
+ server.setFocusedDoc(docId);
21820
+ return { content: [{
21821
+ type: "text",
21822
+ text: `Patched ${docId}: ${surgicalCount} replacement${surgicalCount === 1 ? "" : "s"} (surgical).`
21823
+ }] };
21824
+ }
21825
+ const treeMap = server.getTreeMap();
21826
+ let label = "Untitled";
21827
+ let type;
21828
+ let meta;
21829
+ if (treeMap) {
21830
+ const entry = (0, _abraca_dabra.toPlain)(treeMap.get(docId));
21831
+ if (entry && typeof entry === "object") {
21832
+ label = entry.label || label;
21833
+ type = entry.type;
21834
+ meta = entry.meta;
21835
+ }
21836
+ }
21837
+ const current = (0, _abraca_convert.yjsToMarkdown)(fragment, label, meta, type);
21838
+ if (!current.includes(find)) return {
21839
+ content: [{
21840
+ type: "text",
21841
+ text: `Error patching document: \`find\` text not present in ${docId}. Read the document first to see its exact current markdown.`
21842
+ }],
21843
+ isError: true
21844
+ };
21845
+ let count = 0;
21846
+ let next;
21847
+ if (all) {
21848
+ next = current.split(find).join(replace);
21849
+ count = current.split(find).length - 1;
21850
+ } else {
21851
+ next = current.replace(find, replace);
21852
+ count = 1;
21853
+ }
21854
+ const { title, meta: fmMeta, body } = (0, _abraca_convert.parseFrontmatter)(next);
21855
+ if (title || Object.keys(fmMeta).length > 0) {
21856
+ const rootDoc = server.rootDocument;
21857
+ if (treeMap && rootDoc) {
21858
+ const rawEntry = treeMap.get(docId);
21859
+ if (rawEntry) {
21860
+ const cur = (0, _abraca_dabra.toPlain)(rawEntry);
21861
+ rootDoc.transact(() => {
21862
+ const patch = { updatedAt: Date.now() };
21863
+ if (title) patch.label = title;
21864
+ if (Object.keys(fmMeta).length > 0) patch.meta = {
21865
+ ...cur.meta ?? {},
21866
+ ...fmMeta
21867
+ };
21868
+ (0, _abraca_dabra.patchEntry)(treeMap, docId, patch);
21869
+ });
21870
+ }
21871
+ }
21872
+ }
21873
+ doc.transact(() => {
21874
+ while (fragment.length > 0) fragment.delete(0);
21875
+ });
21876
+ (0, _abraca_convert.populateYDocFromMarkdown)(fragment, body || next, title || label || "Untitled");
21877
+ const coverTree = server.getTreeMap();
21878
+ if (coverTree) (0, _abraca_dabra.reconcileDocCover)(coverTree, docId, fragment);
21879
+ server.setFocusedDoc(docId);
21880
+ server.setDocCursor(docId, fragment.length);
21881
+ return { content: [{
21882
+ type: "text",
21883
+ text: `Patched ${docId}: ${count} replacement${count === 1 ? "" : "s"} (re-rendered).`
21884
+ }] };
21885
+ } catch (error) {
21886
+ return {
21887
+ content: [{
21888
+ type: "text",
21889
+ text: `Error patching document: ${error.message}`
21890
+ }],
21891
+ isError: true
21892
+ };
21893
+ }
21894
+ });
21895
+ mcp.tool("read_subtree", "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`.", {
21896
+ rootId: zod.z.string().describe("Document ID to read from (its own content is included as the tree root)."),
21897
+ depth: zod.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)."),
21898
+ maxNodes: zod.z.number().optional().describe("Maximum number of documents whose content is loaded. Default 40, hard cap 200. Protects against loading hundreds of child providers.")
21899
+ }, async ({ rootId, depth, maxNodes }) => {
21900
+ try {
21901
+ server.setAutoStatus("reading", rootId);
21902
+ server.setActiveToolCall({
21903
+ name: "read_subtree",
21904
+ target: rootId
21905
+ });
21906
+ await server.ensureSpaceActive(rootId);
21907
+ const treeMap = server.getTreeMap();
21908
+ if (!treeMap) return {
21909
+ content: [{
21910
+ type: "text",
21911
+ text: "Not connected"
21912
+ }],
21913
+ isError: true
21914
+ };
21915
+ const targetId = (0, _abraca_dabra.normalizeRootId)(rootId, server.rootDocId);
21916
+ const maxDepth = depth ?? 2;
21917
+ const cap = Math.max(1, Math.min(maxNodes ?? 40, 200));
21918
+ const entries = (0, _abraca_dabra.readEntries)(treeMap, server.rootDocId);
21919
+ const byParent = /* @__PURE__ */ new Map();
21920
+ for (const e of entries) {
21921
+ const list = byParent.get(e.parentId) ?? [];
21922
+ list.push(e);
21923
+ byParent.set(e.parentId, list);
21924
+ }
21925
+ const childrenOf = (id) => (byParent.get(id) ?? []).slice().sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
21926
+ let loaded = 0;
21927
+ const visited = /* @__PURE__ */ new Set();
21928
+ const readMarkdown = async (id, label, meta, type) => {
21929
+ if (loaded >= cap) return {
21930
+ markdown: null,
21931
+ truncated: true
21932
+ };
21933
+ loaded++;
21934
+ return { markdown: (0, _abraca_convert.yjsToMarkdown)((await server.getChildProvider(id)).document.getXmlFragment("default"), label, meta, type) };
21935
+ };
21936
+ const build = async (id, curDepth) => {
21937
+ if (maxDepth >= 0 && curDepth > maxDepth) return [];
21938
+ const out = [];
21939
+ for (const child of childrenOf(id)) {
21940
+ if (visited.has(child.id)) continue;
21941
+ visited.add(child.id);
21942
+ const { markdown, truncated } = await readMarkdown(child.id, child.label, child.meta, child.type);
21943
+ out.push({
21944
+ id: child.id,
21945
+ label: child.label,
21946
+ type: child.type,
21947
+ meta: child.meta,
21948
+ markdown,
21949
+ ...truncated ? { truncated: true } : {},
21950
+ children: await build(child.id, curDepth + 1)
21951
+ });
21952
+ }
21953
+ return out;
21954
+ };
21955
+ const rootEntry = (0, _abraca_dabra.toPlain)(treeMap.get(targetId ?? ""));
21956
+ const rootLabel = rootEntry && rootEntry.label || "Untitled";
21957
+ const rootType = rootEntry?.type;
21958
+ const rootMeta = rootEntry?.meta;
21959
+ visited.add(targetId ?? rootId);
21960
+ const rootContent = targetId === null ? { markdown: null } : await readMarkdown(targetId, rootLabel, rootMeta, rootType);
21961
+ const result = {
21962
+ id: targetId ?? rootId,
21963
+ label: rootLabel,
21964
+ type: rootType,
21965
+ meta: rootMeta,
21966
+ markdown: rootContent.markdown,
21967
+ ...rootContent.truncated ? { truncated: true } : {},
21968
+ children: await build(targetId, 1),
21969
+ ...loaded >= cap ? { note: `Stopped loading content after ${cap} nodes (maxNodes). Increase maxNodes or narrow rootId to see more.` } : {}
21970
+ };
21971
+ return { content: [{
21972
+ type: "text",
21973
+ text: JSON.stringify(result, null, 2)
21974
+ }] };
21975
+ } catch (error) {
21976
+ return {
21977
+ content: [{
21978
+ type: "text",
21979
+ text: `Error reading subtree: ${error.message}`
21980
+ }],
21981
+ isError: true
21982
+ };
21983
+ }
21984
+ });
21528
21985
  }
21529
21986
 
21530
21987
  //#endregion
@@ -21759,6 +22216,96 @@ function registerMetaTools(mcp, server, validator = null) {
21759
22216
  });
21760
22217
  }
21761
22218
 
22219
+ //#endregion
22220
+ //#region packages/mcp/src/tools/servers.ts
22221
+ /**
22222
+ * Server tools — manage and switch between multiple Abracadabra servers.
22223
+ *
22224
+ * `connect_server` is policy-aware: it probes the target before committing, so
22225
+ * an open server connects silently while an invite-only / closed server returns
22226
+ * an actionable message that the agent relays to the user — including this
22227
+ * agent's public key, so an admin can authorize it by hand when no token exists.
22228
+ */
22229
+ function text(s, isError = false) {
22230
+ return {
22231
+ content: [{
22232
+ type: "text",
22233
+ text: s
22234
+ }],
22235
+ isError
22236
+ };
22237
+ }
22238
+ /** Render a connected summary including any read-only promotion hint. */
22239
+ function connectedMessage(manager, alias, url, publicKey, role, needsPromotion) {
22240
+ const spaceCount = manager.active?.spaces.length ?? 0;
22241
+ const lines = [`Connected to "${alias}" (${url}) as ${publicKey.slice(0, 12)}…`, `Role: ${role ?? "unknown"}. Spaces visible: ${spaceCount}.`];
22242
+ if (needsPromotion) lines.push(`Note: this account is read-only (observer). For write access, ask the server admin to grant a write role to public key:\n ${publicKey}`);
22243
+ lines.push("Use list_spaces / get_document_tree to start working.");
22244
+ return lines.join("\n");
22245
+ }
22246
+ /** Render the "can't connect yet" message for invite-only / closed servers. */
22247
+ function blockedMessage(status, serverName, url, publicKey) {
22248
+ const who = serverName ? `"${serverName}" (${url})` : url;
22249
+ return [
22250
+ status === "needs_invite" ? `Server ${who} is invite-only and this agent is not yet registered.` : `Server ${who} has open registration disabled, so this agent cannot self-register.`,
22251
+ "",
22252
+ "Two ways forward (no connection was made):",
22253
+ ` 1. Provide a token: re-run connect_server with invite_code="…".`,
22254
+ ` 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):`,
22255
+ ` ${publicKey}`
22256
+ ].join("\n");
22257
+ }
22258
+ function registerServerTools(mcp, manager) {
22259
+ mcp.tool("list_servers", "List the Abracadabra servers known to this agent and which one is currently active. Use connect_server / switch_server to change the active server.", {}, async () => {
22260
+ const servers = manager.listServers();
22261
+ if (servers.length === 0) return text("No servers configured yet. Connect to one with connect_server (e.g. server=\"https://your-server.example\").");
22262
+ return text(servers.map((s) => `${s.active ? "●" : "○"} ${s.alias}${s.isDefault ? " (default)" : ""} — ${s.url}${s.active ? " [active]" : ""}`).join("\n"));
22263
+ });
22264
+ mcp.tool("connect_server", "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.", {
22265
+ server: zod.z.string().describe("Server alias (from list_servers) or a full URL like \"https://coop.cou.sh\"."),
22266
+ invite_code: zod.z.string().optional().describe("Invite/registration token, if the server requires one."),
22267
+ name: zod.z.string().optional().describe("Display name to present to this server (presence/registration).")
22268
+ }, async ({ server, invite_code, name }) => {
22269
+ try {
22270
+ const { result, profile } = await manager.connectServer(server, {
22271
+ inviteCode: invite_code,
22272
+ name
22273
+ });
22274
+ if (result.status === "connected") {
22275
+ try {
22276
+ const reg = (0, _abraca_dabra.addServer)(manager.registry, profile);
22277
+ manager.setRegistry(reg);
22278
+ await (0, _abraca_dabra.saveServerRegistry)(reg);
22279
+ } catch {}
22280
+ return text(connectedMessage(manager, profile.alias, profile.url, result.publicKey, result.role, result.needsPromotion));
22281
+ }
22282
+ return text(blockedMessage(result.status, result.serverName, profile.url, result.publicKey));
22283
+ } catch (error) {
22284
+ return text(`Error connecting to "${server}": ${error.message}`, true);
22285
+ }
22286
+ });
22287
+ mcp.tool("switch_server", "Switch the active connection to an already-known server (see list_servers). Equivalent to connect_server for a remembered alias.", { server: zod.z.string().describe("Server alias to switch to.") }, async ({ server }) => {
22288
+ try {
22289
+ const profile = await (0, _abraca_dabra.resolveServer)(manager.registry, server);
22290
+ if (!profile || !manager.registry.servers[profile.alias]) return text(`Unknown server "${server}". Use list_servers to see known servers, or connect_server with a full URL.`, true);
22291
+ const { result } = await manager.connectServer(server);
22292
+ if (result.status === "connected") return text(connectedMessage(manager, profile.alias, profile.url, result.publicKey, result.role, result.needsPromotion));
22293
+ return text(blockedMessage(result.status, result.serverName, profile.url, result.publicKey));
22294
+ } catch (error) {
22295
+ return text(`Error switching to "${server}": ${error.message}`, true);
22296
+ }
22297
+ });
22298
+ mcp.tool("current_server", "Show which server is currently active (alias, URL, identity).", {}, async () => {
22299
+ const active = manager.active;
22300
+ if (!active) return text("No server is currently connected. Use connect_server.");
22301
+ return text(`Active server: ${manager.activeAlias ?? "(url)"} — ${active.serverInfo?.name ?? ""} ${active.config.url}\nIdentity: ${active.userId ?? "unknown"}\nSpaces visible: ${active.spaces.length}`);
22302
+ });
22303
+ mcp.tool("disconnect_server", "Disconnect from the active server without connecting another. Tools will report 'no server connected' until you connect again.", {}, async () => {
22304
+ await manager.disconnect();
22305
+ return text("Disconnected. Use connect_server to connect to a server.");
22306
+ });
22307
+ }
22308
+
21762
22309
  //#endregion
21763
22310
  //#region packages/mcp/src/utils/sanitizeSvg.ts
21764
22311
  /**
@@ -21961,6 +22508,46 @@ function descendantsOf(entries, id) {
21961
22508
  collect(id);
21962
22509
  return result;
21963
22510
  }
22511
+ /**
22512
+ * Evaluate one `where` predicate value against a doc's actual value. The
22513
+ * predicate is a small string DSL so agents can filter on meta without a
22514
+ * structured query language:
22515
+ * - `>=N` `<=N` `>N` `<N` → numeric comparison (value coerced to number)
22516
+ * - `contains:X` → array membership OR string substring
22517
+ * - `exists` / `!exists` → presence / absence (null counts as absent)
22518
+ * - `=X` or bare `X` → loose equality (string-coerced)
22519
+ */
22520
+ function matchPredicate(actual, pred) {
22521
+ const p = pred.trim();
22522
+ if (p === "exists") return actual !== void 0 && actual !== null;
22523
+ if (p === "!exists") return actual === void 0 || actual === null;
22524
+ const cmp = p.match(/^(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);
22525
+ if (cmp) {
22526
+ const n = Number(actual);
22527
+ if (Number.isNaN(n)) return false;
22528
+ const rhs = Number(cmp[2]);
22529
+ switch (cmp[1]) {
22530
+ case ">=": return n >= rhs;
22531
+ case "<=": return n <= rhs;
22532
+ case ">": return n > rhs;
22533
+ case "<": return n < rhs;
22534
+ }
22535
+ }
22536
+ if (p.startsWith("contains:")) {
22537
+ const needle = p.slice(9);
22538
+ if (Array.isArray(actual)) return actual.map(String).includes(needle);
22539
+ if (typeof actual === "string") return actual.toLowerCase().includes(needle.toLowerCase());
22540
+ return false;
22541
+ }
22542
+ const want = p.startsWith("=") ? p.slice(1) : p;
22543
+ return String(actual) === want;
22544
+ }
22545
+ /** True when an entry satisfies EVERY predicate in `where`. The special key
22546
+ * `type` matches the entry's page type; every other key matches `entry.meta[key]`. */
22547
+ function matchesWhere(entry, where) {
22548
+ for (const [key, pred] of Object.entries(where)) if (!matchPredicate(key === "type" ? entry.type : entry.meta?.[key], pred)) return false;
22549
+ return true;
22550
+ }
21964
22551
  function buildTree(entries, rootId, maxDepth, currentDepth = 0, visited = /* @__PURE__ */ new Set()) {
21965
22552
  if (maxDepth >= 0 && currentDepth >= maxDepth) return [];
21966
22553
  return childrenOf(entries, rootId).filter((e) => !visited.has(e.id)).map((entry) => {
@@ -22013,15 +22600,24 @@ function registerTreeTools(mcp, server, validator = null) {
22013
22600
  text: JSON.stringify(tree, null, 2)
22014
22601
  }] };
22015
22602
  });
22016
- mcp.tool("find_document", "Search for documents by name across the entire tree. Returns matching documents with their full ancestor path. Use this when you're looking for a specific document and don't know where it is in the hierarchy.", {
22017
- query: zod.z.string().describe("Search query — matched case-insensitively against document labels (substring match)."),
22603
+ mcp.tool("find_document", "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.", {
22604
+ query: zod.z.string().optional().describe("Case-insensitive substring match against document labels. Optional when `where` is given."),
22605
+ where: zod.z.record(zod.z.string(), zod.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\"}."),
22018
22606
  rootId: zod.z.string().optional().describe("Restrict search to descendants of this document. Omit to search the entire tree.")
22019
- }, async ({ query, rootId }) => {
22607
+ }, async ({ query, where, rootId }) => {
22608
+ const label = query ?? (where ? Object.keys(where).join(",") : "find");
22020
22609
  server.setAutoStatus("searching");
22021
22610
  server.setActiveToolCall({
22022
22611
  name: "find_document",
22023
- target: query
22612
+ target: label
22024
22613
  });
22614
+ if (!query && (!where || Object.keys(where).length === 0)) return {
22615
+ content: [{
22616
+ type: "text",
22617
+ text: "find_document needs at least one of `query` (label substring) or `where` (metadata predicates)."
22618
+ }],
22619
+ isError: true
22620
+ };
22025
22621
  await server.ensureSpaceActive(rootId);
22026
22622
  const treeMap = server.getTreeMap();
22027
22623
  if (!treeMap) return { content: [{
@@ -22029,9 +22625,13 @@ function registerTreeTools(mcp, server, validator = null) {
22029
22625
  text: "Not connected"
22030
22626
  }] };
22031
22627
  const entries = (0, _abraca_dabra.readEntries)(treeMap, server.rootDocId);
22032
- const lowerQuery = query.toLowerCase();
22628
+ const lowerQuery = query?.toLowerCase();
22033
22629
  const normalizedRoot = normalizeRootId(rootId, server);
22034
- const matches = (normalizedRoot ? descendantsOf(entries, normalizedRoot) : entries).filter((e) => e.label.toLowerCase().includes(lowerQuery));
22630
+ const matches = (normalizedRoot ? descendantsOf(entries, normalizedRoot) : entries).filter((e) => {
22631
+ if (lowerQuery !== void 0 && !e.label.toLowerCase().includes(lowerQuery)) return false;
22632
+ if (where && !matchesWhere(e, where)) return false;
22633
+ return true;
22634
+ });
22035
22635
  const byId = new Map(entries.map((e) => [e.id, e]));
22036
22636
  const results = matches.map((entry) => {
22037
22637
  const path = [];
@@ -22054,7 +22654,7 @@ function registerTreeTools(mcp, server, validator = null) {
22054
22654
  });
22055
22655
  if (results.length === 0) return { content: [{
22056
22656
  type: "text",
22057
- text: `No documents found matching "${query}". Try get_document_tree to see the full hierarchy.`
22657
+ text: `No documents found matching ${[query ? `label~"${query}"` : null, where ? `where=${JSON.stringify(where)}` : null].filter(Boolean).join(" AND ")}. Try get_document_tree to see the full hierarchy.`
22058
22658
  }] };
22059
22659
  return { content: [{
22060
22660
  type: "text",
@@ -22418,7 +23018,13 @@ function registerTreeTools(mcp, server, validator = null) {
22418
23018
  * Abracadabra MCP Server — entry point.
22419
23019
  *
22420
23020
  * Environment variables:
22421
- * ABRA_URL (required) — Server URL (e.g. http://localhost:1234)
23021
+ * ABRA_URL (optional) — Server URL (e.g. http://localhost:1234).
23022
+ * When set, connects to it at boot (back-compat) and
23023
+ * remembers it in the server registry. When unset, the
23024
+ * agent boots idle and connects on request via the
23025
+ * connect_server tool (or to the registry's default).
23026
+ * ABRA_SERVERS_FILE — Path to the server registry JSON
23027
+ * (default: ~/.abracadabra/servers.json)
22422
23028
  * ABRA_AGENT_NAME — Display name (default: "AI Assistant")
22423
23029
  * ABRA_AGENT_COLOR — HSL color for presence (default: "hsl(270, 80%, 60%)")
22424
23030
  * ABRA_INVITE_CODE — Invite code for first-run registration (grants role)
@@ -22441,10 +23047,6 @@ function registerTreeTools(mcp, server, validator = null) {
22441
23047
  */
22442
23048
  async function main() {
22443
23049
  const url = process.env.ABRA_URL;
22444
- if (!url) {
22445
- console.error("Missing required environment variable: ABRA_URL");
22446
- process.exit(1);
22447
- }
22448
23050
  const rawMode = (process.env.ABRA_AGENT_TRIGGER_MODE ?? "mention+task").trim().toLowerCase();
22449
23051
  const validModes = [
22450
23052
  "all",
@@ -22456,16 +23058,36 @@ async function main() {
22456
23058
  if (rawMode && !validModes.includes(rawMode)) console.error(`[abracadabra-mcp] Invalid ABRA_AGENT_TRIGGER_MODE="${rawMode}", falling back to "mention+task"`);
22457
23059
  const aliasEnv = process.env.ABRA_AGENT_MENTION_ALIASES;
22458
23060
  const mentionAliases = aliasEnv ? aliasEnv.split(",").map((a) => a.trim()).filter((a) => a.length > 0) : void 0;
22459
- const server = new AbracadabraMCPServer({
22460
- url,
23061
+ const registry = await (0, _abraca_dabra.loadServerRegistry)();
23062
+ const { homedir } = await import("node:os");
23063
+ const { join } = await import("node:path");
23064
+ const legacyKeyFile = process.env.ABRA_KEY_FILE ?? join(homedir(), ".abracadabra", "agent.key");
23065
+ let workingRegistry = registry;
23066
+ let initialTarget = registry.defaultAlias ?? null;
23067
+ if (url) {
23068
+ const normalizedUrl = url.replace(/\/+$/, "");
23069
+ const existing = Object.values(workingRegistry.servers).find((p) => p.url === normalizedUrl);
23070
+ if (existing) initialTarget = existing.alias;
23071
+ else {
23072
+ const migrated = await (0, _abraca_dabra.migrateLegacyDefault)(workingRegistry, url, legacyKeyFile);
23073
+ workingRegistry = migrated.migrated ? migrated.registry : (0, _abraca_dabra.addServer)(workingRegistry, {
23074
+ alias: "default",
23075
+ url: normalizedUrl,
23076
+ keyFile: legacyKeyFile
23077
+ });
23078
+ initialTarget = workingRegistry.defaultAlias ?? Object.keys(workingRegistry.servers)[0] ?? null;
23079
+ await (0, _abraca_dabra.saveServerRegistry)(workingRegistry).catch(() => {});
23080
+ }
23081
+ }
23082
+ const manager = new ServerManager(workingRegistry, {
22461
23083
  agentName: process.env.ABRA_AGENT_NAME,
22462
23084
  agentColor: process.env.ABRA_AGENT_COLOR,
22463
23085
  inviteCode: process.env.ABRA_INVITE_CODE,
22464
- keyFile: process.env.ABRA_KEY_FILE,
22465
23086
  triggerMode,
22466
23087
  mentionAliases
22467
23088
  });
22468
- console.error(`[abracadabra-mcp] Trigger mode: ${triggerMode}; aliases: ${server.mentionAliases.join(", ")}`);
23089
+ const server = createActiveServerProxy(manager);
23090
+ console.error(`[abracadabra-mcp] Trigger mode: ${triggerMode}; aliases: ${mentionAliases?.join(", ") ?? process.env.ABRA_AGENT_NAME ?? "AI Assistant"}`);
22469
23091
  let schemaValidator = null;
22470
23092
  const schemaBundlePath = process.env.ABRA_MCP_SCHEMA_BUNDLE;
22471
23093
  if (schemaBundlePath && schemaBundlePath.trim().length > 0) try {
@@ -22525,15 +23147,18 @@ Read the resource at abracadabra://agent-guide for the complete guide covering p
22525
23147
  registerAwarenessTools(mcp, server);
22526
23148
  registerChannelTools(mcp, server);
22527
23149
  registerSvgTools(mcp, server);
23150
+ registerServerTools(mcp, manager);
22528
23151
  registerAgentGuide(mcp);
22529
23152
  registerTreeResource(mcp, server);
22530
23153
  registerServerInfoResource(mcp, server);
22531
- try {
22532
- await server.connect();
23154
+ if (initialTarget) try {
23155
+ const outcome = await manager.connectServer(initialTarget);
23156
+ if (outcome.result.status === "connected") console.error(`[abracadabra-mcp] Connected to "${initialTarget}" as ${outcome.result.publicKey.slice(0, 12)}…`);
23157
+ else console.error(`[abracadabra-mcp] "${initialTarget}" not connected (${outcome.result.status}); pubkey ${outcome.result.publicKey}. Use connect_server with an invite_code or have an admin authorize this key.`);
22533
23158
  } catch (error) {
22534
- console.error(`[abracadabra-mcp] Failed to connect: ${error.message}`);
22535
- process.exit(1);
23159
+ console.error(`[abracadabra-mcp] Initial connect to "${initialTarget}" failed: ${error.message}. Booting idle — use connect_server.`);
22536
23160
  }
23161
+ else console.error("[abracadabra-mcp] No server configured — booting idle. Use connect_server to connect.");
22537
23162
  const hookBridge = new HookBridge(server);
22538
23163
  try {
22539
23164
  const hookPort = await hookBridge.start();
@@ -22544,12 +23169,12 @@ Read the resource at abracadabra://agent-guide for the complete guide covering p
22544
23169
  registerHookTools(mcp, hookBridge);
22545
23170
  const transport = new StdioServerTransport();
22546
23171
  await mcp.connect(transport);
22547
- server.startChannelNotifications(mcp);
23172
+ manager.attachMcp(mcp);
22548
23173
  console.error("[abracadabra-mcp] MCP server running on stdio");
22549
23174
  const shutdown = async () => {
22550
23175
  console.error("[abracadabra-mcp] Shutting down...");
22551
23176
  await hookBridge.destroy();
22552
- await server.destroy();
23177
+ await manager.disconnect();
22553
23178
  process.exit(0);
22554
23179
  };
22555
23180
  process.on("SIGINT", shutdown);