@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.
@@ -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,7 +9,6 @@ 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
13
  import { appendJsonNodes, markdownToFragmentNodes, parseFrontmatter, populateYDocFromMarkdown, yjsToMarkdown } from "@abraca/convert";
14
14
 
@@ -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
  /**
@@ -22035,6 +22208,96 @@ function registerMetaTools(mcp, server, validator = null) {
22035
22208
  });
22036
22209
  }
22037
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
+
22038
22301
  //#endregion
22039
22302
  //#region packages/mcp/src/utils/sanitizeSvg.ts
22040
22303
  /**
@@ -22744,7 +23007,13 @@ function registerTreeTools(mcp, server, validator = null) {
22744
23007
  * Abracadabra MCP Server — entry point.
22745
23008
  *
22746
23009
  * Environment variables:
22747
- * ABRA_URL (required) — Server URL (e.g. http://localhost:1234)
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)
22748
23017
  * ABRA_AGENT_NAME — Display name (default: "AI Assistant")
22749
23018
  * ABRA_AGENT_COLOR — HSL color for presence (default: "hsl(270, 80%, 60%)")
22750
23019
  * ABRA_INVITE_CODE — Invite code for first-run registration (grants role)
@@ -22767,10 +23036,6 @@ function registerTreeTools(mcp, server, validator = null) {
22767
23036
  */
22768
23037
  async function main() {
22769
23038
  const url = process.env.ABRA_URL;
22770
- if (!url) {
22771
- console.error("Missing required environment variable: ABRA_URL");
22772
- process.exit(1);
22773
- }
22774
23039
  const rawMode = (process.env.ABRA_AGENT_TRIGGER_MODE ?? "mention+task").trim().toLowerCase();
22775
23040
  const validModes = [
22776
23041
  "all",
@@ -22782,16 +23047,36 @@ async function main() {
22782
23047
  if (rawMode && !validModes.includes(rawMode)) console.error(`[abracadabra-mcp] Invalid ABRA_AGENT_TRIGGER_MODE="${rawMode}", falling back to "mention+task"`);
22783
23048
  const aliasEnv = process.env.ABRA_AGENT_MENTION_ALIASES;
22784
23049
  const mentionAliases = aliasEnv ? aliasEnv.split(",").map((a) => a.trim()).filter((a) => a.length > 0) : void 0;
22785
- const server = new AbracadabraMCPServer({
22786
- url,
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, {
22787
23072
  agentName: process.env.ABRA_AGENT_NAME,
22788
23073
  agentColor: process.env.ABRA_AGENT_COLOR,
22789
23074
  inviteCode: process.env.ABRA_INVITE_CODE,
22790
- keyFile: process.env.ABRA_KEY_FILE,
22791
23075
  triggerMode,
22792
23076
  mentionAliases
22793
23077
  });
22794
- console.error(`[abracadabra-mcp] Trigger mode: ${triggerMode}; aliases: ${server.mentionAliases.join(", ")}`);
23078
+ const server = createActiveServerProxy(manager);
23079
+ console.error(`[abracadabra-mcp] Trigger mode: ${triggerMode}; aliases: ${mentionAliases?.join(", ") ?? process.env.ABRA_AGENT_NAME ?? "AI Assistant"}`);
22795
23080
  let schemaValidator = null;
22796
23081
  const schemaBundlePath = process.env.ABRA_MCP_SCHEMA_BUNDLE;
22797
23082
  if (schemaBundlePath && schemaBundlePath.trim().length > 0) try {
@@ -22851,15 +23136,18 @@ Read the resource at abracadabra://agent-guide for the complete guide covering p
22851
23136
  registerAwarenessTools(mcp, server);
22852
23137
  registerChannelTools(mcp, server);
22853
23138
  registerSvgTools(mcp, server);
23139
+ registerServerTools(mcp, manager);
22854
23140
  registerAgentGuide(mcp);
22855
23141
  registerTreeResource(mcp, server);
22856
23142
  registerServerInfoResource(mcp, server);
22857
- try {
22858
- await server.connect();
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.`);
22859
23147
  } catch (error) {
22860
- console.error(`[abracadabra-mcp] Failed to connect: ${error.message}`);
22861
- process.exit(1);
23148
+ console.error(`[abracadabra-mcp] Initial connect to "${initialTarget}" failed: ${error.message}. Booting idle — use connect_server.`);
22862
23149
  }
23150
+ else console.error("[abracadabra-mcp] No server configured — booting idle. Use connect_server to connect.");
22863
23151
  const hookBridge = new HookBridge(server);
22864
23152
  try {
22865
23153
  const hookPort = await hookBridge.start();
@@ -22870,12 +23158,12 @@ Read the resource at abracadabra://agent-guide for the complete guide covering p
22870
23158
  registerHookTools(mcp, hookBridge);
22871
23159
  const transport = new StdioServerTransport();
22872
23160
  await mcp.connect(transport);
22873
- server.startChannelNotifications(mcp);
23161
+ manager.attachMcp(mcp);
22874
23162
  console.error("[abracadabra-mcp] MCP server running on stdio");
22875
23163
  const shutdown = async () => {
22876
23164
  console.error("[abracadabra-mcp] Shutting down...");
22877
23165
  await hookBridge.destroy();
22878
- await server.destroy();
23166
+ await manager.disconnect();
22879
23167
  process.exit(0);
22880
23168
  };
22881
23169
  process.on("SIGINT", shutdown);