@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abraca/mcp",
3
- "version": "2.38.0",
3
+ "version": "2.40.0",
4
4
  "description": "MCP server for Abracadabra — AI agent collaboration on CRDT documents",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -35,7 +35,7 @@
35
35
  "y-protocols": "^1.0.6",
36
36
  "yjs": "^13.6.8",
37
37
  "zod": "^4.3.6",
38
- "@abraca/convert": "2.38.0"
38
+ "@abraca/convert": "2.40.0"
39
39
  },
40
40
  "scripts": {
41
41
  "test": "node --no-warnings --conditions=source --experimental-transform-types --test 'tests/*.test.ts'"
@@ -0,0 +1,90 @@
1
+ /**
2
+ * active-server — a late-binding forwarding proxy over the manager's *currently
3
+ * active* {@link AbracadabraMCPServer} connection.
4
+ *
5
+ * Tools and the hook-bridge capture a `server` reference once at registration.
6
+ * With multi-server support the active connection can change at runtime
7
+ * (`connect_server`/`switch_server`), so a fixed reference would go stale. This
8
+ * proxy forwards every access to `manager.active` at *call time*, so a single
9
+ * stable object behaves like "whatever server is active right now".
10
+ *
11
+ * When nothing is connected it forwards to {@link DISCONNECTED} — a safe stub
12
+ * that returns empty/null data, makes status/awareness calls no-ops (so the
13
+ * hook-bridge never throws), and reports "not found" for space resolution. The
14
+ * net effect is that every tool's existing `if (!rootProvider) return "Not
15
+ * connected"` guard fires naturally, and the agent is told to connect first.
16
+ */
17
+
18
+ import type { ServerManager } from "./server-manager.ts";
19
+ import type { AbracadabraMCPServer } from "./server.ts";
20
+
21
+ const NOT_CONNECTED =
22
+ "No server connected. Use connect_server (or list_servers) first.";
23
+
24
+ /**
25
+ * Safe defaults used while no server is active. Mirrors the slice of the
26
+ * `AbracadabraMCPServer` surface that tools + the hook-bridge actually touch
27
+ * (see the `server.*` usage survey). Data getters/methods return empty/null so
28
+ * existing guards trip; void status methods no-op; genuine data ops that need a
29
+ * live connection throw a clear message.
30
+ */
31
+ const DISCONNECTED: Record<string, unknown> = {
32
+ // ── plain getters ──
33
+ client: undefined,
34
+ serverInfo: null,
35
+ rootDocId: null,
36
+ rootDocument: null,
37
+ rootYProvider: null,
38
+ spaces: [],
39
+ userId: null,
40
+ agentName: "AI Assistant",
41
+ agentColor: "hsl(270, 80%, 60%)",
42
+
43
+ // ── data accessors (called as functions) ──
44
+ getTreeMap: () => null,
45
+ getTrashMap: () => null,
46
+ getDocSummary: () => null,
47
+ getEnabledPluginNames: () => [],
48
+
49
+ // ── fire-and-forget status / awareness (must not throw) ──
50
+ setActiveToolCall: () => {},
51
+ setAutoStatus: () => {},
52
+ setWritingStatus: () => {},
53
+ sendTypingIndicator: () => {},
54
+ recordToolDetail: () => {},
55
+ clearAiTask: () => {},
56
+ setFocusedDoc: () => {},
57
+ setDocCursor: () => {},
58
+ startChannelNotifications: () => {},
59
+
60
+ // ── ops that genuinely require a connection ──
61
+ ensureConnected: async () => {},
62
+ // Returning false makes space-resolution guards report "not found" rather
63
+ // than crashing — the tool then surfaces a friendly message.
64
+ ensureSpaceActive: async () => false,
65
+ getChildProvider: async () => {
66
+ throw new Error(NOT_CONNECTED);
67
+ },
68
+ switchSpace: async () => {
69
+ throw new Error(NOT_CONNECTED);
70
+ },
71
+ };
72
+
73
+ /**
74
+ * Build the forwarding proxy. Pass this everywhere a tool/hook-bridge expects an
75
+ * `AbracadabraMCPServer`; it transparently tracks `manager.active`.
76
+ */
77
+ export function createActiveServerProxy(
78
+ manager: ServerManager,
79
+ ): AbracadabraMCPServer {
80
+ return new Proxy({} as AbracadabraMCPServer, {
81
+ get(_target, prop) {
82
+ const target: Record<string, unknown> =
83
+ (manager.active as unknown as Record<string, unknown>) ?? DISCONNECTED;
84
+ const value = target[prop as string];
85
+ return typeof value === "function"
86
+ ? (value as (...a: unknown[]) => unknown).bind(target)
87
+ : value;
88
+ },
89
+ });
90
+ }
package/src/index.ts CHANGED
@@ -3,7 +3,13 @@
3
3
  * Abracadabra MCP Server — entry point.
4
4
  *
5
5
  * Environment variables:
6
- * ABRA_URL (required) — Server URL (e.g. http://localhost:1234)
6
+ * ABRA_URL (optional) — Server URL (e.g. http://localhost:1234).
7
+ * When set, connects to it at boot (back-compat) and
8
+ * remembers it in the server registry. When unset, the
9
+ * agent boots idle and connects on request via the
10
+ * connect_server tool (or to the registry's default).
11
+ * ABRA_SERVERS_FILE — Path to the server registry JSON
12
+ * (default: ~/.abracadabra/servers.json)
7
13
  * ABRA_AGENT_NAME — Display name (default: "AI Assistant")
8
14
  * ABRA_AGENT_COLOR — HSL color for presence (default: "hsl(270, 80%, 60%)")
9
15
  * ABRA_INVITE_CODE — Invite code for first-run registration (grants role)
@@ -24,15 +30,23 @@
24
30
  * schema before forwarding to the server.
25
31
  * When unset, behaviour is unchanged.
26
32
  */
33
+ import {
34
+ addServer,
35
+ loadServerRegistry,
36
+ migrateLegacyDefault,
37
+ saveServerRegistry,
38
+ } from "@abraca/dabra";
27
39
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
28
40
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
41
+ import { createActiveServerProxy } from "./active-server.ts";
29
42
  import { HookBridge } from "./hook-bridge.ts";
30
43
  import { registerAgentGuide } from "./resources/agent-guide.ts";
31
44
  import { registerServerInfoResource } from "./resources/server-info.ts";
32
45
  import { registerTreeResource } from "./resources/tree-resource.ts";
33
46
  import { loadSchemaBundle, SchemaBundleLoadError } from "./schema/loader.ts";
34
47
  import type { SchemaBundleValidator } from "./schema/validator.ts";
35
- import { AbracadabraMCPServer, type TriggerMode } from "./server.ts";
48
+ import { ServerManager } from "./server-manager.ts";
49
+ import { type TriggerMode } from "./server.ts";
36
50
  import { wrapToolsWithDetail } from "./tool-detail.ts";
37
51
  import { registerAwarenessTools } from "./tools/awareness.ts";
38
52
  import { registerChannelTools } from "./tools/channel.ts";
@@ -40,17 +54,13 @@ import { registerContentTools } from "./tools/content.ts";
40
54
  import { registerFileTools } from "./tools/files.ts";
41
55
  import { registerHookTools } from "./tools/hooks.ts";
42
56
  import { registerMetaTools } from "./tools/meta.ts";
57
+ import { registerServerTools } from "./tools/servers.ts";
43
58
  import { registerSvgTools } from "./tools/svg.ts";
44
59
  import { registerTreeTools } from "./tools/tree.ts";
45
60
 
46
61
  async function main() {
47
62
  const url = process.env.ABRA_URL;
48
63
 
49
- if (!url) {
50
- console.error("Missing required environment variable: ABRA_URL");
51
- process.exit(1);
52
- }
53
-
54
64
  // Parse trigger mode (defaults to mention+task)
55
65
  const rawMode = (process.env.ABRA_AGENT_TRIGGER_MODE ?? "mention+task")
56
66
  .trim()
@@ -73,19 +83,66 @@ async function main() {
73
83
  .filter((a: string) => a.length > 0)
74
84
  : undefined;
75
85
 
76
- // Create the Abracadabra connection manager
77
- const server = new AbracadabraMCPServer({
78
- url,
86
+ // ── Server registry + multi-server manager ──────────────────────────────
87
+ // Load the on-disk registry of known servers. When ABRA_URL is set we keep
88
+ // back-compat: migrate the legacy single-key setup into a "default" profile
89
+ // (so existing identities survive) and connect to it at boot. Otherwise we
90
+ // boot idle and let the agent connect via connect_server.
91
+ const registry = await loadServerRegistry();
92
+ const { homedir } = await import("node:os");
93
+ const { join } = await import("node:path");
94
+ const legacyKeyFile =
95
+ process.env.ABRA_KEY_FILE ??
96
+ join(homedir(), ".abracadabra", "agent.key");
97
+
98
+ let workingRegistry = registry;
99
+ let initialTarget: string | null = registry.defaultAlias ?? null;
100
+
101
+ if (url) {
102
+ const normalizedUrl = url.replace(/\/+$/, "");
103
+ // Reuse an existing profile for this URL if present; else upsert one that
104
+ // keeps the legacy key file so the agent's identity doesn't change.
105
+ const existing = Object.values(workingRegistry.servers).find(
106
+ (p) => p.url === normalizedUrl,
107
+ );
108
+ if (existing) {
109
+ initialTarget = existing.alias;
110
+ } else {
111
+ const migrated = await migrateLegacyDefault(
112
+ workingRegistry,
113
+ url,
114
+ legacyKeyFile,
115
+ );
116
+ workingRegistry = migrated.migrated
117
+ ? migrated.registry
118
+ : addServer(workingRegistry, {
119
+ alias: "default",
120
+ url: normalizedUrl,
121
+ keyFile: legacyKeyFile,
122
+ });
123
+ initialTarget =
124
+ workingRegistry.defaultAlias ??
125
+ Object.keys(workingRegistry.servers)[0] ??
126
+ null;
127
+ await saveServerRegistry(workingRegistry).catch(() => {});
128
+ }
129
+ }
130
+
131
+ const manager = new ServerManager(workingRegistry, {
79
132
  agentName: process.env.ABRA_AGENT_NAME,
80
133
  agentColor: process.env.ABRA_AGENT_COLOR,
81
134
  inviteCode: process.env.ABRA_INVITE_CODE,
82
- keyFile: process.env.ABRA_KEY_FILE,
83
135
  triggerMode,
84
136
  mentionAliases,
85
137
  });
86
138
 
139
+ // Stable, late-binding handle that always forwards to the active connection.
140
+ // Tools, resources, the detail-wrapper and the hook-bridge all hold THIS so a
141
+ // connect_server / switch_server is reflected without re-registering anything.
142
+ const server = createActiveServerProxy(manager);
143
+
87
144
  console.error(
88
- `[abracadabra-mcp] Trigger mode: ${triggerMode}; aliases: ${server.mentionAliases.join(", ")}`,
145
+ `[abracadabra-mcp] Trigger mode: ${triggerMode}; aliases: ${mentionAliases?.join(", ") ?? process.env.ABRA_AGENT_NAME ?? "AI Assistant"}`,
89
146
  );
90
147
 
91
148
  // Optional schema bundle. When set, update_metadata + create_document validate
@@ -167,18 +224,37 @@ Read the resource at abracadabra://agent-guide for the complete guide covering p
167
224
  registerAwarenessTools(mcp, server);
168
225
  registerChannelTools(mcp, server);
169
226
  registerSvgTools(mcp, server);
227
+ registerServerTools(mcp, manager);
170
228
 
171
229
  // Register resources
172
230
  registerAgentGuide(mcp);
173
231
  registerTreeResource(mcp, server);
174
232
  registerServerInfoResource(mcp, server);
175
233
 
176
- // Connect to Abracadabra server
177
- try {
178
- await server.connect();
179
- } catch (error: any) {
180
- console.error(`[abracadabra-mcp] Failed to connect: ${error.message}`);
181
- process.exit(1);
234
+ // Connect to the initial server (ABRA_URL or the registry default). A failure
235
+ // here is non-fatal: the agent stays up and idle so the user can fix it via
236
+ // connect_server, which is strictly more useful than crashing the MCP.
237
+ if (initialTarget) {
238
+ try {
239
+ const outcome = await manager.connectServer(initialTarget);
240
+ if (outcome.result.status === "connected") {
241
+ console.error(
242
+ `[abracadabra-mcp] Connected to "${initialTarget}" as ${outcome.result.publicKey.slice(0, 12)}…`,
243
+ );
244
+ } else {
245
+ console.error(
246
+ `[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.`,
247
+ );
248
+ }
249
+ } catch (error: any) {
250
+ console.error(
251
+ `[abracadabra-mcp] Initial connect to "${initialTarget}" failed: ${error.message}. Booting idle — use connect_server.`,
252
+ );
253
+ }
254
+ } else {
255
+ console.error(
256
+ "[abracadabra-mcp] No server configured — booting idle. Use connect_server to connect.",
257
+ );
182
258
  }
183
259
 
184
260
  // Start Claude Code hook bridge (HTTP server for activity events)
@@ -201,15 +277,17 @@ Read the resource at abracadabra://agent-guide for the complete guide covering p
201
277
  const transport = new StdioServerTransport();
202
278
  await mcp.connect(transport);
203
279
 
204
- // Wire up real-time channel notifications (awareness → channel dispatch)
205
- server.startChannelNotifications(mcp);
280
+ // Wire up real-time channel notifications (awareness → channel dispatch).
281
+ // attachMcp wires the active connection now and re-wires any future
282
+ // connect_server/switch_server target.
283
+ manager.attachMcp(mcp);
206
284
  console.error("[abracadabra-mcp] MCP server running on stdio");
207
285
 
208
286
  // Graceful shutdown
209
287
  const shutdown = async () => {
210
288
  console.error("[abracadabra-mcp] Shutting down...");
211
289
  await hookBridge.destroy();
212
- await server.destroy();
290
+ await manager.disconnect();
213
291
  process.exit(0);
214
292
  };
215
293
 
@@ -0,0 +1,182 @@
1
+ /**
2
+ * ServerManager — owns the registry of known servers and the single *active*
3
+ * live connection (one-active model: switching tears down the previous one).
4
+ *
5
+ * The heavy per-server lifecycle (auth, space discovery, inbox observer,
6
+ * heartbeat, channel notifications, awareness) stays in {@link
7
+ * AbracadabraMCPServer}; the manager just decides *which* one is live and
8
+ * brokers connect/switch/disconnect. Tools reach the live connection through the
9
+ * forwarding proxy in `active-server.ts`, so they never hold a stale reference.
10
+ *
11
+ * The connect path is policy-aware: it probes the server first (see
12
+ * {@link loginOrRegisterWithPolicy}) so an un-registered key yields an
13
+ * actionable outcome (`needs_invite` / `registration_closed`) instead of an
14
+ * opaque error — and, crucially, surfaces the agent's public key so an admin can
15
+ * authorize it by hand when no invite token is available.
16
+ */
17
+
18
+ import {
19
+ AbracadabraClient,
20
+ type ConnectPolicyResult,
21
+ loadOrCreateKeyFile,
22
+ loginOrRegisterWithPolicy,
23
+ resolveServer,
24
+ type ServerProfile,
25
+ type ServerRegistry,
26
+ } from "@abraca/dabra";
27
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
28
+ import { AbracadabraMCPServer, type TriggerMode } from "./server.ts";
29
+
30
+ /** Defaults applied to every connection the manager builds (from env at boot). */
31
+ export interface ServerManagerDefaults {
32
+ agentName?: string;
33
+ agentColor?: string;
34
+ inviteCode?: string;
35
+ triggerMode?: TriggerMode;
36
+ mentionAliases?: string[];
37
+ }
38
+
39
+ /** Outcome of {@link ServerManager.connectServer}, formatted by the tool layer. */
40
+ export interface ConnectOutcome {
41
+ result: ConnectPolicyResult;
42
+ profile: ServerProfile;
43
+ /** True when the active connection actually changed (status === connected). */
44
+ switched: boolean;
45
+ }
46
+
47
+ export class ServerManager {
48
+ private _registry: ServerRegistry;
49
+ private readonly _defaults: ServerManagerDefaults;
50
+ private _active: AbracadabraMCPServer | null = null;
51
+ private _activeAlias: string | null = null;
52
+ private _mcp: McpServer | null = null;
53
+
54
+ constructor(registry: ServerRegistry, defaults: ServerManagerDefaults = {}) {
55
+ this._registry = registry;
56
+ this._defaults = defaults;
57
+ }
58
+
59
+ /** The currently live connection, or null when nothing is connected. */
60
+ get active(): AbracadabraMCPServer | null {
61
+ return this._active;
62
+ }
63
+
64
+ get activeAlias(): string | null {
65
+ return this._activeAlias;
66
+ }
67
+
68
+ get registry(): ServerRegistry {
69
+ return this._registry;
70
+ }
71
+
72
+ /** Provide the MCP server so channel notifications can be (re)wired on switch. */
73
+ attachMcp(mcp: McpServer): void {
74
+ this._mcp = mcp;
75
+ // Wire notifications for an already-active connection (boot path).
76
+ if (this._active) this._active.startChannelNotifications(mcp);
77
+ }
78
+
79
+ /**
80
+ * Resolve, probe, and (if authorized) connect to a server. On success the
81
+ * previous active connection is torn down and the new one becomes active.
82
+ * On `needs_invite` / `registration_closed` nothing changes — the caller
83
+ * relays the actionable message (including this agent's public key).
84
+ */
85
+ async connectServer(
86
+ target: string,
87
+ opts: { inviteCode?: string; name?: string } = {},
88
+ ): Promise<ConnectOutcome> {
89
+ const profile = await resolveServer(this._registry, target);
90
+ if (!profile) {
91
+ throw new Error(
92
+ `Unknown server "${target}". Pass a full URL (http[s]://…) or add it to the registry first.`,
93
+ );
94
+ }
95
+
96
+ // Already active? No-op switch.
97
+ if (this._active && this._activeAlias === profile.alias) {
98
+ return {
99
+ profile,
100
+ switched: false,
101
+ result: {
102
+ status: "connected",
103
+ token: "",
104
+ publicKey: this._active.userId ?? "",
105
+ serverName: profile.displayName,
106
+ needsPromotion: false,
107
+ },
108
+ };
109
+ }
110
+
111
+ const agentName = opts.name ?? profile.displayName ?? this._defaults.agentName;
112
+ const inviteCode = opts.inviteCode ?? profile.inviteCode ?? this._defaults.inviteCode;
113
+
114
+ // Policy probe on a throwaway client — cheap, and lets us bail before
115
+ // building the heavy connection when the key isn't authorized.
116
+ const probeClient = new AbracadabraClient({
117
+ url: profile.url,
118
+ persistAuth: false,
119
+ });
120
+ const keypair = await loadOrCreateKeyFile(profile.keyFile, {
121
+ defaultFileName: "agent.key",
122
+ });
123
+ const result = await loginOrRegisterWithPolicy(probeClient, keypair, {
124
+ displayName: agentName,
125
+ deviceName: "MCP Agent",
126
+ inviteCode,
127
+ });
128
+
129
+ if (result.status !== "connected") {
130
+ return { profile, switched: false, result };
131
+ }
132
+
133
+ // Authorized — build and connect the full per-server connection. It
134
+ // re-authenticates with the same (now-registered) key.
135
+ const conn = new AbracadabraMCPServer({
136
+ url: profile.url,
137
+ agentName,
138
+ agentColor: profile.color ?? this._defaults.agentColor,
139
+ inviteCode,
140
+ keyFile: profile.keyFile,
141
+ triggerMode: this._defaults.triggerMode,
142
+ mentionAliases: this._defaults.mentionAliases,
143
+ });
144
+ await conn.connect();
145
+
146
+ const prev = this._active;
147
+ this._active = conn;
148
+ this._activeAlias = profile.alias;
149
+ if (this._mcp) conn.startChannelNotifications(this._mcp);
150
+ if (prev) await prev.destroy().catch(() => {});
151
+
152
+ return { profile, switched: true, result };
153
+ }
154
+
155
+ /** Tear down the active connection (no-op when none). */
156
+ async disconnect(): Promise<void> {
157
+ const prev = this._active;
158
+ this._active = null;
159
+ this._activeAlias = null;
160
+ if (prev) await prev.destroy().catch(() => {});
161
+ }
162
+
163
+ /** Snapshot of known servers + which is active, for `list_servers`. */
164
+ listServers(): Array<{
165
+ alias: string;
166
+ url: string;
167
+ active: boolean;
168
+ isDefault: boolean;
169
+ }> {
170
+ return Object.values(this._registry.servers).map((p) => ({
171
+ alias: p.alias,
172
+ url: p.url,
173
+ active: p.alias === this._activeAlias,
174
+ isDefault: p.alias === this._registry.defaultAlias,
175
+ }));
176
+ }
177
+
178
+ /** Replace the in-memory registry (e.g. after a CLI edit reload). */
179
+ setRegistry(registry: ServerRegistry): void {
180
+ this._registry = registry;
181
+ }
182
+ }