@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.
- package/dist/abracadabra-mcp.cjs +652 -27
- package/dist/abracadabra-mcp.cjs.map +1 -1
- package/dist/abracadabra-mcp.esm.js +656 -28
- package/dist/abracadabra-mcp.esm.js.map +1 -1
- package/package.json +2 -2
- package/src/active-server.ts +90 -0
- package/src/index.ts +99 -21
- package/src/server-manager.ts +182 -0
- package/src/tools/content.ts +350 -4
- package/src/tools/servers.ts +211 -0
- package/src/tools/tree.ts +70 -10
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { AbracadabraClient, AbracadabraProvider, PAGE_TYPES, SERVER_ROOT_ID, TYPE_ALIASES, WebSocketStatus, addServer, awarenessStatesToArray, foldRecords, isEncryptedContent, loadOrCreateKeyFile, loadServerRegistry, loginOrRegisterWithKey, loginOrRegisterWithPolicy, makeChallengeSigner, makeEntryMap, migrateLegacyDefault, normalizeRootId, openSyncedProvider, patchEntry, pickEntrySpace, readEntries, readEntries as readEntries$1, reconcileDocCover, recordFromYAny, resolvePageType, resolveServer, saveServerRegistry, toPlain, waitForSync } from "@abraca/dabra";
|
|
2
3
|
import Ajv from "ajv";
|
|
3
4
|
import addFormats from "ajv-formats";
|
|
4
5
|
import { ZodOptional, z } from "zod";
|
|
@@ -8,9 +9,8 @@ import { readFileSync } from "node:fs";
|
|
|
8
9
|
import * as http from "node:http";
|
|
9
10
|
import * as os from "node:os";
|
|
10
11
|
import * as path from "node:path";
|
|
11
|
-
import { AbracadabraClient, AbracadabraProvider, PAGE_TYPES, SERVER_ROOT_ID, TYPE_ALIASES, WebSocketStatus, awarenessStatesToArray, foldRecords, isEncryptedContent, loadOrCreateKeyFile, loginOrRegisterWithKey, makeChallengeSigner, makeEntryMap, normalizeRootId, openSyncedProvider, patchEntry, pickEntrySpace, readEntries, readEntries as readEntries$1, reconcileDocCover, recordFromYAny, resolvePageType, toPlain, waitForSync } from "@abraca/dabra";
|
|
12
12
|
import * as Y from "yjs";
|
|
13
|
-
import { parseFrontmatter, populateYDocFromMarkdown, yjsToMarkdown } from "@abraca/convert";
|
|
13
|
+
import { appendJsonNodes, markdownToFragmentNodes, parseFrontmatter, populateYDocFromMarkdown, yjsToMarkdown } from "@abraca/convert";
|
|
14
14
|
|
|
15
15
|
//#region \0rolldown/runtime.js
|
|
16
16
|
var __create = Object.create;
|
|
@@ -12786,6 +12786,60 @@ var StdioServerTransport = class {
|
|
|
12786
12786
|
}
|
|
12787
12787
|
};
|
|
12788
12788
|
|
|
12789
|
+
//#endregion
|
|
12790
|
+
//#region packages/mcp/src/active-server.ts
|
|
12791
|
+
const NOT_CONNECTED = "No server connected. Use connect_server (or list_servers) first.";
|
|
12792
|
+
/**
|
|
12793
|
+
* Safe defaults used while no server is active. Mirrors the slice of the
|
|
12794
|
+
* `AbracadabraMCPServer` surface that tools + the hook-bridge actually touch
|
|
12795
|
+
* (see the `server.*` usage survey). Data getters/methods return empty/null so
|
|
12796
|
+
* existing guards trip; void status methods no-op; genuine data ops that need a
|
|
12797
|
+
* live connection throw a clear message.
|
|
12798
|
+
*/
|
|
12799
|
+
const DISCONNECTED = {
|
|
12800
|
+
client: void 0,
|
|
12801
|
+
serverInfo: null,
|
|
12802
|
+
rootDocId: null,
|
|
12803
|
+
rootDocument: null,
|
|
12804
|
+
rootYProvider: null,
|
|
12805
|
+
spaces: [],
|
|
12806
|
+
userId: null,
|
|
12807
|
+
agentName: "AI Assistant",
|
|
12808
|
+
agentColor: "hsl(270, 80%, 60%)",
|
|
12809
|
+
getTreeMap: () => null,
|
|
12810
|
+
getTrashMap: () => null,
|
|
12811
|
+
getDocSummary: () => null,
|
|
12812
|
+
getEnabledPluginNames: () => [],
|
|
12813
|
+
setActiveToolCall: () => {},
|
|
12814
|
+
setAutoStatus: () => {},
|
|
12815
|
+
setWritingStatus: () => {},
|
|
12816
|
+
sendTypingIndicator: () => {},
|
|
12817
|
+
recordToolDetail: () => {},
|
|
12818
|
+
clearAiTask: () => {},
|
|
12819
|
+
setFocusedDoc: () => {},
|
|
12820
|
+
setDocCursor: () => {},
|
|
12821
|
+
startChannelNotifications: () => {},
|
|
12822
|
+
ensureConnected: async () => {},
|
|
12823
|
+
ensureSpaceActive: async () => false,
|
|
12824
|
+
getChildProvider: async () => {
|
|
12825
|
+
throw new Error(NOT_CONNECTED);
|
|
12826
|
+
},
|
|
12827
|
+
switchSpace: async () => {
|
|
12828
|
+
throw new Error(NOT_CONNECTED);
|
|
12829
|
+
}
|
|
12830
|
+
};
|
|
12831
|
+
/**
|
|
12832
|
+
* Build the forwarding proxy. Pass this everywhere a tool/hook-bridge expects an
|
|
12833
|
+
* `AbracadabraMCPServer`; it transparently tracks `manager.active`.
|
|
12834
|
+
*/
|
|
12835
|
+
function createActiveServerProxy(manager) {
|
|
12836
|
+
return new Proxy({}, { get(_target, prop) {
|
|
12837
|
+
const target = manager.active ?? DISCONNECTED;
|
|
12838
|
+
const value = target[prop];
|
|
12839
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
12840
|
+
} });
|
|
12841
|
+
}
|
|
12842
|
+
|
|
12789
12843
|
//#endregion
|
|
12790
12844
|
//#region packages/mcp/src/hook-bridge.ts
|
|
12791
12845
|
/**
|
|
@@ -21053,6 +21107,125 @@ var AbracadabraMCPServer = class AbracadabraMCPServer {
|
|
|
21053
21107
|
}
|
|
21054
21108
|
};
|
|
21055
21109
|
|
|
21110
|
+
//#endregion
|
|
21111
|
+
//#region packages/mcp/src/server-manager.ts
|
|
21112
|
+
/**
|
|
21113
|
+
* ServerManager — owns the registry of known servers and the single *active*
|
|
21114
|
+
* live connection (one-active model: switching tears down the previous one).
|
|
21115
|
+
*
|
|
21116
|
+
* The heavy per-server lifecycle (auth, space discovery, inbox observer,
|
|
21117
|
+
* heartbeat, channel notifications, awareness) stays in {@link
|
|
21118
|
+
* AbracadabraMCPServer}; the manager just decides *which* one is live and
|
|
21119
|
+
* brokers connect/switch/disconnect. Tools reach the live connection through the
|
|
21120
|
+
* forwarding proxy in `active-server.ts`, so they never hold a stale reference.
|
|
21121
|
+
*
|
|
21122
|
+
* The connect path is policy-aware: it probes the server first (see
|
|
21123
|
+
* {@link loginOrRegisterWithPolicy}) so an un-registered key yields an
|
|
21124
|
+
* actionable outcome (`needs_invite` / `registration_closed`) instead of an
|
|
21125
|
+
* opaque error — and, crucially, surfaces the agent's public key so an admin can
|
|
21126
|
+
* authorize it by hand when no invite token is available.
|
|
21127
|
+
*/
|
|
21128
|
+
var ServerManager = class {
|
|
21129
|
+
constructor(registry, defaults = {}) {
|
|
21130
|
+
this._active = null;
|
|
21131
|
+
this._activeAlias = null;
|
|
21132
|
+
this._mcp = null;
|
|
21133
|
+
this._registry = registry;
|
|
21134
|
+
this._defaults = defaults;
|
|
21135
|
+
}
|
|
21136
|
+
/** The currently live connection, or null when nothing is connected. */
|
|
21137
|
+
get active() {
|
|
21138
|
+
return this._active;
|
|
21139
|
+
}
|
|
21140
|
+
get activeAlias() {
|
|
21141
|
+
return this._activeAlias;
|
|
21142
|
+
}
|
|
21143
|
+
get registry() {
|
|
21144
|
+
return this._registry;
|
|
21145
|
+
}
|
|
21146
|
+
/** Provide the MCP server so channel notifications can be (re)wired on switch. */
|
|
21147
|
+
attachMcp(mcp) {
|
|
21148
|
+
this._mcp = mcp;
|
|
21149
|
+
if (this._active) this._active.startChannelNotifications(mcp);
|
|
21150
|
+
}
|
|
21151
|
+
/**
|
|
21152
|
+
* Resolve, probe, and (if authorized) connect to a server. On success the
|
|
21153
|
+
* previous active connection is torn down and the new one becomes active.
|
|
21154
|
+
* On `needs_invite` / `registration_closed` nothing changes — the caller
|
|
21155
|
+
* relays the actionable message (including this agent's public key).
|
|
21156
|
+
*/
|
|
21157
|
+
async connectServer(target, opts = {}) {
|
|
21158
|
+
const profile = await resolveServer(this._registry, target);
|
|
21159
|
+
if (!profile) throw new Error(`Unknown server "${target}". Pass a full URL (http[s]://…) or add it to the registry first.`);
|
|
21160
|
+
if (this._active && this._activeAlias === profile.alias) return {
|
|
21161
|
+
profile,
|
|
21162
|
+
switched: false,
|
|
21163
|
+
result: {
|
|
21164
|
+
status: "connected",
|
|
21165
|
+
token: "",
|
|
21166
|
+
publicKey: this._active.userId ?? "",
|
|
21167
|
+
serverName: profile.displayName,
|
|
21168
|
+
needsPromotion: false
|
|
21169
|
+
}
|
|
21170
|
+
};
|
|
21171
|
+
const agentName = opts.name ?? profile.displayName ?? this._defaults.agentName;
|
|
21172
|
+
const inviteCode = opts.inviteCode ?? profile.inviteCode ?? this._defaults.inviteCode;
|
|
21173
|
+
const result = await loginOrRegisterWithPolicy(new AbracadabraClient({
|
|
21174
|
+
url: profile.url,
|
|
21175
|
+
persistAuth: false
|
|
21176
|
+
}), await loadOrCreateKeyFile(profile.keyFile, { defaultFileName: "agent.key" }), {
|
|
21177
|
+
displayName: agentName,
|
|
21178
|
+
deviceName: "MCP Agent",
|
|
21179
|
+
inviteCode
|
|
21180
|
+
});
|
|
21181
|
+
if (result.status !== "connected") return {
|
|
21182
|
+
profile,
|
|
21183
|
+
switched: false,
|
|
21184
|
+
result
|
|
21185
|
+
};
|
|
21186
|
+
const conn = new AbracadabraMCPServer({
|
|
21187
|
+
url: profile.url,
|
|
21188
|
+
agentName,
|
|
21189
|
+
agentColor: profile.color ?? this._defaults.agentColor,
|
|
21190
|
+
inviteCode,
|
|
21191
|
+
keyFile: profile.keyFile,
|
|
21192
|
+
triggerMode: this._defaults.triggerMode,
|
|
21193
|
+
mentionAliases: this._defaults.mentionAliases
|
|
21194
|
+
});
|
|
21195
|
+
await conn.connect();
|
|
21196
|
+
const prev = this._active;
|
|
21197
|
+
this._active = conn;
|
|
21198
|
+
this._activeAlias = profile.alias;
|
|
21199
|
+
if (this._mcp) conn.startChannelNotifications(this._mcp);
|
|
21200
|
+
if (prev) await prev.destroy().catch(() => {});
|
|
21201
|
+
return {
|
|
21202
|
+
profile,
|
|
21203
|
+
switched: true,
|
|
21204
|
+
result
|
|
21205
|
+
};
|
|
21206
|
+
}
|
|
21207
|
+
/** Tear down the active connection (no-op when none). */
|
|
21208
|
+
async disconnect() {
|
|
21209
|
+
const prev = this._active;
|
|
21210
|
+
this._active = null;
|
|
21211
|
+
this._activeAlias = null;
|
|
21212
|
+
if (prev) await prev.destroy().catch(() => {});
|
|
21213
|
+
}
|
|
21214
|
+
/** Snapshot of known servers + which is active, for `list_servers`. */
|
|
21215
|
+
listServers() {
|
|
21216
|
+
return Object.values(this._registry.servers).map((p) => ({
|
|
21217
|
+
alias: p.alias,
|
|
21218
|
+
url: p.url,
|
|
21219
|
+
active: p.alias === this._activeAlias,
|
|
21220
|
+
isDefault: p.alias === this._registry.defaultAlias
|
|
21221
|
+
}));
|
|
21222
|
+
}
|
|
21223
|
+
/** Replace the in-memory registry (e.g. after a CLI edit reload). */
|
|
21224
|
+
setRegistry(registry) {
|
|
21225
|
+
this._registry = registry;
|
|
21226
|
+
}
|
|
21227
|
+
};
|
|
21228
|
+
|
|
21056
21229
|
//#endregion
|
|
21057
21230
|
//#region packages/mcp/src/tool-detail.ts
|
|
21058
21231
|
/**
|
|
@@ -21394,6 +21567,79 @@ function registerChannelTools(mcp, server) {
|
|
|
21394
21567
|
|
|
21395
21568
|
//#endregion
|
|
21396
21569
|
//#region packages/mcp/src/tools/content.ts
|
|
21570
|
+
/**
|
|
21571
|
+
* Content tools — read/write document content via markdown ↔ Y.js conversion.
|
|
21572
|
+
*/
|
|
21573
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
21574
|
+
/** Clamp per-block streaming delay to a sane window. */
|
|
21575
|
+
const STREAM_MS_DEFAULT = 90;
|
|
21576
|
+
const STREAM_MS_MAX = 2e3;
|
|
21577
|
+
/**
|
|
21578
|
+
* Collect every body Y.XmlText in a fragment, skipping the `documentHeader`
|
|
21579
|
+
* and `documentMeta` elements — the title/meta are synced to the tree entry
|
|
21580
|
+
* elsewhere, so a surgical body edit must never touch them (it would desync
|
|
21581
|
+
* the header from the tree `label`).
|
|
21582
|
+
*/
|
|
21583
|
+
function collectBodyXmlText(frag, out) {
|
|
21584
|
+
for (const child of frag.toArray()) if (child instanceof Y.XmlText) out.push(child);
|
|
21585
|
+
else if (child instanceof Y.XmlElement) {
|
|
21586
|
+
const tag = child.nodeName;
|
|
21587
|
+
if (tag === "documentHeader" || tag === "documentMeta") continue;
|
|
21588
|
+
collectXmlTextDeep(child, out);
|
|
21589
|
+
}
|
|
21590
|
+
}
|
|
21591
|
+
function collectXmlTextDeep(node, out) {
|
|
21592
|
+
for (const child of node.toArray()) if (child instanceof Y.XmlText) out.push(child);
|
|
21593
|
+
else if (child instanceof Y.XmlElement) collectXmlTextDeep(child, out);
|
|
21594
|
+
}
|
|
21595
|
+
/**
|
|
21596
|
+
* Plain text of a Y.XmlText aligned with its Y character indices. Critically
|
|
21597
|
+
* NOT `text.toString()` — that serialises marks as XML tags
|
|
21598
|
+
* (`hello <bold>WORLD</bold>`), which throws off `indexOf` offsets. Each
|
|
21599
|
+
* non-string embed (inline atom) counts as one character, matching how Yjs
|
|
21600
|
+
* indexes them, so `delete`/`insert` offsets stay correct.
|
|
21601
|
+
*/
|
|
21602
|
+
function plainTextForIndex(text) {
|
|
21603
|
+
const delta = text.toDelta();
|
|
21604
|
+
let s = "";
|
|
21605
|
+
for (const op of delta) s += typeof op.insert === "string" ? op.insert : "";
|
|
21606
|
+
return s;
|
|
21607
|
+
}
|
|
21608
|
+
/** Marks/attributes active at a character offset inside a Y.XmlText, so a
|
|
21609
|
+
* replacement can re-use the surrounding formatting (bold, link, etc.). */
|
|
21610
|
+
function attrsAtOffset(text, offset) {
|
|
21611
|
+
const delta = text.toDelta();
|
|
21612
|
+
let pos = 0;
|
|
21613
|
+
for (const op of delta) {
|
|
21614
|
+
const len = typeof op.insert === "string" ? op.insert.length : 1;
|
|
21615
|
+
if (offset < pos + len) return op.attributes;
|
|
21616
|
+
pos += len;
|
|
21617
|
+
}
|
|
21618
|
+
}
|
|
21619
|
+
/**
|
|
21620
|
+
* Replace `find` with `replace` inside a single Y.XmlText, preserving the
|
|
21621
|
+
* formatting at each match's start. Splices right-to-left so earlier offsets
|
|
21622
|
+
* stay valid. Returns the number of replacements made. Caller wraps the whole
|
|
21623
|
+
* pass in one transaction.
|
|
21624
|
+
*/
|
|
21625
|
+
function surgicalReplaceInText(text, find, replace, all) {
|
|
21626
|
+
const s = plainTextForIndex(text);
|
|
21627
|
+
const offsets = [];
|
|
21628
|
+
let idx = s.indexOf(find);
|
|
21629
|
+
while (idx !== -1) {
|
|
21630
|
+
offsets.push(idx);
|
|
21631
|
+
if (!all) break;
|
|
21632
|
+
idx = s.indexOf(find, idx + find.length);
|
|
21633
|
+
}
|
|
21634
|
+
for (let i = offsets.length - 1; i >= 0; i--) {
|
|
21635
|
+
const at = offsets[i];
|
|
21636
|
+
const attrs = attrsAtOffset(text, at);
|
|
21637
|
+
text.delete(at, find.length);
|
|
21638
|
+
if (replace.length > 0) if (attrs && Object.keys(attrs).length > 0) text.insert(at, replace, attrs);
|
|
21639
|
+
else text.insert(at, replace);
|
|
21640
|
+
}
|
|
21641
|
+
return offsets.length;
|
|
21642
|
+
}
|
|
21397
21643
|
function registerContentTools(mcp, server) {
|
|
21398
21644
|
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: z.string().describe("Document ID to read.") }, async ({ docId }) => {
|
|
21399
21645
|
try {
|
|
@@ -21458,8 +21704,10 @@ function registerContentTools(mcp, server) {
|
|
|
21458
21704
|
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.", {
|
|
21459
21705
|
docId: z.string().describe("Document ID to write to."),
|
|
21460
21706
|
markdown: z.string().describe("Markdown content to write. Can include YAML frontmatter with title and metadata fields."),
|
|
21461
|
-
mode: z.enum(["replace", "append"]).optional().describe("Write mode. \"replace\" clears existing content first (default). \"append\" adds to the end.")
|
|
21462
|
-
|
|
21707
|
+
mode: z.enum(["replace", "append"]).optional().describe("Write mode. \"replace\" clears existing content first (default). \"append\" adds to the end."),
|
|
21708
|
+
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."),
|
|
21709
|
+
streamMs: z.number().optional().describe("Delay in milliseconds between streamed blocks (only used when stream=true). Default 90, clamped to [0, 2000].")
|
|
21710
|
+
}, async ({ docId, markdown, mode, stream, streamMs }) => {
|
|
21463
21711
|
try {
|
|
21464
21712
|
server.setAutoStatus("writing", docId);
|
|
21465
21713
|
server.setActiveToolCall({
|
|
@@ -21495,14 +21743,28 @@ function registerContentTools(mcp, server) {
|
|
|
21495
21743
|
});
|
|
21496
21744
|
const contentToWrite = body || markdown;
|
|
21497
21745
|
const existingLabel = server.getDocSummary(docId)?.label;
|
|
21498
|
-
|
|
21746
|
+
const fallbackTitle = title || existingLabel || "Untitled";
|
|
21747
|
+
if (stream) {
|
|
21748
|
+
const { header, meta: metaNode, body: bodyNodes } = markdownToFragmentNodes(contentToWrite, fallbackTitle);
|
|
21749
|
+
if (writeMode !== "append") {
|
|
21750
|
+
const lead = [header, metaNode].filter((n) => !!n);
|
|
21751
|
+
if (lead.length) appendJsonNodes(fragment, lead);
|
|
21752
|
+
}
|
|
21753
|
+
const delay = Math.max(0, Math.min(streamMs ?? STREAM_MS_DEFAULT, STREAM_MS_MAX));
|
|
21754
|
+
for (const node of bodyNodes) {
|
|
21755
|
+
appendJsonNodes(fragment, [node]);
|
|
21756
|
+
server.setFocusedDoc(docId);
|
|
21757
|
+
server.setDocCursor(docId, fragment.length);
|
|
21758
|
+
if (delay > 0) await sleep(delay);
|
|
21759
|
+
}
|
|
21760
|
+
} else populateYDocFromMarkdown(fragment, contentToWrite, fallbackTitle);
|
|
21499
21761
|
const coverTree = server.getTreeMap();
|
|
21500
21762
|
if (coverTree) reconcileDocCover(coverTree, docId, fragment);
|
|
21501
21763
|
server.setFocusedDoc(docId);
|
|
21502
21764
|
server.setDocCursor(docId, fragment.length);
|
|
21503
21765
|
return { content: [{
|
|
21504
21766
|
type: "text",
|
|
21505
|
-
text: `Document ${docId} updated (${writeMode} mode)`
|
|
21767
|
+
text: `Document ${docId} updated (${writeMode} mode${stream ? ", streamed" : ""})`
|
|
21506
21768
|
}] };
|
|
21507
21769
|
} catch (error) {
|
|
21508
21770
|
return {
|
|
@@ -21514,6 +21776,204 @@ function registerContentTools(mcp, server) {
|
|
|
21514
21776
|
};
|
|
21515
21777
|
}
|
|
21516
21778
|
});
|
|
21779
|
+
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.", {
|
|
21780
|
+
docId: z.string().describe("Document ID to patch."),
|
|
21781
|
+
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."),
|
|
21782
|
+
replace: z.string().describe("Replacement text. Use an empty string to delete the matched text."),
|
|
21783
|
+
all: z.boolean().optional().describe("Replace every occurrence (true) or only the first (false, default).")
|
|
21784
|
+
}, async ({ docId, find, replace, all }) => {
|
|
21785
|
+
try {
|
|
21786
|
+
server.setAutoStatus("writing", docId);
|
|
21787
|
+
server.setActiveToolCall({
|
|
21788
|
+
name: "patch_document",
|
|
21789
|
+
target: docId
|
|
21790
|
+
});
|
|
21791
|
+
if (find.length === 0) return {
|
|
21792
|
+
content: [{
|
|
21793
|
+
type: "text",
|
|
21794
|
+
text: "Error patching document: `find` must be a non-empty string."
|
|
21795
|
+
}],
|
|
21796
|
+
isError: true
|
|
21797
|
+
};
|
|
21798
|
+
await server.ensureSpaceActive(docId);
|
|
21799
|
+
const doc = (await server.getChildProvider(docId)).document;
|
|
21800
|
+
const fragment = doc.getXmlFragment("default");
|
|
21801
|
+
const textNodes = [];
|
|
21802
|
+
collectBodyXmlText(fragment, textNodes);
|
|
21803
|
+
let surgicalCount = 0;
|
|
21804
|
+
doc.transact(() => {
|
|
21805
|
+
for (const tn of textNodes) {
|
|
21806
|
+
surgicalCount += surgicalReplaceInText(tn, find, replace, !!all);
|
|
21807
|
+
if (!all && surgicalCount > 0) break;
|
|
21808
|
+
}
|
|
21809
|
+
});
|
|
21810
|
+
if (surgicalCount > 0) {
|
|
21811
|
+
server.setFocusedDoc(docId);
|
|
21812
|
+
return { content: [{
|
|
21813
|
+
type: "text",
|
|
21814
|
+
text: `Patched ${docId}: ${surgicalCount} replacement${surgicalCount === 1 ? "" : "s"} (surgical).`
|
|
21815
|
+
}] };
|
|
21816
|
+
}
|
|
21817
|
+
const treeMap = server.getTreeMap();
|
|
21818
|
+
let label = "Untitled";
|
|
21819
|
+
let type;
|
|
21820
|
+
let meta;
|
|
21821
|
+
if (treeMap) {
|
|
21822
|
+
const entry = toPlain(treeMap.get(docId));
|
|
21823
|
+
if (entry && typeof entry === "object") {
|
|
21824
|
+
label = entry.label || label;
|
|
21825
|
+
type = entry.type;
|
|
21826
|
+
meta = entry.meta;
|
|
21827
|
+
}
|
|
21828
|
+
}
|
|
21829
|
+
const current = yjsToMarkdown(fragment, label, meta, type);
|
|
21830
|
+
if (!current.includes(find)) return {
|
|
21831
|
+
content: [{
|
|
21832
|
+
type: "text",
|
|
21833
|
+
text: `Error patching document: \`find\` text not present in ${docId}. Read the document first to see its exact current markdown.`
|
|
21834
|
+
}],
|
|
21835
|
+
isError: true
|
|
21836
|
+
};
|
|
21837
|
+
let count = 0;
|
|
21838
|
+
let next;
|
|
21839
|
+
if (all) {
|
|
21840
|
+
next = current.split(find).join(replace);
|
|
21841
|
+
count = current.split(find).length - 1;
|
|
21842
|
+
} else {
|
|
21843
|
+
next = current.replace(find, replace);
|
|
21844
|
+
count = 1;
|
|
21845
|
+
}
|
|
21846
|
+
const { title, meta: fmMeta, body } = parseFrontmatter(next);
|
|
21847
|
+
if (title || Object.keys(fmMeta).length > 0) {
|
|
21848
|
+
const rootDoc = server.rootDocument;
|
|
21849
|
+
if (treeMap && rootDoc) {
|
|
21850
|
+
const rawEntry = treeMap.get(docId);
|
|
21851
|
+
if (rawEntry) {
|
|
21852
|
+
const cur = toPlain(rawEntry);
|
|
21853
|
+
rootDoc.transact(() => {
|
|
21854
|
+
const patch = { updatedAt: Date.now() };
|
|
21855
|
+
if (title) patch.label = title;
|
|
21856
|
+
if (Object.keys(fmMeta).length > 0) patch.meta = {
|
|
21857
|
+
...cur.meta ?? {},
|
|
21858
|
+
...fmMeta
|
|
21859
|
+
};
|
|
21860
|
+
patchEntry(treeMap, docId, patch);
|
|
21861
|
+
});
|
|
21862
|
+
}
|
|
21863
|
+
}
|
|
21864
|
+
}
|
|
21865
|
+
doc.transact(() => {
|
|
21866
|
+
while (fragment.length > 0) fragment.delete(0);
|
|
21867
|
+
});
|
|
21868
|
+
populateYDocFromMarkdown(fragment, body || next, title || label || "Untitled");
|
|
21869
|
+
const coverTree = server.getTreeMap();
|
|
21870
|
+
if (coverTree) reconcileDocCover(coverTree, docId, fragment);
|
|
21871
|
+
server.setFocusedDoc(docId);
|
|
21872
|
+
server.setDocCursor(docId, fragment.length);
|
|
21873
|
+
return { content: [{
|
|
21874
|
+
type: "text",
|
|
21875
|
+
text: `Patched ${docId}: ${count} replacement${count === 1 ? "" : "s"} (re-rendered).`
|
|
21876
|
+
}] };
|
|
21877
|
+
} catch (error) {
|
|
21878
|
+
return {
|
|
21879
|
+
content: [{
|
|
21880
|
+
type: "text",
|
|
21881
|
+
text: `Error patching document: ${error.message}`
|
|
21882
|
+
}],
|
|
21883
|
+
isError: true
|
|
21884
|
+
};
|
|
21885
|
+
}
|
|
21886
|
+
});
|
|
21887
|
+
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`.", {
|
|
21888
|
+
rootId: z.string().describe("Document ID to read from (its own content is included as the tree root)."),
|
|
21889
|
+
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)."),
|
|
21890
|
+
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.")
|
|
21891
|
+
}, async ({ rootId, depth, maxNodes }) => {
|
|
21892
|
+
try {
|
|
21893
|
+
server.setAutoStatus("reading", rootId);
|
|
21894
|
+
server.setActiveToolCall({
|
|
21895
|
+
name: "read_subtree",
|
|
21896
|
+
target: rootId
|
|
21897
|
+
});
|
|
21898
|
+
await server.ensureSpaceActive(rootId);
|
|
21899
|
+
const treeMap = server.getTreeMap();
|
|
21900
|
+
if (!treeMap) return {
|
|
21901
|
+
content: [{
|
|
21902
|
+
type: "text",
|
|
21903
|
+
text: "Not connected"
|
|
21904
|
+
}],
|
|
21905
|
+
isError: true
|
|
21906
|
+
};
|
|
21907
|
+
const targetId = normalizeRootId(rootId, server.rootDocId);
|
|
21908
|
+
const maxDepth = depth ?? 2;
|
|
21909
|
+
const cap = Math.max(1, Math.min(maxNodes ?? 40, 200));
|
|
21910
|
+
const entries = readEntries(treeMap, server.rootDocId);
|
|
21911
|
+
const byParent = /* @__PURE__ */ new Map();
|
|
21912
|
+
for (const e of entries) {
|
|
21913
|
+
const list = byParent.get(e.parentId) ?? [];
|
|
21914
|
+
list.push(e);
|
|
21915
|
+
byParent.set(e.parentId, list);
|
|
21916
|
+
}
|
|
21917
|
+
const childrenOf = (id) => (byParent.get(id) ?? []).slice().sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
|
|
21918
|
+
let loaded = 0;
|
|
21919
|
+
const visited = /* @__PURE__ */ new Set();
|
|
21920
|
+
const readMarkdown = async (id, label, meta, type) => {
|
|
21921
|
+
if (loaded >= cap) return {
|
|
21922
|
+
markdown: null,
|
|
21923
|
+
truncated: true
|
|
21924
|
+
};
|
|
21925
|
+
loaded++;
|
|
21926
|
+
return { markdown: yjsToMarkdown((await server.getChildProvider(id)).document.getXmlFragment("default"), label, meta, type) };
|
|
21927
|
+
};
|
|
21928
|
+
const build = async (id, curDepth) => {
|
|
21929
|
+
if (maxDepth >= 0 && curDepth > maxDepth) return [];
|
|
21930
|
+
const out = [];
|
|
21931
|
+
for (const child of childrenOf(id)) {
|
|
21932
|
+
if (visited.has(child.id)) continue;
|
|
21933
|
+
visited.add(child.id);
|
|
21934
|
+
const { markdown, truncated } = await readMarkdown(child.id, child.label, child.meta, child.type);
|
|
21935
|
+
out.push({
|
|
21936
|
+
id: child.id,
|
|
21937
|
+
label: child.label,
|
|
21938
|
+
type: child.type,
|
|
21939
|
+
meta: child.meta,
|
|
21940
|
+
markdown,
|
|
21941
|
+
...truncated ? { truncated: true } : {},
|
|
21942
|
+
children: await build(child.id, curDepth + 1)
|
|
21943
|
+
});
|
|
21944
|
+
}
|
|
21945
|
+
return out;
|
|
21946
|
+
};
|
|
21947
|
+
const rootEntry = toPlain(treeMap.get(targetId ?? ""));
|
|
21948
|
+
const rootLabel = rootEntry && rootEntry.label || "Untitled";
|
|
21949
|
+
const rootType = rootEntry?.type;
|
|
21950
|
+
const rootMeta = rootEntry?.meta;
|
|
21951
|
+
visited.add(targetId ?? rootId);
|
|
21952
|
+
const rootContent = targetId === null ? { markdown: null } : await readMarkdown(targetId, rootLabel, rootMeta, rootType);
|
|
21953
|
+
const result = {
|
|
21954
|
+
id: targetId ?? rootId,
|
|
21955
|
+
label: rootLabel,
|
|
21956
|
+
type: rootType,
|
|
21957
|
+
meta: rootMeta,
|
|
21958
|
+
markdown: rootContent.markdown,
|
|
21959
|
+
...rootContent.truncated ? { truncated: true } : {},
|
|
21960
|
+
children: await build(targetId, 1),
|
|
21961
|
+
...loaded >= cap ? { note: `Stopped loading content after ${cap} nodes (maxNodes). Increase maxNodes or narrow rootId to see more.` } : {}
|
|
21962
|
+
};
|
|
21963
|
+
return { content: [{
|
|
21964
|
+
type: "text",
|
|
21965
|
+
text: JSON.stringify(result, null, 2)
|
|
21966
|
+
}] };
|
|
21967
|
+
} catch (error) {
|
|
21968
|
+
return {
|
|
21969
|
+
content: [{
|
|
21970
|
+
type: "text",
|
|
21971
|
+
text: `Error reading subtree: ${error.message}`
|
|
21972
|
+
}],
|
|
21973
|
+
isError: true
|
|
21974
|
+
};
|
|
21975
|
+
}
|
|
21976
|
+
});
|
|
21517
21977
|
}
|
|
21518
21978
|
|
|
21519
21979
|
//#endregion
|
|
@@ -21748,6 +22208,96 @@ function registerMetaTools(mcp, server, validator = null) {
|
|
|
21748
22208
|
});
|
|
21749
22209
|
}
|
|
21750
22210
|
|
|
22211
|
+
//#endregion
|
|
22212
|
+
//#region packages/mcp/src/tools/servers.ts
|
|
22213
|
+
/**
|
|
22214
|
+
* Server tools — manage and switch between multiple Abracadabra servers.
|
|
22215
|
+
*
|
|
22216
|
+
* `connect_server` is policy-aware: it probes the target before committing, so
|
|
22217
|
+
* an open server connects silently while an invite-only / closed server returns
|
|
22218
|
+
* an actionable message that the agent relays to the user — including this
|
|
22219
|
+
* agent's public key, so an admin can authorize it by hand when no token exists.
|
|
22220
|
+
*/
|
|
22221
|
+
function text(s, isError = false) {
|
|
22222
|
+
return {
|
|
22223
|
+
content: [{
|
|
22224
|
+
type: "text",
|
|
22225
|
+
text: s
|
|
22226
|
+
}],
|
|
22227
|
+
isError
|
|
22228
|
+
};
|
|
22229
|
+
}
|
|
22230
|
+
/** Render a connected summary including any read-only promotion hint. */
|
|
22231
|
+
function connectedMessage(manager, alias, url, publicKey, role, needsPromotion) {
|
|
22232
|
+
const spaceCount = manager.active?.spaces.length ?? 0;
|
|
22233
|
+
const lines = [`Connected to "${alias}" (${url}) as ${publicKey.slice(0, 12)}…`, `Role: ${role ?? "unknown"}. Spaces visible: ${spaceCount}.`];
|
|
22234
|
+
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}`);
|
|
22235
|
+
lines.push("Use list_spaces / get_document_tree to start working.");
|
|
22236
|
+
return lines.join("\n");
|
|
22237
|
+
}
|
|
22238
|
+
/** Render the "can't connect yet" message for invite-only / closed servers. */
|
|
22239
|
+
function blockedMessage(status, serverName, url, publicKey) {
|
|
22240
|
+
const who = serverName ? `"${serverName}" (${url})` : url;
|
|
22241
|
+
return [
|
|
22242
|
+
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.`,
|
|
22243
|
+
"",
|
|
22244
|
+
"Two ways forward (no connection was made):",
|
|
22245
|
+
` 1. Provide a token: re-run connect_server with invite_code="…".`,
|
|
22246
|
+
` 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):`,
|
|
22247
|
+
` ${publicKey}`
|
|
22248
|
+
].join("\n");
|
|
22249
|
+
}
|
|
22250
|
+
function registerServerTools(mcp, manager) {
|
|
22251
|
+
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 () => {
|
|
22252
|
+
const servers = manager.listServers();
|
|
22253
|
+
if (servers.length === 0) return text("No servers configured yet. Connect to one with connect_server (e.g. server=\"https://your-server.example\").");
|
|
22254
|
+
return text(servers.map((s) => `${s.active ? "●" : "○"} ${s.alias}${s.isDefault ? " (default)" : ""} — ${s.url}${s.active ? " [active]" : ""}`).join("\n"));
|
|
22255
|
+
});
|
|
22256
|
+
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.", {
|
|
22257
|
+
server: z.string().describe("Server alias (from list_servers) or a full URL like \"https://coop.cou.sh\"."),
|
|
22258
|
+
invite_code: z.string().optional().describe("Invite/registration token, if the server requires one."),
|
|
22259
|
+
name: z.string().optional().describe("Display name to present to this server (presence/registration).")
|
|
22260
|
+
}, async ({ server, invite_code, name }) => {
|
|
22261
|
+
try {
|
|
22262
|
+
const { result, profile } = await manager.connectServer(server, {
|
|
22263
|
+
inviteCode: invite_code,
|
|
22264
|
+
name
|
|
22265
|
+
});
|
|
22266
|
+
if (result.status === "connected") {
|
|
22267
|
+
try {
|
|
22268
|
+
const reg = addServer(manager.registry, profile);
|
|
22269
|
+
manager.setRegistry(reg);
|
|
22270
|
+
await saveServerRegistry(reg);
|
|
22271
|
+
} catch {}
|
|
22272
|
+
return text(connectedMessage(manager, profile.alias, profile.url, result.publicKey, result.role, result.needsPromotion));
|
|
22273
|
+
}
|
|
22274
|
+
return text(blockedMessage(result.status, result.serverName, profile.url, result.publicKey));
|
|
22275
|
+
} catch (error) {
|
|
22276
|
+
return text(`Error connecting to "${server}": ${error.message}`, true);
|
|
22277
|
+
}
|
|
22278
|
+
});
|
|
22279
|
+
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: z.string().describe("Server alias to switch to.") }, async ({ server }) => {
|
|
22280
|
+
try {
|
|
22281
|
+
const profile = await resolveServer(manager.registry, server);
|
|
22282
|
+
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);
|
|
22283
|
+
const { result } = await manager.connectServer(server);
|
|
22284
|
+
if (result.status === "connected") return text(connectedMessage(manager, profile.alias, profile.url, result.publicKey, result.role, result.needsPromotion));
|
|
22285
|
+
return text(blockedMessage(result.status, result.serverName, profile.url, result.publicKey));
|
|
22286
|
+
} catch (error) {
|
|
22287
|
+
return text(`Error switching to "${server}": ${error.message}`, true);
|
|
22288
|
+
}
|
|
22289
|
+
});
|
|
22290
|
+
mcp.tool("current_server", "Show which server is currently active (alias, URL, identity).", {}, async () => {
|
|
22291
|
+
const active = manager.active;
|
|
22292
|
+
if (!active) return text("No server is currently connected. Use connect_server.");
|
|
22293
|
+
return text(`Active server: ${manager.activeAlias ?? "(url)"} — ${active.serverInfo?.name ?? ""} ${active.config.url}\nIdentity: ${active.userId ?? "unknown"}\nSpaces visible: ${active.spaces.length}`);
|
|
22294
|
+
});
|
|
22295
|
+
mcp.tool("disconnect_server", "Disconnect from the active server without connecting another. Tools will report 'no server connected' until you connect again.", {}, async () => {
|
|
22296
|
+
await manager.disconnect();
|
|
22297
|
+
return text("Disconnected. Use connect_server to connect to a server.");
|
|
22298
|
+
});
|
|
22299
|
+
}
|
|
22300
|
+
|
|
21751
22301
|
//#endregion
|
|
21752
22302
|
//#region packages/mcp/src/utils/sanitizeSvg.ts
|
|
21753
22303
|
/**
|
|
@@ -21947,6 +22497,46 @@ function descendantsOf(entries, id) {
|
|
|
21947
22497
|
collect(id);
|
|
21948
22498
|
return result;
|
|
21949
22499
|
}
|
|
22500
|
+
/**
|
|
22501
|
+
* Evaluate one `where` predicate value against a doc's actual value. The
|
|
22502
|
+
* predicate is a small string DSL so agents can filter on meta without a
|
|
22503
|
+
* structured query language:
|
|
22504
|
+
* - `>=N` `<=N` `>N` `<N` → numeric comparison (value coerced to number)
|
|
22505
|
+
* - `contains:X` → array membership OR string substring
|
|
22506
|
+
* - `exists` / `!exists` → presence / absence (null counts as absent)
|
|
22507
|
+
* - `=X` or bare `X` → loose equality (string-coerced)
|
|
22508
|
+
*/
|
|
22509
|
+
function matchPredicate(actual, pred) {
|
|
22510
|
+
const p = pred.trim();
|
|
22511
|
+
if (p === "exists") return actual !== void 0 && actual !== null;
|
|
22512
|
+
if (p === "!exists") return actual === void 0 || actual === null;
|
|
22513
|
+
const cmp = p.match(/^(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);
|
|
22514
|
+
if (cmp) {
|
|
22515
|
+
const n = Number(actual);
|
|
22516
|
+
if (Number.isNaN(n)) return false;
|
|
22517
|
+
const rhs = Number(cmp[2]);
|
|
22518
|
+
switch (cmp[1]) {
|
|
22519
|
+
case ">=": return n >= rhs;
|
|
22520
|
+
case "<=": return n <= rhs;
|
|
22521
|
+
case ">": return n > rhs;
|
|
22522
|
+
case "<": return n < rhs;
|
|
22523
|
+
}
|
|
22524
|
+
}
|
|
22525
|
+
if (p.startsWith("contains:")) {
|
|
22526
|
+
const needle = p.slice(9);
|
|
22527
|
+
if (Array.isArray(actual)) return actual.map(String).includes(needle);
|
|
22528
|
+
if (typeof actual === "string") return actual.toLowerCase().includes(needle.toLowerCase());
|
|
22529
|
+
return false;
|
|
22530
|
+
}
|
|
22531
|
+
const want = p.startsWith("=") ? p.slice(1) : p;
|
|
22532
|
+
return String(actual) === want;
|
|
22533
|
+
}
|
|
22534
|
+
/** True when an entry satisfies EVERY predicate in `where`. The special key
|
|
22535
|
+
* `type` matches the entry's page type; every other key matches `entry.meta[key]`. */
|
|
22536
|
+
function matchesWhere(entry, where) {
|
|
22537
|
+
for (const [key, pred] of Object.entries(where)) if (!matchPredicate(key === "type" ? entry.type : entry.meta?.[key], pred)) return false;
|
|
22538
|
+
return true;
|
|
22539
|
+
}
|
|
21950
22540
|
function buildTree(entries, rootId, maxDepth, currentDepth = 0, visited = /* @__PURE__ */ new Set()) {
|
|
21951
22541
|
if (maxDepth >= 0 && currentDepth >= maxDepth) return [];
|
|
21952
22542
|
return childrenOf(entries, rootId).filter((e) => !visited.has(e.id)).map((entry) => {
|
|
@@ -21999,15 +22589,24 @@ function registerTreeTools(mcp, server, validator = null) {
|
|
|
21999
22589
|
text: JSON.stringify(tree, null, 2)
|
|
22000
22590
|
}] };
|
|
22001
22591
|
});
|
|
22002
|
-
mcp.tool("find_document", "Search for documents by name
|
|
22003
|
-
query: z.string().describe("
|
|
22592
|
+
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.", {
|
|
22593
|
+
query: z.string().optional().describe("Case-insensitive substring match against document labels. Optional when `where` is given."),
|
|
22594
|
+
where: z.record(z.string(), z.string()).optional().describe("Metadata predicates, ALL of which must match. Key is a meta field (or the special key \"type\" for page type); value is a tiny predicate: \">=3\" / \"<=1\" (numeric, e.g. priority), \"contains:bug\" (array membership or string substring, e.g. tags), \"exists\" / \"!exists\", or a bare/\"=value\" for equality. Example: {\"priority\":\">=3\",\"type\":\"kanban\"}."),
|
|
22004
22595
|
rootId: z.string().optional().describe("Restrict search to descendants of this document. Omit to search the entire tree.")
|
|
22005
|
-
}, async ({ query, rootId }) => {
|
|
22596
|
+
}, async ({ query, where, rootId }) => {
|
|
22597
|
+
const label = query ?? (where ? Object.keys(where).join(",") : "find");
|
|
22006
22598
|
server.setAutoStatus("searching");
|
|
22007
22599
|
server.setActiveToolCall({
|
|
22008
22600
|
name: "find_document",
|
|
22009
|
-
target:
|
|
22601
|
+
target: label
|
|
22010
22602
|
});
|
|
22603
|
+
if (!query && (!where || Object.keys(where).length === 0)) return {
|
|
22604
|
+
content: [{
|
|
22605
|
+
type: "text",
|
|
22606
|
+
text: "find_document needs at least one of `query` (label substring) or `where` (metadata predicates)."
|
|
22607
|
+
}],
|
|
22608
|
+
isError: true
|
|
22609
|
+
};
|
|
22011
22610
|
await server.ensureSpaceActive(rootId);
|
|
22012
22611
|
const treeMap = server.getTreeMap();
|
|
22013
22612
|
if (!treeMap) return { content: [{
|
|
@@ -22015,9 +22614,13 @@ function registerTreeTools(mcp, server, validator = null) {
|
|
|
22015
22614
|
text: "Not connected"
|
|
22016
22615
|
}] };
|
|
22017
22616
|
const entries = readEntries$1(treeMap, server.rootDocId);
|
|
22018
|
-
const lowerQuery = query
|
|
22617
|
+
const lowerQuery = query?.toLowerCase();
|
|
22019
22618
|
const normalizedRoot = normalizeRootId$1(rootId, server);
|
|
22020
|
-
const matches = (normalizedRoot ? descendantsOf(entries, normalizedRoot) : entries).filter((e) =>
|
|
22619
|
+
const matches = (normalizedRoot ? descendantsOf(entries, normalizedRoot) : entries).filter((e) => {
|
|
22620
|
+
if (lowerQuery !== void 0 && !e.label.toLowerCase().includes(lowerQuery)) return false;
|
|
22621
|
+
if (where && !matchesWhere(e, where)) return false;
|
|
22622
|
+
return true;
|
|
22623
|
+
});
|
|
22021
22624
|
const byId = new Map(entries.map((e) => [e.id, e]));
|
|
22022
22625
|
const results = matches.map((entry) => {
|
|
22023
22626
|
const path = [];
|
|
@@ -22040,7 +22643,7 @@ function registerTreeTools(mcp, server, validator = null) {
|
|
|
22040
22643
|
});
|
|
22041
22644
|
if (results.length === 0) return { content: [{
|
|
22042
22645
|
type: "text",
|
|
22043
|
-
text: `No documents found matching "${query}". Try get_document_tree to see the full hierarchy.`
|
|
22646
|
+
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.`
|
|
22044
22647
|
}] };
|
|
22045
22648
|
return { content: [{
|
|
22046
22649
|
type: "text",
|
|
@@ -22404,7 +23007,13 @@ function registerTreeTools(mcp, server, validator = null) {
|
|
|
22404
23007
|
* Abracadabra MCP Server — entry point.
|
|
22405
23008
|
*
|
|
22406
23009
|
* Environment variables:
|
|
22407
|
-
* ABRA_URL (
|
|
23010
|
+
* ABRA_URL (optional) — Server URL (e.g. http://localhost:1234).
|
|
23011
|
+
* When set, connects to it at boot (back-compat) and
|
|
23012
|
+
* remembers it in the server registry. When unset, the
|
|
23013
|
+
* agent boots idle and connects on request via the
|
|
23014
|
+
* connect_server tool (or to the registry's default).
|
|
23015
|
+
* ABRA_SERVERS_FILE — Path to the server registry JSON
|
|
23016
|
+
* (default: ~/.abracadabra/servers.json)
|
|
22408
23017
|
* ABRA_AGENT_NAME — Display name (default: "AI Assistant")
|
|
22409
23018
|
* ABRA_AGENT_COLOR — HSL color for presence (default: "hsl(270, 80%, 60%)")
|
|
22410
23019
|
* ABRA_INVITE_CODE — Invite code for first-run registration (grants role)
|
|
@@ -22427,10 +23036,6 @@ function registerTreeTools(mcp, server, validator = null) {
|
|
|
22427
23036
|
*/
|
|
22428
23037
|
async function main() {
|
|
22429
23038
|
const url = process.env.ABRA_URL;
|
|
22430
|
-
if (!url) {
|
|
22431
|
-
console.error("Missing required environment variable: ABRA_URL");
|
|
22432
|
-
process.exit(1);
|
|
22433
|
-
}
|
|
22434
23039
|
const rawMode = (process.env.ABRA_AGENT_TRIGGER_MODE ?? "mention+task").trim().toLowerCase();
|
|
22435
23040
|
const validModes = [
|
|
22436
23041
|
"all",
|
|
@@ -22442,16 +23047,36 @@ async function main() {
|
|
|
22442
23047
|
if (rawMode && !validModes.includes(rawMode)) console.error(`[abracadabra-mcp] Invalid ABRA_AGENT_TRIGGER_MODE="${rawMode}", falling back to "mention+task"`);
|
|
22443
23048
|
const aliasEnv = process.env.ABRA_AGENT_MENTION_ALIASES;
|
|
22444
23049
|
const mentionAliases = aliasEnv ? aliasEnv.split(",").map((a) => a.trim()).filter((a) => a.length > 0) : void 0;
|
|
22445
|
-
const
|
|
22446
|
-
|
|
23050
|
+
const registry = await loadServerRegistry();
|
|
23051
|
+
const { homedir } = await import("node:os");
|
|
23052
|
+
const { join } = await import("node:path");
|
|
23053
|
+
const legacyKeyFile = process.env.ABRA_KEY_FILE ?? join(homedir(), ".abracadabra", "agent.key");
|
|
23054
|
+
let workingRegistry = registry;
|
|
23055
|
+
let initialTarget = registry.defaultAlias ?? null;
|
|
23056
|
+
if (url) {
|
|
23057
|
+
const normalizedUrl = url.replace(/\/+$/, "");
|
|
23058
|
+
const existing = Object.values(workingRegistry.servers).find((p) => p.url === normalizedUrl);
|
|
23059
|
+
if (existing) initialTarget = existing.alias;
|
|
23060
|
+
else {
|
|
23061
|
+
const migrated = await migrateLegacyDefault(workingRegistry, url, legacyKeyFile);
|
|
23062
|
+
workingRegistry = migrated.migrated ? migrated.registry : addServer(workingRegistry, {
|
|
23063
|
+
alias: "default",
|
|
23064
|
+
url: normalizedUrl,
|
|
23065
|
+
keyFile: legacyKeyFile
|
|
23066
|
+
});
|
|
23067
|
+
initialTarget = workingRegistry.defaultAlias ?? Object.keys(workingRegistry.servers)[0] ?? null;
|
|
23068
|
+
await saveServerRegistry(workingRegistry).catch(() => {});
|
|
23069
|
+
}
|
|
23070
|
+
}
|
|
23071
|
+
const manager = new ServerManager(workingRegistry, {
|
|
22447
23072
|
agentName: process.env.ABRA_AGENT_NAME,
|
|
22448
23073
|
agentColor: process.env.ABRA_AGENT_COLOR,
|
|
22449
23074
|
inviteCode: process.env.ABRA_INVITE_CODE,
|
|
22450
|
-
keyFile: process.env.ABRA_KEY_FILE,
|
|
22451
23075
|
triggerMode,
|
|
22452
23076
|
mentionAliases
|
|
22453
23077
|
});
|
|
22454
|
-
|
|
23078
|
+
const server = createActiveServerProxy(manager);
|
|
23079
|
+
console.error(`[abracadabra-mcp] Trigger mode: ${triggerMode}; aliases: ${mentionAliases?.join(", ") ?? process.env.ABRA_AGENT_NAME ?? "AI Assistant"}`);
|
|
22455
23080
|
let schemaValidator = null;
|
|
22456
23081
|
const schemaBundlePath = process.env.ABRA_MCP_SCHEMA_BUNDLE;
|
|
22457
23082
|
if (schemaBundlePath && schemaBundlePath.trim().length > 0) try {
|
|
@@ -22511,15 +23136,18 @@ Read the resource at abracadabra://agent-guide for the complete guide covering p
|
|
|
22511
23136
|
registerAwarenessTools(mcp, server);
|
|
22512
23137
|
registerChannelTools(mcp, server);
|
|
22513
23138
|
registerSvgTools(mcp, server);
|
|
23139
|
+
registerServerTools(mcp, manager);
|
|
22514
23140
|
registerAgentGuide(mcp);
|
|
22515
23141
|
registerTreeResource(mcp, server);
|
|
22516
23142
|
registerServerInfoResource(mcp, server);
|
|
22517
|
-
try {
|
|
22518
|
-
await
|
|
23143
|
+
if (initialTarget) try {
|
|
23144
|
+
const outcome = await manager.connectServer(initialTarget);
|
|
23145
|
+
if (outcome.result.status === "connected") console.error(`[abracadabra-mcp] Connected to "${initialTarget}" as ${outcome.result.publicKey.slice(0, 12)}…`);
|
|
23146
|
+
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.`);
|
|
22519
23147
|
} catch (error) {
|
|
22520
|
-
console.error(`[abracadabra-mcp]
|
|
22521
|
-
process.exit(1);
|
|
23148
|
+
console.error(`[abracadabra-mcp] Initial connect to "${initialTarget}" failed: ${error.message}. Booting idle — use connect_server.`);
|
|
22522
23149
|
}
|
|
23150
|
+
else console.error("[abracadabra-mcp] No server configured — booting idle. Use connect_server to connect.");
|
|
22523
23151
|
const hookBridge = new HookBridge(server);
|
|
22524
23152
|
try {
|
|
22525
23153
|
const hookPort = await hookBridge.start();
|
|
@@ -22530,12 +23158,12 @@ Read the resource at abracadabra://agent-guide for the complete guide covering p
|
|
|
22530
23158
|
registerHookTools(mcp, hookBridge);
|
|
22531
23159
|
const transport = new StdioServerTransport();
|
|
22532
23160
|
await mcp.connect(transport);
|
|
22533
|
-
|
|
23161
|
+
manager.attachMcp(mcp);
|
|
22534
23162
|
console.error("[abracadabra-mcp] MCP server running on stdio");
|
|
22535
23163
|
const shutdown = async () => {
|
|
22536
23164
|
console.error("[abracadabra-mcp] Shutting down...");
|
|
22537
23165
|
await hookBridge.destroy();
|
|
22538
|
-
await
|
|
23166
|
+
await manager.disconnect();
|
|
22539
23167
|
process.exit(0);
|
|
22540
23168
|
};
|
|
22541
23169
|
process.on("SIGINT", shutdown);
|