@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.
- package/dist/abracadabra-mcp.cjs +304 -16
- package/dist/abracadabra-mcp.cjs.map +1 -1
- package/dist/abracadabra-mcp.esm.js +304 -16
- 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/servers.ts +211 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@abraca/mcp",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.41.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
|
+
"@abraca/convert": "2.41.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 (
|
|
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 {
|
|
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
|
-
//
|
|
77
|
-
|
|
78
|
-
|
|
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: ${
|
|
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
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
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
|
-
|
|
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
|
|
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
|
+
}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server tools — manage and switch between multiple Abracadabra servers.
|
|
3
|
+
*
|
|
4
|
+
* `connect_server` is policy-aware: it probes the target before committing, so
|
|
5
|
+
* an open server connects silently while an invite-only / closed server returns
|
|
6
|
+
* an actionable message that the agent relays to the user — including this
|
|
7
|
+
* agent's public key, so an admin can authorize it by hand when no token exists.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
addServer,
|
|
12
|
+
resolveServer,
|
|
13
|
+
saveServerRegistry,
|
|
14
|
+
} from "@abraca/dabra";
|
|
15
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
16
|
+
import { z } from "zod";
|
|
17
|
+
import type { ServerManager } from "../server-manager.ts";
|
|
18
|
+
|
|
19
|
+
function text(s: string, isError = false) {
|
|
20
|
+
return { content: [{ type: "text" as const, text: s }], isError };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Render a connected summary including any read-only promotion hint. */
|
|
24
|
+
function connectedMessage(
|
|
25
|
+
manager: ServerManager,
|
|
26
|
+
alias: string,
|
|
27
|
+
url: string,
|
|
28
|
+
publicKey: string,
|
|
29
|
+
role: string | undefined,
|
|
30
|
+
needsPromotion: boolean,
|
|
31
|
+
): string {
|
|
32
|
+
const active = manager.active;
|
|
33
|
+
const spaceCount = active?.spaces.length ?? 0;
|
|
34
|
+
const lines = [
|
|
35
|
+
`Connected to "${alias}" (${url}) as ${publicKey.slice(0, 12)}…`,
|
|
36
|
+
`Role: ${role ?? "unknown"}. Spaces visible: ${spaceCount}.`,
|
|
37
|
+
];
|
|
38
|
+
if (needsPromotion) {
|
|
39
|
+
lines.push(
|
|
40
|
+
`Note: this account is read-only (observer). For write access, ask the server admin to grant a write role to public key:\n ${publicKey}`,
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
lines.push("Use list_spaces / get_document_tree to start working.");
|
|
44
|
+
return lines.join("\n");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Render the "can't connect yet" message for invite-only / closed servers. */
|
|
48
|
+
function blockedMessage(
|
|
49
|
+
status: "needs_invite" | "registration_closed",
|
|
50
|
+
serverName: string | undefined,
|
|
51
|
+
url: string,
|
|
52
|
+
publicKey: string,
|
|
53
|
+
): string {
|
|
54
|
+
const who = serverName ? `"${serverName}" (${url})` : url;
|
|
55
|
+
const header =
|
|
56
|
+
status === "needs_invite"
|
|
57
|
+
? `Server ${who} is invite-only and this agent is not yet registered.`
|
|
58
|
+
: `Server ${who} has open registration disabled, so this agent cannot self-register.`;
|
|
59
|
+
return [
|
|
60
|
+
header,
|
|
61
|
+
"",
|
|
62
|
+
"Two ways forward (no connection was made):",
|
|
63
|
+
` 1. Provide a token: re-run connect_server with invite_code="…".`,
|
|
64
|
+
` 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):`,
|
|
65
|
+
` ${publicKey}`,
|
|
66
|
+
].join("\n");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function registerServerTools(mcp: McpServer, manager: ServerManager) {
|
|
70
|
+
mcp.tool(
|
|
71
|
+
"list_servers",
|
|
72
|
+
"List the Abracadabra servers known to this agent and which one is currently active. Use connect_server / switch_server to change the active server.",
|
|
73
|
+
{},
|
|
74
|
+
async () => {
|
|
75
|
+
const servers = manager.listServers();
|
|
76
|
+
if (servers.length === 0) {
|
|
77
|
+
return text(
|
|
78
|
+
'No servers configured yet. Connect to one with connect_server (e.g. server="https://your-server.example").',
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
const rows = servers.map(
|
|
82
|
+
(s) =>
|
|
83
|
+
`${s.active ? "●" : "○"} ${s.alias}${s.isDefault ? " (default)" : ""} — ${s.url}${s.active ? " [active]" : ""}`,
|
|
84
|
+
);
|
|
85
|
+
return text(rows.join("\n"));
|
|
86
|
+
},
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
mcp.tool(
|
|
90
|
+
"connect_server",
|
|
91
|
+
'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.',
|
|
92
|
+
{
|
|
93
|
+
server: z
|
|
94
|
+
.string()
|
|
95
|
+
.describe('Server alias (from list_servers) or a full URL like "https://coop.cou.sh".'),
|
|
96
|
+
invite_code: z
|
|
97
|
+
.string()
|
|
98
|
+
.optional()
|
|
99
|
+
.describe("Invite/registration token, if the server requires one."),
|
|
100
|
+
name: z
|
|
101
|
+
.string()
|
|
102
|
+
.optional()
|
|
103
|
+
.describe("Display name to present to this server (presence/registration)."),
|
|
104
|
+
},
|
|
105
|
+
async ({ server, invite_code, name }) => {
|
|
106
|
+
try {
|
|
107
|
+
const outcome = await manager.connectServer(server, {
|
|
108
|
+
inviteCode: invite_code,
|
|
109
|
+
name,
|
|
110
|
+
});
|
|
111
|
+
const { result, profile } = outcome;
|
|
112
|
+
|
|
113
|
+
if (result.status === "connected") {
|
|
114
|
+
// Remember the server so switch_server works later.
|
|
115
|
+
try {
|
|
116
|
+
const reg = addServer(manager.registry, profile);
|
|
117
|
+
manager.setRegistry(reg);
|
|
118
|
+
await saveServerRegistry(reg);
|
|
119
|
+
} catch {
|
|
120
|
+
/* registry persistence is best-effort */
|
|
121
|
+
}
|
|
122
|
+
return text(
|
|
123
|
+
connectedMessage(
|
|
124
|
+
manager,
|
|
125
|
+
profile.alias,
|
|
126
|
+
profile.url,
|
|
127
|
+
result.publicKey,
|
|
128
|
+
result.role,
|
|
129
|
+
result.needsPromotion,
|
|
130
|
+
),
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return text(
|
|
135
|
+
blockedMessage(
|
|
136
|
+
result.status,
|
|
137
|
+
result.serverName,
|
|
138
|
+
profile.url,
|
|
139
|
+
result.publicKey,
|
|
140
|
+
),
|
|
141
|
+
);
|
|
142
|
+
} catch (error: any) {
|
|
143
|
+
return text(`Error connecting to "${server}": ${error.message}`, true);
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
mcp.tool(
|
|
149
|
+
"switch_server",
|
|
150
|
+
"Switch the active connection to an already-known server (see list_servers). Equivalent to connect_server for a remembered alias.",
|
|
151
|
+
{
|
|
152
|
+
server: z.string().describe("Server alias to switch to."),
|
|
153
|
+
},
|
|
154
|
+
async ({ server }) => {
|
|
155
|
+
try {
|
|
156
|
+
const profile = await resolveServer(manager.registry, server);
|
|
157
|
+
if (!profile || !manager.registry.servers[profile.alias]) {
|
|
158
|
+
return text(
|
|
159
|
+
`Unknown server "${server}". Use list_servers to see known servers, or connect_server with a full URL.`,
|
|
160
|
+
true,
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
const outcome = await manager.connectServer(server);
|
|
164
|
+
const { result } = outcome;
|
|
165
|
+
if (result.status === "connected") {
|
|
166
|
+
return text(
|
|
167
|
+
connectedMessage(
|
|
168
|
+
manager,
|
|
169
|
+
profile.alias,
|
|
170
|
+
profile.url,
|
|
171
|
+
result.publicKey,
|
|
172
|
+
result.role,
|
|
173
|
+
result.needsPromotion,
|
|
174
|
+
),
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
return text(
|
|
178
|
+
blockedMessage(result.status, result.serverName, profile.url, result.publicKey),
|
|
179
|
+
);
|
|
180
|
+
} catch (error: any) {
|
|
181
|
+
return text(`Error switching to "${server}": ${error.message}`, true);
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
);
|
|
185
|
+
|
|
186
|
+
mcp.tool(
|
|
187
|
+
"current_server",
|
|
188
|
+
"Show which server is currently active (alias, URL, identity).",
|
|
189
|
+
{},
|
|
190
|
+
async () => {
|
|
191
|
+
const active = manager.active;
|
|
192
|
+
if (!active) {
|
|
193
|
+
return text("No server is currently connected. Use connect_server.");
|
|
194
|
+
}
|
|
195
|
+
const alias = manager.activeAlias ?? "(url)";
|
|
196
|
+
return text(
|
|
197
|
+
`Active server: ${alias} — ${active.serverInfo?.name ?? ""} ${active.config.url}\nIdentity: ${active.userId ?? "unknown"}\nSpaces visible: ${active.spaces.length}`,
|
|
198
|
+
);
|
|
199
|
+
},
|
|
200
|
+
);
|
|
201
|
+
|
|
202
|
+
mcp.tool(
|
|
203
|
+
"disconnect_server",
|
|
204
|
+
"Disconnect from the active server without connecting another. Tools will report 'no server connected' until you connect again.",
|
|
205
|
+
{},
|
|
206
|
+
async () => {
|
|
207
|
+
await manager.disconnect();
|
|
208
|
+
return text("Disconnected. Use connect_server to connect to a server.");
|
|
209
|
+
},
|
|
210
|
+
);
|
|
211
|
+
}
|