@totalreclaw/mcp-server 1.0.0 → 1.2.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.
Files changed (71) hide show
  1. package/README.md +92 -63
  2. package/dist/cli/setup.d.ts.map +1 -1
  3. package/dist/cli/setup.js +18 -2
  4. package/dist/cli/setup.js.map +1 -1
  5. package/dist/consolidation.d.ts +97 -0
  6. package/dist/consolidation.d.ts.map +1 -0
  7. package/dist/consolidation.js +183 -0
  8. package/dist/consolidation.js.map +1 -0
  9. package/dist/index.js +261 -51
  10. package/dist/index.js.map +1 -1
  11. package/dist/prompts.d.ts +5 -4
  12. package/dist/prompts.d.ts.map +1 -1
  13. package/dist/prompts.js +20 -5
  14. package/dist/prompts.js.map +1 -1
  15. package/dist/resources/memory-context.d.ts +1 -1
  16. package/dist/resources/memory-context.d.ts.map +1 -1
  17. package/dist/resources/memory-context.js +6 -11
  18. package/dist/resources/memory-context.js.map +1 -1
  19. package/dist/subgraph/embedding.d.ts +17 -18
  20. package/dist/subgraph/embedding.d.ts.map +1 -1
  21. package/dist/subgraph/embedding.js +25 -31
  22. package/dist/subgraph/embedding.js.map +1 -1
  23. package/dist/subgraph/lsh.d.ts +1 -1
  24. package/dist/subgraph/lsh.js +1 -1
  25. package/dist/subgraph/search.d.ts +3 -3
  26. package/dist/subgraph/search.d.ts.map +1 -1
  27. package/dist/subgraph/search.js +26 -11
  28. package/dist/subgraph/search.js.map +1 -1
  29. package/dist/subgraph/store.d.ts +11 -7
  30. package/dist/subgraph/store.d.ts.map +1 -1
  31. package/dist/subgraph/store.js +32 -17
  32. package/dist/subgraph/store.js.map +1 -1
  33. package/dist/tools/consolidate.d.ts +39 -0
  34. package/dist/tools/consolidate.d.ts.map +1 -0
  35. package/dist/tools/consolidate.js +167 -0
  36. package/dist/tools/consolidate.js.map +1 -0
  37. package/dist/tools/export.d.ts +1 -6
  38. package/dist/tools/export.d.ts.map +1 -1
  39. package/dist/tools/export.js +5 -15
  40. package/dist/tools/export.js.map +1 -1
  41. package/dist/tools/forget.d.ts +1 -6
  42. package/dist/tools/forget.d.ts.map +1 -1
  43. package/dist/tools/forget.js +2 -13
  44. package/dist/tools/forget.js.map +1 -1
  45. package/dist/tools/import-from.d.ts +94 -0
  46. package/dist/tools/import-from.d.ts.map +1 -0
  47. package/dist/tools/import-from.js +213 -0
  48. package/dist/tools/import-from.js.map +1 -0
  49. package/dist/tools/import.d.ts +1 -11
  50. package/dist/tools/import.d.ts.map +1 -1
  51. package/dist/tools/import.js +2 -17
  52. package/dist/tools/import.js.map +1 -1
  53. package/dist/tools/index.d.ts +2 -0
  54. package/dist/tools/index.d.ts.map +1 -1
  55. package/dist/tools/index.js +7 -1
  56. package/dist/tools/index.js.map +1 -1
  57. package/dist/tools/recall.d.ts +1 -6
  58. package/dist/tools/recall.d.ts.map +1 -1
  59. package/dist/tools/recall.js +3 -11
  60. package/dist/tools/recall.js.map +1 -1
  61. package/dist/tools/remember.d.ts +4 -7
  62. package/dist/tools/remember.d.ts.map +1 -1
  63. package/dist/tools/remember.js +136 -17
  64. package/dist/tools/remember.js.map +1 -1
  65. package/dist/tools/status.d.ts.map +1 -1
  66. package/dist/tools/status.js +1 -0
  67. package/dist/tools/status.js.map +1 -1
  68. package/dist/tools/upgrade.d.ts.map +1 -1
  69. package/dist/tools/upgrade.js +1 -0
  70. package/dist/tools/upgrade.js.map +1 -1
  71. package/package.json +12 -5
