@abraca/mcp 2.39.0 → 2.41.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
  /**
@@ -22043,6 +22216,96 @@ function registerMetaTools(mcp, server, validator = null) {
22043
22216
  });
22044
22217
  }
22045
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
+
22046
22309
  //#endregion
22047
22310
  //#region packages/mcp/src/utils/sanitizeSvg.ts
22048
22311
  /**
@@ -22755,7 +23018,13 @@ function registerTreeTools(mcp, server, validator = null) {
22755
23018
  * Abracadabra MCP Server — entry point.
22756
23019
  *
22757
23020
  * Environment variables:
22758
- * 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)
22759
23028
  * ABRA_AGENT_NAME — Display name (default: "AI Assistant")
22760
23029
  * ABRA_AGENT_COLOR — HSL color for presence (default: "hsl(270, 80%, 60%)")
22761
23030
  * ABRA_INVITE_CODE — Invite code for first-run registration (grants role)
@@ -22778,10 +23047,6 @@ function registerTreeTools(mcp, server, validator = null) {
22778
23047
  */
22779
23048
  async function main() {
22780
23049
  const url = process.env.ABRA_URL;
22781
- if (!url) {
22782
- console.error("Missing required environment variable: ABRA_URL");
22783
- process.exit(1);
22784
- }
22785
23050
  const rawMode = (process.env.ABRA_AGENT_TRIGGER_MODE ?? "mention+task").trim().toLowerCase();
22786
23051
  const validModes = [
22787
23052
  "all",
@@ -22793,16 +23058,36 @@ async function main() {
22793
23058
  if (rawMode && !validModes.includes(rawMode)) console.error(`[abracadabra-mcp] Invalid ABRA_AGENT_TRIGGER_MODE="${rawMode}", falling back to "mention+task"`);
22794
23059
  const aliasEnv = process.env.ABRA_AGENT_MENTION_ALIASES;
22795
23060
  const mentionAliases = aliasEnv ? aliasEnv.split(",").map((a) => a.trim()).filter((a) => a.length > 0) : void 0;
22796
- const server = new AbracadabraMCPServer({
22797
- 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, {
22798
23083
  agentName: process.env.ABRA_AGENT_NAME,
22799
23084
  agentColor: process.env.ABRA_AGENT_COLOR,
22800
23085
  inviteCode: process.env.ABRA_INVITE_CODE,
22801
- keyFile: process.env.ABRA_KEY_FILE,
22802
23086
  triggerMode,
22803
23087
  mentionAliases
22804
23088
  });
22805
- 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"}`);
22806
23091
  let schemaValidator = null;
22807
23092
  const schemaBundlePath = process.env.ABRA_MCP_SCHEMA_BUNDLE;
22808
23093
  if (schemaBundlePath && schemaBundlePath.trim().length > 0) try {
@@ -22862,15 +23147,18 @@ Read the resource at abracadabra://agent-guide for the complete guide covering p
22862
23147
  registerAwarenessTools(mcp, server);
22863
23148
  registerChannelTools(mcp, server);
22864
23149
  registerSvgTools(mcp, server);
23150
+ registerServerTools(mcp, manager);
22865
23151
  registerAgentGuide(mcp);
22866
23152
  registerTreeResource(mcp, server);
22867
23153
  registerServerInfoResource(mcp, server);
22868
- try {
22869
- 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.`);
22870
23158
  } catch (error) {
22871
- console.error(`[abracadabra-mcp] Failed to connect: ${error.message}`);
22872
- process.exit(1);
23159
+ console.error(`[abracadabra-mcp] Initial connect to "${initialTarget}" failed: ${error.message}. Booting idle — use connect_server.`);
22873
23160
  }
23161
+ else console.error("[abracadabra-mcp] No server configured — booting idle. Use connect_server to connect.");
22874
23162
  const hookBridge = new HookBridge(server);
22875
23163
  try {
22876
23164
  const hookPort = await hookBridge.start();
@@ -22881,12 +23169,12 @@ Read the resource at abracadabra://agent-guide for the complete guide covering p
22881
23169
  registerHookTools(mcp, hookBridge);
22882
23170
  const transport = new StdioServerTransport();
22883
23171
  await mcp.connect(transport);
22884
- server.startChannelNotifications(mcp);
23172
+ manager.attachMcp(mcp);
22885
23173
  console.error("[abracadabra-mcp] MCP server running on stdio");
22886
23174
  const shutdown = async () => {
22887
23175
  console.error("[abracadabra-mcp] Shutting down...");
22888
23176
  await hookBridge.destroy();
22889
- await server.destroy();
23177
+ await manager.disconnect();
22890
23178
  process.exit(0);
22891
23179
  };
22892
23180
  process.on("SIGINT", shutdown);