@abraca/mcp 2.88.0 → 2.91.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/src/index.ts DELETED
@@ -1,305 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Abracadabra MCP Server — entry point.
4
- *
5
- * Environment variables:
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)
13
- * ABRA_AGENT_NAME — Display name (default: "AI Assistant")
14
- * ABRA_AGENT_COLOR — HSL color for presence (default: "hsl(270, 80%, 60%)")
15
- * ABRA_INVITE_CODE — Invite code for first-run registration (grants role)
16
- * ABRA_KEY_FILE — Path to Ed25519 key file (default: ~/.abracadabra/agent.key)
17
- * ABRA_AGENT_TRIGGER_MODE — When to respond in group chats:
18
- * all → every message (legacy)
19
- * mention → only when @<alias> is used
20
- * task → only ai:task awareness events
21
- * mention+task → mention OR ai:task (default)
22
- * DMs always trigger regardless of mode.
23
- * ABRA_AGENT_MENTION_ALIASES — Comma-separated aliases for @mentions
24
- * (default: [ABRA_AGENT_NAME])
25
- * ABRA_MCP_SCHEMA_BUNDLE — (optional) Path to a JSON Schema bundle
26
- * emitted by `@abraca/schema`. When set,
27
- * update_metadata + create_document
28
- * reject `meta` payloads that fail
29
- * validation against the resolved doc-type's
30
- * schema before forwarding to the server.
31
- * When unset, behaviour is unchanged.
32
- */
33
- import {
34
- addServer,
35
- loadServerRegistry,
36
- migrateLegacyDefault,
37
- saveServerRegistry,
38
- } from "@abraca/dabra";
39
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
40
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
41
- import { createActiveServerProxy } from "./active-server.ts";
42
- import { HookBridge } from "./hook-bridge.ts";
43
- import { registerAgentGuide } from "./resources/agent-guide.ts";
44
- import { registerServerInfoResource } from "./resources/server-info.ts";
45
- import { registerTreeResource } from "./resources/tree-resource.ts";
46
- import { loadSchemaBundle, SchemaBundleLoadError } from "./schema/loader.ts";
47
- import type { SchemaBundleValidator } from "./schema/validator.ts";
48
- import { ServerManager } from "./server-manager.ts";
49
- import { type TriggerMode } from "./server.ts";
50
- import { wrapToolsWithDetail } from "./tool-detail.ts";
51
- import { registerAwarenessTools } from "./tools/awareness.ts";
52
- import { registerChannelTools } from "./tools/channel.ts";
53
- import { registerContentTools } from "./tools/content.ts";
54
- import { registerFileTools } from "./tools/files.ts";
55
- import { registerHookTools } from "./tools/hooks.ts";
56
- import { registerMetaTools } from "./tools/meta.ts";
57
- import { registerServerTools } from "./tools/servers.ts";
58
- import { registerSvgTools } from "./tools/svg.ts";
59
- import { registerTreeTools } from "./tools/tree.ts";
60
-
61
- async function main() {
62
- const url = process.env.ABRA_URL;
63
-
64
- // Parse trigger mode (defaults to mention+task)
65
- const rawMode = (process.env.ABRA_AGENT_TRIGGER_MODE ?? "mention+task")
66
- .trim()
67
- .toLowerCase();
68
- const validModes: TriggerMode[] = ["all", "mention", "task", "mention+task"];
69
- const triggerMode = (validModes as string[]).includes(rawMode)
70
- ? (rawMode as TriggerMode)
71
- : "mention+task";
72
- if (rawMode && !(validModes as string[]).includes(rawMode)) {
73
- console.error(
74
- `[abracadabra-mcp] Invalid ABRA_AGENT_TRIGGER_MODE="${rawMode}", falling back to "mention+task"`,
75
- );
76
- }
77
-
78
- const aliasEnv = process.env.ABRA_AGENT_MENTION_ALIASES;
79
- const mentionAliases: string[] | undefined = aliasEnv
80
- ? aliasEnv
81
- .split(",")
82
- .map((a: string) => a.trim())
83
- .filter((a: string) => a.length > 0)
84
- : undefined;
85
-
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, {
132
- agentName: process.env.ABRA_AGENT_NAME,
133
- agentColor: process.env.ABRA_AGENT_COLOR,
134
- inviteCode: process.env.ABRA_INVITE_CODE,
135
- triggerMode,
136
- mentionAliases,
137
- });
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
-
144
- console.error(
145
- `[abracadabra-mcp] Trigger mode: ${triggerMode}; aliases: ${mentionAliases?.join(", ") ?? process.env.ABRA_AGENT_NAME ?? "AI Assistant"}`,
146
- );
147
-
148
- // Optional schema bundle. When set, update_metadata + create_document validate
149
- // `meta` against the resolved doc-type's schema before forwarding. When unset,
150
- // behaviour is identical to today (Rules 2 + 4 in feedback_schema_free_core.md).
151
- let schemaValidator: SchemaBundleValidator | null = null;
152
- const schemaBundlePath = process.env.ABRA_MCP_SCHEMA_BUNDLE;
153
- if (schemaBundlePath && schemaBundlePath.trim().length > 0) {
154
- try {
155
- schemaValidator = loadSchemaBundle(schemaBundlePath);
156
- console.error(
157
- `[abracadabra-mcp] Loaded schema bundle from ${schemaBundlePath}; known doc-types: ${schemaValidator.knownTypes.join(", ")}`,
158
- );
159
- } catch (err) {
160
- const msg =
161
- err instanceof SchemaBundleLoadError ? err.message : String(err);
162
- console.error(`[abracadabra-mcp] ${msg}`);
163
- process.exit(1);
164
- }
165
- }
166
-
167
- // Create MCP server with channel capability
168
- const mcp = new McpServer(
169
- { name: "abracadabra", version: "1.0.0" },
170
- {
171
- capabilities: { experimental: { "claude/channel": {} } },
172
- instructions: `Abracadabra is a CRDT collaboration platform where everything is a document in a tree.
173
-
174
- ## CRITICAL: Responding to Channel Events
175
- The user CANNOT see your plain text output — they only see messages sent via MCP tools. When you receive a channel event:
176
- - **Chat messages**: Use send_chat_message with the SAME channel for ALL replies AND progress updates.
177
- - **AI tasks**: Use reply tool for the final response; use send_chat_message for progress updates.
178
- - For multi-step work, send brief status updates via send_chat_message so the user sees progress.
179
- - NEVER output plain text as a response or status update — it is invisible to the user.
180
-
181
- ## Quick Start Workflow
182
- 1. list_spaces → note the active space's doc_id (this is the hub/root document)
183
- 2. get_document_tree(rootId: hubDocId) → see the FULL hierarchy before doing anything
184
- 3. find_document(query) → search for a document by name if you know what you're looking for
185
- 4. read_document / write_document / create_document → operate on specific documents
186
-
187
- ## Key Concepts
188
- - Documents form a tree. A kanban board's columns are child documents; cards are grandchildren.
189
- - A document's label IS its display name everywhere. Children ARE the content (not just the body text).
190
- - Page types are views over the SAME tree — switching types preserves data.
191
- - An empty markdown body does NOT mean empty content — always check the children array.
192
- - Use ![[docId]] in content to embed another document, or [[docId|label]] for inline links.
193
-
194
- ## Finding Documents
195
- - list_documents only shows ONE level of children. Use find_document to search by name, or get_document_tree to see the full hierarchy.
196
- - NEVER conclude a document doesn't exist after only checking root-level documents.
197
-
198
- ## Rules
199
- - Always call list_spaces first to get the hub doc ID before creating documents.
200
- - Always call get_document_tree to understand existing structure before creating documents.
201
- - Use Lucide icon names in kebab-case (e.g. "star", "code-2") for meta.icon — NEVER emoji.
202
- - Never rename or write content to the hub document itself.
203
- - Use universal meta keys (color, icon, dateStart) — never prefix with page type names.
204
-
205
- ## Full Reference
206
- Read the resource at abracadabra://agent-guide for the complete guide covering page type schemas, metadata reference, awareness/presence, content structure, and detailed examples.`,
207
- },
208
- );
209
-
210
- // Wrap mcp.tool ONCE so every tool invocation records an expandable detail
211
- // (the arguments it was called with + the text it returned) onto its
212
- // tool-history entry. This is what lets the cou-sh chat cards expand to show
213
- // "which doc / which tree / what it found" — the same way built-in Claude
214
- // tools (bash / read / edit) already expand via the hook-bridge. The pill
215
- // itself is still emitted by each tool's own setActiveToolCall; we only
216
- // enrich it after the handler resolves. Must run before the register* calls.
217
- wrapToolsWithDetail(mcp, server);
218
-
219
- // Register tools
220
- registerTreeTools(mcp, server, schemaValidator);
221
- registerContentTools(mcp, server);
222
- registerMetaTools(mcp, server, schemaValidator);
223
- registerFileTools(mcp, server);
224
- registerAwarenessTools(mcp, server);
225
- registerChannelTools(mcp, server);
226
- registerSvgTools(mcp, server);
227
- registerServerTools(mcp, manager);
228
-
229
- // Register resources
230
- registerAgentGuide(mcp);
231
- registerTreeResource(mcp, server);
232
- registerServerInfoResource(mcp, server);
233
-
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
- );
258
- }
259
-
260
- // Start Claude Code hook bridge (HTTP server for activity events)
261
- const hookBridge = new HookBridge(server);
262
- try {
263
- const hookPort = await hookBridge.start();
264
- console.error(
265
- `[abracadabra-mcp] Hook bridge listening on port ${hookPort}`,
266
- );
267
- } catch (error: any) {
268
- console.error(
269
- `[abracadabra-mcp] Hook bridge failed to start: ${error.message}`,
270
- );
271
- }
272
-
273
- // Register hook config tool (must be after bridge starts so port is available)
274
- registerHookTools(mcp, hookBridge);
275
-
276
- // Start MCP stdio transport
277
- const transport = new StdioServerTransport();
278
- await mcp.connect(transport);
279
-
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);
284
- console.error("[abracadabra-mcp] MCP server running on stdio");
285
-
286
- // Graceful shutdown
287
- const shutdown = async () => {
288
- console.error("[abracadabra-mcp] Shutting down...");
289
- await hookBridge.destroy();
290
- await manager.disconnect();
291
- process.exit(0);
292
- };
293
-
294
- process.on("SIGINT", shutdown);
295
- process.on("SIGTERM", shutdown);
296
- }
297
-
298
- main().catch((error) => {
299
- console.error("[abracadabra-mcp] Fatal error:", error);
300
- process.exit(1);
301
- });
302
-
303
- export type { MCPServerConfig } from "./server.ts";
304
- // Re-export for library usage
305
- export { AbracadabraMCPServer } from "./server.ts";
package/src/mentions.ts DELETED
@@ -1,42 +0,0 @@
1
- /**
2
- * Mention parsing for chat messages.
3
- *
4
- * Recognizes `@alias` tokens (case-insensitive, word-boundary) so the agent
5
- * can decide whether a group-chat message is directed at it.
6
- */
7
-
8
- /** Escape regex metacharacters in an alias string. */
9
- function escapeRegex(s: string): string {
10
- return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
11
- }
12
-
13
- /**
14
- * Build a regex that matches `@<alias>` for any of the given aliases.
15
- * Requires a non-word char (or start) before `@` and a word boundary after the alias
16
- * so `@Claude` matches but `email@claudesomething` does not.
17
- */
18
- function buildMentionRegex(aliases: string[]): RegExp | null {
19
- const cleaned = aliases.map(a => a.trim()).filter(a => a.length > 0)
20
- if (cleaned.length === 0) return null
21
- const alt = cleaned.map(escapeRegex).join('|')
22
- return new RegExp(`(?:^|[^\\w@])@(?:${alt})\\b`, 'i')
23
- }
24
-
25
- /** Returns true if `text` contains `@alias` for any alias (case-insensitive). */
26
- export function containsMention(text: string, aliases: string[]): boolean {
27
- const re = buildMentionRegex(aliases)
28
- if (!re) return false
29
- return re.test(text)
30
- }
31
-
32
- /**
33
- * Remove `@alias` tokens from the text. Leaves surrounding whitespace tidy so
34
- * the cleaned prompt reads naturally (e.g. `"@Claude help"` → `"help"`).
35
- */
36
- export function stripMention(text: string, aliases: string[]): string {
37
- const cleaned = aliases.map(a => a.trim()).filter(a => a.length > 0)
38
- if (cleaned.length === 0) return text
39
- const alt = cleaned.map(escapeRegex).join('|')
40
- const re = new RegExp(`(^|\\s)@(?:${alt})\\b[,:]?\\s*`, 'gi')
41
- return text.replace(re, (_m, lead) => (lead ? ' ' : '')).replace(/\s{2,}/g, ' ').trim()
42
- }