package/dist/index.js CHANGED
@@ -10,9 +10,10 @@ const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
10
10
  const client_1 = require("@totalreclaw/client");
11
11
  const index_js_2 = require("./tools/index.js");
12
12
  const remember_js_1 = require("./tools/remember.js");
13
+ const consolidation_js_1 = require("./consolidation.js");
13
14
  const prompts_js_1 = require("./prompts.js");
14
15
  const index_js_3 = require("./resources/index.js");
15
- // Subgraph imports (lazy usage -- only when subgraph mode is active)
16
+ // Subgraph imports (lazy usage -- only when managed service is active)
16
17
  const crypto_js_1 = require("./subgraph/crypto.js");
17
18
  const lsh_js_1 = require("./subgraph/lsh.js");
18
19
  const embedding_js_1 = require("./subgraph/embedding.js");
@@ -22,23 +23,31 @@ const search_js_1 = require("./subgraph/search.js");
22
23
  const bip39_1 = require("@scure/bip39");
23
24
  const english_js_1 = require("@scure/bip39/wordlists/english.js");
24
25
  const accounts_1 = require("viem/accounts");
26
+ const viem_1 = require("viem");
27
+ const chains_1 = require("viem/chains");
28
+ const accounts_2 = require("permissionless/accounts");
29
+ const account_abstraction_1 = require("viem/account-abstraction");
25
30
  const node_crypto_1 = __importDefault(require("node:crypto"));
26
31
  // ── Configuration ───────────────────────────────────────────────────────────
27
32
  const SERVER_URL = process.env.TOTALRECLAW_SERVER_URL || 'http://127.0.0.1:8080';
28
- const DEFAULT_NAMESPACE = process.env.TOTALRECLAW_NAMESPACE || 'default';
29
33
  const MASTER_PASSWORD = process.env.TOTALRECLAW_MASTER_PASSWORD;
34
+ // Store-time near-duplicate detection (consolidation module)
35
+ const STORE_DEDUP_ENABLED = process.env.TOTALRECLAW_STORE_DEDUP !== 'false';
30
36
  let subgraphState = null;
31
37
  /**
32
38
  * Detect server mode based on environment configuration.
33
39
  *
34
- * Subgraph mode requires:
35
- * 1. TOTALRECLAW_MASTER_PASSWORD is a valid BIP-39 mnemonic
36
- * 2. TOTALRECLAW_SUBGRAPH_MODE=true
40
+ * Managed service (subgraph) mode is the default when a valid BIP-39 mnemonic
41
+ * is provided as TOTALRECLAW_MASTER_PASSWORD.
42
+ *
43
+ * Self-hosted mode (HTTP) requires TOTALRECLAW_SELF_HOSTED=true.
44
+ * Defaults to managed service otherwise.
37
45
  */
