@abraca/mcp 2.34.0 → 2.35.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.34.0",
3
+ "version": "2.35.0",
4
4
  "description": "MCP server for Abracadabra — AI agent collaboration on CRDT documents",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -30,13 +30,12 @@
30
30
  "dependencies": {
31
31
  "@abraca/dabra": "^2.0.10",
32
32
  "@modelcontextprotocol/sdk": "^1.29.0",
33
- "@noble/hashes": "^2.2.0",
34
33
  "ajv": "^8.17.1",
35
34
  "ajv-formats": "^3.0.1",
36
35
  "y-protocols": "^1.0.6",
37
36
  "yjs": "^13.6.8",
38
37
  "zod": "^4.3.6",
39
- "@abraca/convert": "2.34.0"
38
+ "@abraca/convert": "2.35.0"
40
39
  },
41
40
  "scripts": {
42
41
  "test": "node --no-warnings --conditions=source --experimental-transform-types --test 'tests/*.test.ts'"
@@ -1,29 +1,10 @@
1
1
  /**
2
2
  * Dynamic resource: document tree as navigable JSON.
3
3
  */
4
- import { toPlain } from '@abraca/dabra'
4
+ import { readEntries } from '@abraca/dabra'
5
+ import type { TreeEntry } from '@abraca/dabra'
5
6
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
6
7
  import type { AbracadabraMCPServer } from '../server.ts'
7
- import type { TreeEntry } from '../converters/types.ts'
8
-
9
- function readEntries(treeMap: any): TreeEntry[] {
10
- const entries: TreeEntry[] = []
11
- treeMap.forEach((raw: any, id: string) => {
12
- // Entries are nested Y.Map values — raw field access returns undefined;
13
- // resolve via toPlain first (mirrors tree.ts:readEntries).
14
- const value = toPlain(raw) as any
15
- if (typeof value !== 'object' || value === null) return // skip non-entry keys (e.g. ":updatedAt")
16
- entries.push({
17
- id,
18
- label: value.label || 'Untitled',
19
- parentId: value.parentId ?? null,
20
- order: value.order ?? 0,
21
- type: value.type,
22
- meta: value.meta,
23
- })
24
- })
25
- return entries
26
- }
27
8
 
28
9
  function childrenOf(entries: TreeEntry[], parentId: string | null): TreeEntry[] {
29
10
  return entries
package/src/server.ts CHANGED
@@ -13,6 +13,11 @@ import {
13
13
  foldRecords,
14
14
  isEncryptedContent,
15
15
  Kind,
16
+ loadOrCreateKeyFile,
17
+ loginOrRegisterWithKey,
18
+ makeChallengeSigner,
19
+ openSyncedProvider,
20
+ pickEntrySpace,
16
21
  recordFromYAny,
17
22
  SERVER_ROOT_ID,
18
23
  WebSocketStatus,
@@ -20,7 +25,6 @@ import {
20
25
  import type { Server } from "@modelcontextprotocol/sdk/server/index.js";
21
26
  import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
22
27
  import * as Y from "yjs";
23
- import { loadOrCreateKeypair, signChallenge } from "./crypto.ts";
24
28
  import { containsMention, stripMention } from "./mentions.ts";
25
29
  import { waitForSync } from "./utils.ts";
26
30
 
@@ -173,42 +177,29 @@ export class AbracadabraMCPServer {
173
177
 
174
178
  /** Start the server: authenticate with Ed25519 key, discover spaces/root doc, connect provider. */
175
179
  async connect(): Promise<void> {
176
- // Step 1: Load or generate Ed25519 keypair
177
- const keypair = await loadOrCreateKeypair(this.config.keyFile);
180
+ // Step 1: Load or generate the Ed25519 key file
181
+ const keypair = await loadOrCreateKeyFile(this.config.keyFile, {
182
+ defaultFileName: "agent.key",
183
+ onCreate: ({ path, publicKeyB64 }) => {
184
+ console.error(
185
+ `[abracadabra-mcp] Generated new agent keypair at ${path}`,
186
+ );
187
+ console.error(`[abracadabra-mcp] Public key: ${publicKeyB64}`);
188
+ },
189
+ });
178
190
  this._userId = keypair.publicKeyB64;
179
- const signFn = (challenge: string) =>
180
- Promise.resolve(signChallenge(challenge, keypair.privateKey));
181
- this._signFn = signFn;
191
+ this._signFn = makeChallengeSigner(keypair);
182
192
 
183
193
  // Step 2: Authenticate via challenge-response (register on first run)
184
- try {
185
- await this.client.loginWithKey(keypair.publicKeyB64, signFn);
186
- } catch (err: any) {
187
- // Key not registered — auto-register and retry.
188
- // Servers signal this with 404/422, or 401 + "public key not registered" / "user not found".
189
- const status = err?.status ?? err?.response?.status;
190
- const msg = String(err?.message ?? "").toLowerCase();
191
- const notRegistered =
192
- status === 404 ||
193
- status === 422 ||
194
- (status === 401 &&
195
- /not registered|user not found|no such user/.test(msg));
196
- if (notRegistered) {
194
+ await loginOrRegisterWithKey(this.client, keypair, {
195
+ displayName: this.agentName,
196
+ deviceName: "MCP Agent",
197
+ inviteCode: this.config.inviteCode,
198
+ onRegister: () =>
197
199
  console.error(
198
200
  "[abracadabra-mcp] Key not registered, creating new account...",
199
- );
200
- await this.client.registerWithKey({
201
- publicKey: keypair.publicKeyB64,
202
- username: this.agentName.replace(/\s+/g, "-").toLowerCase(),
203
- displayName: this.agentName,
204
- deviceName: "MCP Agent",
205
- inviteCode: this.config.inviteCode,
206
- });
207
- await this.client.loginWithKey(keypair.publicKeyB64, signFn);
208
- } else {
209
- throw err;
210
- }
211
- }
201
+ ),
202
+ });
212
203
  console.error(
213
204
  `[abracadabra-mcp] Authenticated as ${this.agentName} (pubkey=${keypair.publicKeyB64})`,
214
205
  );
@@ -219,9 +210,10 @@ export class AbracadabraMCPServer {
219
210
  // Step 4: Discover Spaces — top-level docs (children of the server root)
220
211
  // tagged with kind="space". The first Space is the default landing doc;
221
212
  // any other top-level doc serves as a fallback if no Spaces exist.
222
- const roots = await this.client.listChildren();
223
- this._spaces = roots.filter((d) => d.kind === Kind.Space);
224
- const first = this._spaces[0] ?? roots[0];
213
+ const { entry: first, spaces } = pickEntrySpace(
214
+ await this.client.listChildren(),
215
+ );
216
+ this._spaces = spaces;
225
217
  const initialDocId = first?.id ?? null;
226
218
  if (first) {
227
219
  console.error(
@@ -271,17 +263,11 @@ export class AbracadabraMCPServer {
271
263
  console.error("[abracadabra-mcp] Re-authenticated successfully");
272
264
  }
273
265
 
274
- const doc = new Y.Doc({ guid: docId });
275
- const provider = new AbracadabraProvider({
276
- name: docId,
277
- document: doc,
266
+ const { doc, provider } = await openSyncedProvider({
278
267
  client: this.client,
279
- disableOfflineStore: true,
280
- subdocLoading: "lazy",
268
+ docId,
281
269
  });
282
270
 
283
- await waitForSync(provider);
284
-
285
271
  provider.awareness.setLocalStateField("user", {
286
272
  name: this.agentName,
287
273
  color: this.agentColor,
package/src/tools/tree.ts CHANGED
@@ -5,56 +5,31 @@ import * as Y from 'yjs'
5
5
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
6
6
  import { z } from 'zod'
7
7
  import type { AbracadabraMCPServer } from '../server.ts'
8
- import type { TreeEntry, PageMeta } from '../converters/types.ts'
9
- import { PAGE_TYPES, TYPE_ALIASES, resolvePageType } from '../converters/page-types.ts'
10
8
  import type { SchemaBundleValidator } from '../schema/validator.ts'
11
- import { makeEntryMap, patchEntry } from '@abraca/dabra'
9
+ import {
10
+ makeEntryMap,
11
+ normalizeRootId as normalizeRootIdImpl,
12
+ patchEntry,
13
+ readEntries,
14
+ toPlain,
15
+ PAGE_TYPES,
16
+ TYPE_ALIASES,
17
+ resolvePageType,
18
+ } from '@abraca/dabra'
19
+ import type { TreeEntry, PageMeta } from '@abraca/dabra'
20
+
21
+ // `readEntries` now lives in @abraca/dabra (provider DocUtils). Re-exported for
22
+ // any in-package consumer that imported it from here.
23
+ export { readEntries }
12
24
 
13
25
  /**
14
- * Normalize a document ID so the hub/root doc ID is treated as the tree root (null).
15
- * This lets callers pass the hub doc_id from list_spaces as parentId/rootId
16
- * and get the expected root-level results instead of an empty set.
26
+ * Normalize a document ID so the hub/root doc ID is treated as the tree root
27
+ * (null). This lets callers pass the hub doc_id from list_spaces as
28
+ * parentId/rootId and get the expected root-level results instead of an empty
29
+ * set. Thin adapter over `@abraca/dabra`'s `normalizeRootId`.
17
30
  */
18
31
  function normalizeRootId(id: string | null | undefined, server: AbracadabraMCPServer): string | null {
19
- if (id == null) return null
20
- return id === server.rootDocId ? null : id
21
- }
22
-
23
- /** Safely read a tree map value, converting Y.Map to plain object if needed. */
24
- function toPlain(val: any): any {
25
- return val instanceof Y.Map ? val.toJSON() : val
26
- }
27
-
28
- /**
29
- * Read every doc-tree entry, optionally skipping the space's self-descriptor.
30
- *
31
- * A space's own `doc-tree` Y.Map holds an entry keyed by the space's OWN id
32
- * (the connected root doc), with `parentId: null` and `order: -1`. It stores
33
- * the space root's own icon/color/type/label — it is NOT a child document.
34
- * Because its `parentId` is null it otherwise shows up alongside real
35
- * top-level docs, making the space render as a phantom first child of itself
36
- * ("Health space's first document is 'Development'"). Pass `selfId =
37
- * server.rootDocId` to drop it. cou-sh's DocumentTree applies the same guard
38
- * (`if (id === spaceDocId) continue`).
39
- */
40
- export function readEntries(treeMap: Y.Map<any>, selfId?: string | null): TreeEntry[] {
41
- const entries: TreeEntry[] = []
42
- treeMap.forEach((raw: any, id: string) => {
43
- if (selfId && id === selfId) return // skip the space root's self-descriptor entry
44
- const value = toPlain(raw)
45
- if (typeof value !== 'object' || value === null) return // skip non-entry keys (e.g. ":updatedAt" timestamps)
46
- entries.push({
47
- id,
48
- label: value.label || 'Untitled',
49
- parentId: value.parentId ?? null,
50
- order: value.order ?? 0,
51
- type: value.type,
52
- meta: value.meta,
53
- createdAt: value.createdAt,
54
- updatedAt: value.updatedAt,
55
- })
56
- })
57
- return entries
32
+ return normalizeRootIdImpl(id, server.rootDocId)
58
33
  }
59
34
 
60
35
  function childrenOf(entries: TreeEntry[], parentId: string | null): TreeEntry[] {
@@ -498,7 +473,7 @@ export function registerTreeTools(
498
473
  for (const nid of toDelete) {
499
474
  const raw = treeMap.get(nid)
500
475
  if (!raw) continue
501
- const entry = toPlain(raw)
476
+ const entry = toPlain(raw) as any
502
477
  trashMap.set(nid, {
503
478
  label: entry.label || 'Untitled',
504
479
  parentId: entry.parentId ?? null,
@@ -595,7 +570,7 @@ export function registerTreeTools(
595
570
  const raw = treeMap.get(id)
596
571
  if (!raw) return { content: [{ type: 'text', text: `Document ${id} not found` }] }
597
572
 
598
- const entry = toPlain(raw)
573
+ const entry = toPlain(raw) as any
599
574
  const newId = crypto.randomUUID()
600
575
  treeMap.set(
601
576
  newId,
package/src/utils.ts CHANGED
@@ -1,52 +1,6 @@
1
1
  /**
2
- * Wait for a provider's `synced` event with a timeout.
3
- *
4
- * Mirrors `@abraca/dabra`'s `DocUtils.waitForSync`: the `isSynced` short-circuit
5
- * is load-bearing. `synced` is emitted once per sync transition (and deferred a
6
- * microtask), so a provider that has ALREADY synced — e.g. the cached child
7
- * provider that `loadChild` returns on a repeat read/write of the same doc —
8
- * will never re-emit. Without this guard those callers block for the full
9
- * `timeoutMs` ("works once, then every later op on that doc times out at 15s").
2
+ * Re-exports of the shared provider sync utilities. The implementations live in
3
+ * `@abraca/dabra` (`DocUtils`) — kept here as a stable local import path for the
4
+ * MCP tools that already `import { … } from "./utils.ts"`.
10
5
  */
11
- export function waitForSync(
12
- provider: {
13
- isSynced?: boolean
14
- on(event: string, cb: () => void): void
15
- off(event: string, cb: () => void): void
16
- },
17
- timeoutMs = 15000
18
- ): Promise<void> {
19
- // Already synced — resolve immediately (no event will fire again).
20
- if (provider.isSynced) return Promise.resolve()
21
-
22
- return new Promise<void>((resolve, reject) => {
23
- const timer = setTimeout(() => {
24
- provider.off('synced', handler)
25
- reject(new Error(`Sync timed out after ${timeoutMs}ms`))
26
- }, timeoutMs)
27
-
28
- function handler() {
29
- clearTimeout(timer)
30
- provider.off('synced', handler)
31
- resolve()
32
- }
33
-
34
- provider.on('synced', handler)
35
- })
36
- }
37
-
38
- /**
39
- * Wraps a promise with a timeout.
40
- */
41
- export function withTimeout<T>(promise: Promise<T>, timeoutMs: number, message?: string): Promise<T> {
42
- return new Promise<T>((resolve, reject) => {
43
- const timer = setTimeout(
44
- () => reject(new Error(message ?? `Operation timed out after ${timeoutMs}ms`)),
45
- timeoutMs
46
- )
47
- promise.then(
48
- (val) => { clearTimeout(timer); resolve(val) },
49
- (err) => { clearTimeout(timer); reject(err) }
50
- )
51
- })
52
- }
6
+ export { waitForSync, withTimeout } from "@abraca/dabra";