38
46
  function detectServerMode() {
39
47
  if (!MASTER_PASSWORD)
40
48
  return 'http';
41
- if (process.env.TOTALRECLAW_SUBGRAPH_MODE !== 'true')
49
+ // Self-hosted mode is opt-in: requires explicit TOTALRECLAW_SELF_HOSTED=true
50
+ if (process.env.TOTALRECLAW_SELF_HOSTED === 'true')
42
51
  return 'http';
43
52
  const words = MASTER_PASSWORD.trim().split(/\s+/);
44
53
  if (words.length !== 12 && words.length !== 24)
@@ -51,18 +60,38 @@ function detectServerMode() {
51
60
  * Initialize subgraph state from the BIP-39 mnemonic.
52
61
  * Derives all cryptographic keys and creates the LSH hasher.
53
62
  */
54
- function initSubgraphState() {
63
+ async function initSubgraphState() {
55
64
  const mnemonic = MASTER_PASSWORD.trim();
56
65
  const { authKey, encryptionKey, dedupKey, salt } = (0, crypto_js_1.deriveKeys)(mnemonic);
57
66
  // Derive LSH seed and create hasher
58
67
  const lshSeed = (0, crypto_js_1.deriveLshSeed)(mnemonic, salt);
59
- const dims = (0, embedding_js_1.getEmbeddingDims)(); // 384 for bge-small-en-v1.5
68
+ const dims = (0, embedding_js_1.getEmbeddingDims)(); // 1024 for Qwen3-Embedding-0.6B
60
69
  const lshHasher = new lsh_js_1.LSHHasher(lshSeed, dims);
61
- // Derive Smart Account address from mnemonic
70
+ // Derive Smart Account address via relay bundler proxy (same chain view as Pimlico).
71
+ // This does an eth_call to the EntryPoint to compute the counterfactual CREATE2 address.
72
+ const chainId = parseInt(process.env.TOTALRECLAW_CHAIN_ID || '100');
73
+ const chain = chainId === 100 ? chains_1.gnosis : chainId === 84532 ? chains_1.baseSepolia : chains_1.gnosisChiado;
74
+ const bundlerRpcUrl = `${SERVER_URL}/v1/bundler`;
62
75
  const ownerAccount = (0, accounts_1.mnemonicToAccount)(mnemonic);
63
- // The Smart Account address is deterministic from the EOA via CREATE2
64
- // For now, use the EOA address as owner identifier (Smart Account is derived on-chain)
65
- const smartAccountAddress = ownerAccount.address;
76
+ const entryPointAddr = (process.env.TOTALRECLAW_ENTRYPOINT_ADDRESS || account_abstraction_1.entryPoint07Address);
77
+ const authKeyHex = Buffer.from(authKey).toString('hex');
78
+ // Use public RPC for the eth_call (Pimlico bundler doesn't support eth_call).
79
+ // This is only used to derive the counterfactual Smart Account address via CREATE2 —
80
+ // the result is deterministic and doesn't depend on chain head position.
81
+ const publicClient = (0, viem_1.createPublicClient)({
82
+ chain,
83
+ transport: (0, viem_1.http)(),
84
+ });
85
+ const smartAccount = await (0, accounts_2.toSimpleSmartAccount)({
86
+ // @ts-ignore - viem/permissionless type intersection conflict
87
+ client: publicClient,
88
+ owner: ownerAccount,
89
+ entryPoint: {
90
+ address: entryPointAddr,
91
+ version: '0.7',
92
+ },
93
+ });
94
+ const smartAccountAddress = smartAccount.address.toLowerCase();
66
95
  return {
67
96
  mode: 'subgraph',
68
97
  mnemonic,
@@ -193,22 +222,137 @@ async function handleRememberSubgraph(state, args) {
193
222
  }],
194
223
  };
195
224
  }
225
+ // Determine if this is an explicit remember (user-initiated) — always supersede.
226
+ // For batch mode (multiple facts from auto-extraction), apply full skip/supersede logic.
227
+ const isExplicitRemember = !!input?.fact;
196
228
  const results = [];
229
+ let dedupSkipped = 0;
230
+ let dedupSuperseded = 0;
197
231
  for (const item of textsToStore) {
198
232
  try {
199
- // 1. Encrypt the fact text
200
- const encryptedBlob = (0, crypto_js_1.encrypt)(item.text, state.encryptionKey);
201
- // 2. Generate blind indices (word-based)
233
+ // 1. Generate blind indices (word-based)
202
234
  const wordIndices = (0, crypto_js_1.generateBlindIndices)(item.text);
203
- // 3. Generate embedding and LSH indices
235
+ // 2. Generate embedding and LSH indices
204
236
  const embedding = await (0, embedding_js_1.generateEmbedding)(item.text);
205
237
  const lshIndices = state.lshHasher.hash(embedding);
206
- // 4. Combine word + LSH indices
238
+ // 3. Combine word + LSH indices
207
239
  const allIndices = [...wordIndices, ...lshIndices];
240
+ // Store-time dedup: search for near-duplicates before storing
241
+ let effectiveImportance = item.importance;
242
+ if (STORE_DEDUP_ENABLED) {
243
+ try {
244
+ const maxCandidates = consolidation_js_1.STORE_DEDUP_MAX_CANDIDATES;
245
+ const candidates = await (0, search_js_1.searchSubgraph)(state.smartAccountAddress, allIndices, maxCandidates, state.serverUrl, Buffer.from(state.authKey).toString('hex'));
246
+ if (candidates.length > 0) {
247
+ // Decrypt candidates and extract embeddings
248
+ const decryptedCandidates = [];
249
+ for (const c of candidates) {
250
+ try {
251
+ const blobBase64 = Buffer.from(c.encryptedBlob, 'hex').toString('base64');
252
+ const text = (0, crypto_js_1.decrypt)(blobBase64, state.encryptionKey);
253
+ let candEmbedding = null;
254
+ if (c.encryptedEmbedding) {
255
+ try {
256
+ candEmbedding = decryptEmbedding(c.encryptedEmbedding, state.encryptionKey);
257
+ }
258
+ catch { /* skip */ }
259
+ }
260
+ decryptedCandidates.push({
261
+ id: c.id,
262
+ text,
263
+ embedding: candEmbedding,
264
+ importance: Math.round(parseFloat(c.decayScore) * 10) || 5,
265
+ decayScore: parseFloat(c.decayScore) || 0.5,
266
+ createdAt: parseInt(c.timestamp) || 0,
267
+ version: 1,
268
+ });
269
+ }
270
+ catch { /* skip undecryptable */ }
271
+ }
272
+ const dupMatch = (0, consolidation_js_1.findNearDuplicate)(embedding, decryptedCandidates, (0, consolidation_js_1.getStoreDedupThreshold)());
273
+ if (dupMatch) {
274
+ if (isExplicitRemember) {
275
+ // Explicit remember: always supersede — submit tombstone for old fact
276
+ effectiveImportance = Math.max(item.importance, dupMatch.existingFact.importance);
277
+ try {
278
+ const tombstonePayload = {
279
+ id: dupMatch.existingFact.id,
280
+ timestamp: new Date().toISOString(),
281
+ owner: state.smartAccountAddress,
282
+ encryptedBlob: Buffer.from('tombstone').toString('hex'),
283
+ blindIndices: [],
284
+ decayScore: 0,
285
+ source: 'mcp_dedup',
286
+ contentFp: '',
287
+ agentId: 'mcp-server',
288
+ };
289
+ const tombProtobuf = (0, store_js_1.encodeFactProtobuf)(tombstonePayload);
290
+ const tombConfig = (0, store_js_1.getSubgraphConfig)({
291
+ relayUrl: state.serverUrl,
292
+ mnemonic: state.mnemonic,
293
+ authKeyHex: Buffer.from(state.authKey).toString('hex'),
294
+ walletAddress: state.smartAccountAddress,
295
+ });
296
+ await (0, store_js_1.submitFactOnChain)(tombProtobuf, tombConfig);
297
+ console.error(`Store-time dedup: superseded ${dupMatch.existingFact.id} (sim=${dupMatch.similarity.toFixed(3)})`);
298
+ }
299
+ catch {
300
+ console.error(`Store-time dedup: failed to tombstone superseded fact ${dupMatch.existingFact.id}`);
301
+ }
302
+ dedupSuperseded++;
303
+ }
304
+ else {
305
+ // Batch mode: apply shouldSupersede logic
306
+ const action = (0, consolidation_js_1.shouldSupersede)(item.importance, dupMatch.existingFact);
307
+ if (action === 'skip') {
308
+ console.error(`Store-time dedup: skipping "${item.text.slice(0, 60)}..." (sim=${dupMatch.similarity.toFixed(3)})`);
309
+ results.push({ success: true, fact_id: '', action: 'skipped_dedup' });
310
+ dedupSkipped++;
311
+ continue;
312
+ }
313
+ // action === 'supersede'
314
+ effectiveImportance = Math.max(item.importance, dupMatch.existingFact.importance);
315
+ try {
316
+ const tombstonePayload = {
317
+ id: dupMatch.existingFact.id,
318
+ timestamp: new Date().toISOString(),
319
+ owner: state.smartAccountAddress,
320
+ encryptedBlob: Buffer.from('tombstone').toString('hex'),
321
+ blindIndices: [],
322
+ decayScore: 0,
323
+ source: 'mcp_dedup',
324
+ contentFp: '',
325
+ agentId: 'mcp-server',
326
+ };
327
+ const tombProtobuf = (0, store_js_1.encodeFactProtobuf)(tombstonePayload);
328
+ const tombConfig = (0, store_js_1.getSubgraphConfig)({
329
+ relayUrl: state.serverUrl,
330
+ mnemonic: state.mnemonic,
331
+ authKeyHex: Buffer.from(state.authKey).toString('hex'),
332
+ walletAddress: state.smartAccountAddress,
333
+ });
334
+ await (0, store_js_1.submitFactOnChain)(tombProtobuf, tombConfig);
335
+ console.error(`Store-time dedup: superseded ${dupMatch.existingFact.id} (sim=${dupMatch.similarity.toFixed(3)})`);
336
+ }
337
+ catch {
338
+ console.error(`Store-time dedup: failed to tombstone superseded fact ${dupMatch.existingFact.id}`);
339
+ }
340
+ dedupSuperseded++;
341
+ }
342
+ }
343
+ }
344
+ }
345
+ catch (dedupErr) {
346
+ // Fail-open: dedup failure should not prevent storing the fact
347
+ console.error(`Store-time dedup search failed: ${dedupErr instanceof Error ? dedupErr.message : String(dedupErr)}`);
348
+ }
349
+ }
350
+ // 4. Encrypt the fact text
351
+ const encryptedBlob = (0, crypto_js_1.encrypt)(item.text, state.encryptionKey);
208
352
  // 5. Generate content fingerprint for dedup
209
353
  const contentFp = (0, crypto_js_1.generateContentFingerprint)(item.text, state.dedupKey);
210
354
  // 6. Encrypt the embedding for on-chain storage
211
- const encryptedEmbedding = encryptEmbedding(embedding, state.encryptionKey);
355
+ const encryptedEmb = encryptEmbedding(embedding, state.encryptionKey);
212
356
  // 7. Build fact payload
213
357
  const factId = node_crypto_1.default.randomUUID();
214
358
  const factPayload = {
@@ -217,20 +361,22 @@ async function handleRememberSubgraph(state, args) {
217
361
  owner: state.smartAccountAddress,
218
362
  encryptedBlob: Buffer.from(encryptedBlob, 'base64').toString('hex'),
219
363
  blindIndices: allIndices,
220
- decayScore: item.importance / 10,
364
+ decayScore: effectiveImportance / 10,
221
365
  source: 'mcp_remember',
222
366
  contentFp,
223
367
  agentId: 'mcp-server',
224
- encryptedEmbedding,
368
+ encryptedEmbedding: encryptedEmb,
225
369
  };
226
370
  // 8. Encode as protobuf and submit on-chain
227
371
  const protobuf = (0, store_js_1.encodeFactProtobuf)(factPayload);
228
372
  const config = (0, store_js_1.getSubgraphConfig)({
229
373
  relayUrl: state.serverUrl,
230
374
  mnemonic: state.mnemonic,
375
+ authKeyHex: Buffer.from(state.authKey).toString('hex'),
376
+ walletAddress: state.smartAccountAddress,
231
377
  });
232
378
  const { txHash, success } = await (0, store_js_1.submitFactOnChain)(protobuf, config);
233
- results.push({ success, fact_id: factId, tx_hash: txHash });
379
+ results.push({ success, fact_id: factId, tx_hash: txHash, action: dedupSuperseded > 0 ? 'superseded' : 'created' });
234
380
  }
235
381
  catch (error) {
236
382
  const message = error instanceof Error ? error.message : 'Unknown error';
@@ -238,7 +384,7 @@ async function handleRememberSubgraph(state, args) {
238
384
  console.error(`Failed to store fact on-chain: ${message}`);
239
385
  }
240
386
  }
241
- const created = results.filter(r => r.success).length;
387
+ const created = results.filter(r => r.success && r.action !== 'skipped_dedup').length;
242
388
  return {
243
389
  content: [{
244
390
  type: 'text',
@@ -248,6 +394,8 @@ async function handleRememberSubgraph(state, args) {
248
394
  total: textsToStore.length,
249
395
  created,
250
396
  skipped: textsToStore.length - created,
397
+ dedup_skipped: dedupSkipped,
398
+ dedup_superseded: dedupSuperseded,
251
399
  mode: 'subgraph',
252
400
  }),
253
401
  }],
@@ -287,7 +435,7 @@ async function handleRecallSubgraph(state, args) {
287
435
  const allTrapdoors = [...wordTrapdoors, ...lshTrapdoors];
288
436
  // 4. Search the subgraph
289
437
  const maxCandidates = Math.max(k * 50, 400); // Fetch more candidates for reranking
290
- const candidates = await (0, search_js_1.searchSubgraph)(state.smartAccountAddress, allTrapdoors, maxCandidates, state.serverUrl);
438
+ const candidates = await (0, search_js_1.searchSubgraph)(state.smartAccountAddress, allTrapdoors, maxCandidates, state.serverUrl, Buffer.from(state.authKey).toString('hex'));
291
439
  if (candidates.length === 0) {
292
440
  return {
293
441
  content: [{
@@ -304,8 +452,9 @@ async function handleRecallSubgraph(state, args) {
304
452
  const decryptedCandidates = [];
305
453
  for (const c of candidates) {
306
454
  try {
307
- // Decrypt the fact text (encryptedBlob is hex on subgraph, base64 internally)
308
- const blobBase64 = Buffer.from(c.encryptedBlob, 'hex').toString('base64');
455
+ // Decrypt the fact text (encryptedBlob is 0x-prefixed hex from subgraph)
456
+ const blobHex = c.encryptedBlob.startsWith('0x') ? c.encryptedBlob.slice(2) : c.encryptedBlob;
457
+ const blobBase64 = Buffer.from(blobHex, 'hex').toString('base64');
309
458
  const text = (0, crypto_js_1.decrypt)(blobBase64, state.encryptionKey);
310
459
  // Decrypt embedding if available
311
460
  let embedding;
@@ -326,7 +475,7 @@ async function handleRecallSubgraph(state, args) {
326
475
  });
327
476
  }
328
477
  catch {
329
- // Skip candidates that fail to decrypt
478
+ // Skip candidates that fail to decrypt (e.g., wrong key, corrupt data)
330
479
  }
331
480
  }
332
481
  // 6. Detect query intent for dynamic weight selection
@@ -389,7 +538,7 @@ async function handleForgetSubgraph(state, args) {
389
538
  text: JSON.stringify({
390
539
  deleted_count: 0,
391
540
  fact_ids: [],
392
- error: 'fact_id is required for subgraph forget (query-based forget not supported in subgraph mode)',
541
+ error: 'fact_id is required for forget (query-based forget is not supported with the managed service)',
393
542
  }),
394
543
  }],
395
544
  };
@@ -414,6 +563,8 @@ async function handleForgetSubgraph(state, args) {
414
563
  const config = (0, store_js_1.getSubgraphConfig)({
415
564
  relayUrl: state.serverUrl,
416
565
  mnemonic: state.mnemonic,
566
+ authKeyHex: Buffer.from(state.authKey).toString('hex'),
567
+ walletAddress: state.smartAccountAddress,
417
568
  });
418
569
  const { txHash, success } = await (0, store_js_1.submitFactOnChain)(protobuf, config);
419
570
  return {
@@ -443,6 +594,22 @@ async function handleForgetSubgraph(state, args) {
443
594
  };
444
595
  }
445
596
  }
597
+ // ── Auth error helper ────────────────────────────────────────────────────────
598
+ const AUTH_HINT_MESSAGE = 'Authentication failed. If using a recovery phrase, check that all 12 words are in the correct order and spelled correctly.';
599
+ /**
600
+ * Check if an error is a 401 authentication error and return a helpful message.
601
+ */
602
+ function isAuthError(error) {
603
+ if (error instanceof Error) {
604
+ const msg = error.message;
605
+ return (msg.includes('401') ||
606
+ msg.includes('UNAUTHORIZED') ||
607
+ msg.includes('Not authenticated') ||
608
+ msg.includes('AUTH_FAILED') ||
609
+ msg.includes('Invalid credentials'));
610
+ }
611
+ return false;
612
+ }
446
613
  // ── Quota error helper ──────────────────────────────────────────────────────
447
614
  /**
448
615
  * Check if an error is a quota exceeded error (HTTP 403 with error_code: QUOTA_EXCEEDED).
@@ -481,7 +648,7 @@ const server = new index_js_1.Server({ name: 'totalreclaw', version: '1.0.0' },
481
648
  (0, remember_js_1.setOnRememberCallback)(() => {
482
649
  (0, index_js_3.invalidateMemoryContextCache)();
483
650
  // Notify subscribed clients that the resource has been updated
484
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch(() => { });
651
+ server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
485
652
  });
486
653
  // ── Layer 2 + 3: Tool handlers ───────────────────────────────────────────────
487
654
  server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
@@ -491,6 +658,8 @@ server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
491
658
  index_js_2.forgetToolDefinition,
492
659
  index_js_2.exportToolDefinition,
493
660
  index_js_2.importToolDefinition,
661
+ index_js_2.importFromToolDefinition,
662
+ index_js_2.consolidateToolDefinition,
494
663
  index_js_2.statusToolDefinition,
495
664
  index_js_2.upgradeToolDefinition,
496
665
  ],
@@ -501,16 +670,16 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
501
670
  try {
502
671
  // ── Billing tools (mode-independent, always use HTTP relay) ────────────
503
672
  if (name === 'totalreclaw_status') {
504
- const authKey = subgraphState
505
- ? (0, crypto_js_1.computeAuthKeyHash)(subgraphState.authKey)
673
+ const authKeyHex = subgraphState
674
+ ? Buffer.from(subgraphState.authKey).toString('hex')
506
675
  : '';
507
- return await (0, index_js_2.handleStatus)(SERVER_URL, authKey, args);
676
+ return await (0, index_js_2.handleStatus)(SERVER_URL, authKeyHex, args);
508
677
  }
509
678
  if (name === 'totalreclaw_upgrade') {
510
- const authKey = subgraphState
511
- ? (0, crypto_js_1.computeAuthKeyHash)(subgraphState.authKey)
679
+ const authKeyHex = subgraphState
680
+ ? Buffer.from(subgraphState.authKey).toString('hex')
512
681
  : '';
513
- return await (0, index_js_2.handleUpgrade)(SERVER_URL, authKey, args);
682
+ return await (0, index_js_2.handleUpgrade)(SERVER_URL, authKeyHex, args);
514
683
  }
515
684
  // ── Subgraph mode ─────────────────────────────────────────────────────
516
685
  if (subgraphState) {
@@ -520,7 +689,7 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
520
689
  const result = await handleRememberSubgraph(subgraphState, args);
521
690
  // Invalidate cache after successful store
522
691
  (0, index_js_3.invalidateMemoryContextCache)();
523
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch(() => { });
692
+ server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
524
693
  return result;
525
694
  }
526
695
  catch (error) {
@@ -535,16 +704,16 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
535
704
  case 'totalreclaw_forget': {
536
705
  const result = await handleForgetSubgraph(subgraphState, args);
537
706
  (0, index_js_3.invalidateMemoryContextCache)();
538
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch(() => { });
707
+ server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
539
708
  return result;
540
709
  }
541
710
  case 'totalreclaw_export':
542
- // Export in subgraph mode not yet implemented -- fall through to error
711
+ // Export not yet implemented for the managed service -- fall through to error
543
712
  return {
544
713
  content: [{
545
714
  type: 'text',
546
715
  text: JSON.stringify({
547
- error: 'Export is not yet supported in subgraph mode. Use HTTP mode for export.',
716
+ error: 'Export is not yet supported with the managed service. Use self-hosted mode for export.',
548
717
  }),
549
718
  }],
550
719
  isError: true,
@@ -554,7 +723,27 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
554
723
  content: [{
555
724
  type: 'text',
556
725
  text: JSON.stringify({
557
- error: 'Import is not yet supported in subgraph mode. Use HTTP mode for import.',
726
+ error: 'Import is not yet supported with the managed service. Use self-hosted mode for import.',
727
+ }),
728
+ }],
729
+ isError: true,
730
+ };
731
+ case 'totalreclaw_import_from':
732
+ return {
733
+ content: [{
734
+ type: 'text',
735
+ text: JSON.stringify({
736
+ error: 'Import from external sources is not yet supported with the managed service. Use self-hosted mode for import.',
737
+ }),
738
+ }],
739
+ isError: true,
740
+ };
741
+ case 'totalreclaw_consolidate':
742
+ return {
743
+ content: [{
744
+ type: 'text',
745
+ text: JSON.stringify({
746
+ error: 'Consolidation is not supported with the managed service. On-chain facts require tombstone-based dedup which is handled automatically at store time.',
558
747
  }),
559
748
  }],
560
749
  isError: true,
@@ -574,7 +763,7 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
574
763
  switch (name) {
575
764
  case 'totalreclaw_remember': {
576
765
  try {
577
- const result = await (0, index_js_2.handleRemember)(client, args, DEFAULT_NAMESPACE);
766
+ const result = await (0, index_js_2.handleRemember)(client, args);
578
767
  return result;
579
768
  }
580
769
  catch (error) {
@@ -585,18 +774,27 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
585
774
  }
586
775
  }
587
776
  case 'totalreclaw_recall':
588
- return await (0, index_js_2.handleRecall)(client, args, DEFAULT_NAMESPACE);
777
+ return await (0, index_js_2.handleRecall)(client, args);
589
778
  case 'totalreclaw_forget': {
590
- const result = await (0, index_js_2.handleForget)(client, args, DEFAULT_NAMESPACE);
779
+ const result = await (0, index_js_2.handleForget)(client, args);
591
780
  // Invalidate cache on forget too
592
781
  (0, index_js_3.invalidateMemoryContextCache)();
593
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch(() => { });
782
+ server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
594
783
  return result;
595
784
  }
596
785
  case 'totalreclaw_export':
597
- return await (0, index_js_2.handleExport)(client, args, DEFAULT_NAMESPACE);
786
+ return await (0, index_js_2.handleExport)(client, args);
598
787
  case 'totalreclaw_import':
599
- return await (0, index_js_2.handleImport)(client, args, DEFAULT_NAMESPACE);
788
+ return await (0, index_js_2.handleImport)(client, args);
789
+ case 'totalreclaw_import_from':
790
+ return await (0, index_js_2.handleImportFrom)(client, args);
791
+ case 'totalreclaw_consolidate': {
792
+ const result = await (0, index_js_2.handleConsolidate)(client, args);
793
+ // Invalidate cache after consolidation (facts may have been deleted)
794
+ (0, index_js_3.invalidateMemoryContextCache)();
795
+ server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
796
+ return result;
797
+ }
600
798
  default:
601
799
  return {
602
800
  content: [{
@@ -612,6 +810,18 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
612
810
  if (isQuotaExceededError(error)) {
613
811
  return quotaExceededResponse();
614
812
  }
813
+ // Provide a helpful hint for authentication failures
814
+ if (isAuthError(error)) {
815
+ return {
816
+ content: [{
817
+ type: 'text',
818
+ text: JSON.stringify({
819
+ error: AUTH_HINT_MESSAGE,
820
+ }),
821
+ }],
822
+ isError: true,
823
+ };
824
+ }
615
825
  return {
616
826
  content: [{
617
827
  type: 'text',
@@ -630,20 +840,20 @@ server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => ({
630
840
  server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request) => {
631
841
  const { uri } = request.params;
632
842
  if (uri === index_js_3.memoryContextResource.uri) {
633
- // In subgraph mode, resource reading is not supported yet
843
+ // With the managed service, resource reading is not supported yet
634
844
  if (subgraphState) {
635
845
  return {
636
846
  contents: [
637
847
  {
638
848
  uri: index_js_3.memoryContextResource.uri,
639
849
  mimeType: 'text/markdown',
640
- text: '*Memory context resource is not available in subgraph mode. Use totalreclaw_recall to search memories.*',
850
+ text: '*Memory context resource is not available with the managed service. Use totalreclaw_recall to search memories.*',
641
851
  },
642
852
  ],
643
853
  };
644
854
  }
645
855
  const client = await getClient();
646
- const content = await (0, index_js_3.readMemoryContext)(client, DEFAULT_NAMESPACE);
856
+ const content = await (0, index_js_3.readMemoryContext)(client);
647
857
  return {
648
858
  contents: [
649
859
  {
@@ -684,11 +894,11 @@ async function main() {
684
894
  // Detect and initialize server mode
685
895
  const mode = detectServerMode();
686
896
  if (mode === 'subgraph') {
687
- subgraphState = initSubgraphState();
688
- console.error(`TotalReclaw MCP server started (subgraph mode, owner: ${subgraphState.smartAccountAddress})`);
897
+ subgraphState = await initSubgraphState();
898
+ console.error(`TotalReclaw MCP server started (managed service, owner: ${subgraphState.smartAccountAddress})`);
689
899
  }
690
900
  else {
691
- console.error('TotalReclaw MCP server started (HTTP mode)');
901
+ console.error('TotalReclaw MCP server started (self-hosted mode)');
692
902
  }
693
903
  const transport = new stdio_js_1.StdioServerTransport();
694
904
  await server.connect(transport);