@totalreclaw/mcp-server 3.3.0-rc.4 → 3.4.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 (133) hide show
  1. package/README.md +4 -7
  2. package/SKILL.md +6 -7
  3. package/dist/claims-helper.d.ts +1 -1
  4. package/dist/claims-helper.d.ts.map +1 -1
  5. package/dist/claims-helper.js +31 -31
  6. package/dist/claims-helper.js.map +1 -1
  7. package/dist/cli/setup.js +5 -5
  8. package/dist/cli/setup.js.map +1 -1
  9. package/dist/consolidation.d.ts +3 -5
  10. package/dist/consolidation.d.ts.map +1 -1
  11. package/dist/consolidation.js +47 -122
  12. package/dist/consolidation.js.map +1 -1
  13. package/dist/contradiction-sync.d.ts +2 -2
  14. package/dist/contradiction-sync.d.ts.map +1 -1
  15. package/dist/contradiction-sync.js +12 -12
  16. package/dist/contradiction-sync.js.map +1 -1
  17. package/dist/dispatch.d.ts +95 -0
  18. package/dist/dispatch.d.ts.map +1 -0
  19. package/dist/dispatch.js +191 -0
  20. package/dist/dispatch.js.map +1 -0
  21. package/dist/extraction/extractor.d.ts +1 -0
  22. package/dist/extraction/extractor.d.ts.map +1 -1
  23. package/dist/extraction/extractor.js +15 -15
  24. package/dist/extraction/extractor.js.map +1 -1
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +207 -732
  27. package/dist/index.js.map +1 -1
  28. package/dist/prompts.d.ts +3 -4
  29. package/dist/prompts.d.ts.map +1 -1
  30. package/dist/prompts.js +5 -11
  31. package/dist/prompts.js.map +1 -1
  32. package/dist/server-setup.d.ts +35 -0
  33. package/dist/server-setup.d.ts.map +1 -0
  34. package/dist/server-setup.js +102 -0
  35. package/dist/server-setup.js.map +1 -0
  36. package/dist/subgraph/chain-config.d.ts +45 -0
  37. package/dist/subgraph/chain-config.d.ts.map +1 -0
  38. package/dist/subgraph/chain-config.js +66 -0
  39. package/dist/subgraph/chain-config.js.map +1 -0
  40. package/dist/subgraph/search.js +13 -13
  41. package/dist/subgraph/search.js.map +1 -1
  42. package/dist/subgraph/store.d.ts.map +1 -1
  43. package/dist/subgraph/store.js +4 -1
  44. package/dist/subgraph/store.js.map +1 -1
  45. package/dist/tools/account.d.ts +5 -2
  46. package/dist/tools/account.d.ts.map +1 -1
  47. package/dist/tools/account.js +11 -4
  48. package/dist/tools/account.js.map +1 -1
  49. package/dist/tools/consolidate.d.ts +2 -2
  50. package/dist/tools/consolidate.d.ts.map +1 -1
  51. package/dist/tools/consolidate.js +2 -1
  52. package/dist/tools/consolidate.js.map +1 -1
  53. package/dist/tools/debrief.d.ts +2 -2
  54. package/dist/tools/debrief.d.ts.map +1 -1
  55. package/dist/tools/debrief.js +2 -1
  56. package/dist/tools/debrief.js.map +1 -1
  57. package/dist/tools/export.d.ts +2 -2
  58. package/dist/tools/export.d.ts.map +1 -1
  59. package/dist/tools/export.js +2 -1
  60. package/dist/tools/export.js.map +1 -1
  61. package/dist/tools/forget.d.ts +8 -2
  62. package/dist/tools/forget.d.ts.map +1 -1
  63. package/dist/tools/forget.js +14 -7
  64. package/dist/tools/forget.js.map +1 -1
  65. package/dist/tools/helpers.d.ts +40 -0
  66. package/dist/tools/helpers.d.ts.map +1 -0
  67. package/dist/tools/helpers.js +64 -0
  68. package/dist/tools/helpers.js.map +1 -0
  69. package/dist/tools/import-batch.d.ts +2 -1
  70. package/dist/tools/import-batch.d.ts.map +1 -1
  71. package/dist/tools/import-batch.js +1 -1
  72. package/dist/tools/import-batch.js.map +1 -1
  73. package/dist/tools/import-from.d.ts +2 -2
  74. package/dist/tools/import-from.d.ts.map +1 -1
  75. package/dist/tools/import-from.js +2 -1
  76. package/dist/tools/import-from.js.map +1 -1
  77. package/dist/tools/import.d.ts +2 -2
  78. package/dist/tools/import.d.ts.map +1 -1
  79. package/dist/tools/import.js +4 -3
  80. package/dist/tools/import.js.map +1 -1
  81. package/dist/tools/index.d.ts +2 -2
  82. package/dist/tools/index.d.ts.map +1 -1
  83. package/dist/tools/index.js +7 -9
  84. package/dist/tools/index.js.map +1 -1
  85. package/dist/tools/pair.d.ts +2 -1
  86. package/dist/tools/pair.d.ts.map +1 -1
  87. package/dist/tools/pair.js +4 -4
  88. package/dist/tools/pair.js.map +1 -1
  89. package/dist/tools/pin.d.ts +10 -7
  90. package/dist/tools/pin.d.ts.map +1 -1
  91. package/dist/tools/pin.js +43 -49
  92. package/dist/tools/pin.js.map +1 -1
  93. package/dist/tools/recall.d.ts +2 -2
  94. package/dist/tools/recall.d.ts.map +1 -1
  95. package/dist/tools/recall.js +22 -47
  96. package/dist/tools/recall.js.map +1 -1
  97. package/dist/tools/remember.d.ts +2 -2
  98. package/dist/tools/remember.d.ts.map +1 -1
  99. package/dist/tools/remember.js +30 -48
  100. package/dist/tools/remember.js.map +1 -1
  101. package/dist/tools/retype.d.ts +6 -1
  102. package/dist/tools/retype.d.ts.map +1 -1
  103. package/dist/tools/retype.js +37 -33
  104. package/dist/tools/retype.js.map +1 -1
  105. package/dist/tools/set-scope.d.ts +6 -1
  106. package/dist/tools/set-scope.d.ts.map +1 -1
  107. package/dist/tools/set-scope.js +14 -10
  108. package/dist/tools/set-scope.js.map +1 -1
  109. package/dist/tools/status.d.ts +2 -1
  110. package/dist/tools/status.d.ts.map +1 -1
  111. package/dist/tools/status.js +24 -15
  112. package/dist/tools/status.js.map +1 -1
  113. package/dist/tools/support.d.ts +5 -3
  114. package/dist/tools/support.d.ts.map +1 -1
  115. package/dist/tools/support.js +9 -8
  116. package/dist/tools/support.js.map +1 -1
  117. package/dist/tools/types.d.ts +38 -0
  118. package/dist/tools/types.d.ts.map +1 -0
  119. package/dist/tools/types.js +17 -0
  120. package/dist/tools/types.js.map +1 -0
  121. package/dist/tools/upgrade.d.ts +2 -1
  122. package/dist/tools/upgrade.d.ts.map +1 -1
  123. package/dist/tools/upgrade.js +6 -4
  124. package/dist/tools/upgrade.js.map +1 -1
  125. package/package.json +2 -3
  126. package/dist/subgraph/index.d.ts +0 -7
  127. package/dist/subgraph/index.d.ts.map +0 -1
  128. package/dist/subgraph/index.js +0 -23
  129. package/dist/subgraph/index.js.map +0 -1
  130. package/dist/tools/migrate.d.ts +0 -88
  131. package/dist/tools/migrate.d.ts.map +0 -1
  132. package/dist/tools/migrate.js +0 -273
  133. package/dist/tools/migrate.js.map +0 -1
package/dist/index.js CHANGED
@@ -38,22 +38,21 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
38
38
  };
39
39
  Object.defineProperty(exports, "__esModule", { value: true });
40
40
  exports.getSessionId = void 0;
41
- const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
42
41
  const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
43
- const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
44
42
  const client_1 = require("@totalreclaw/client");
45
- const index_js_2 = require("./tools/index.js");
43
+ const index_js_1 = require("./tools/index.js");
46
44
  const status_js_1 = require("./tools/status.js");
47
- const remember_js_1 = require("./tools/remember.js");
48
45
  const consolidation_js_1 = require("./consolidation.js");
49
- const prompts_js_1 = require("./prompts.js");
50
- const index_js_3 = require("./resources/index.js");
46
+ const index_js_2 = require("./resources/index.js");
47
+ const server_setup_js_1 = require("./server-setup.js");
48
+ const dispatch_js_1 = require("./dispatch.js");
51
49
  // Subgraph imports (lazy usage -- only when managed service is active)
52
50
  const crypto_js_1 = require("./subgraph/crypto.js");
53
51
  const lsh_js_1 = require("./subgraph/lsh.js");
54
52
  const embedding_js_1 = require("./subgraph/embedding.js");
55
53
  const reranker_js_1 = require("./subgraph/reranker.js");
56
54
  const store_js_1 = require("./subgraph/store.js");
55
+ const chain_config_js_1 = require("./subgraph/chain-config.js");
57
56
  const search_js_1 = require("./subgraph/search.js");
58
57
  const confirm_indexed_js_1 = require("./subgraph/confirm-indexed.js");
59
58
  const contradiction_sync_js_1 = require("./contradiction-sync.js");
@@ -62,7 +61,7 @@ const retype_js_1 = require("./tools/retype.js");
62
61
  const set_scope_js_1 = require("./tools/set-scope.js");
63
62
  const claims_helper_js_1 = require("./claims-helper.js");
64
63
  const memory_types_js_1 = require("./memory-types.js");
65
- const remember_js_2 = require("./tools/remember.js");
64
+ const remember_js_1 = require("./tools/remember.js");
66
65
  const bip39_1 = require("@scure/bip39");
67
66
  const english_js_1 = require("@scure/bip39/wordlists/english.js");
68
67
  const accounts_1 = require("viem/accounts");
@@ -130,8 +129,8 @@ function resolveMnemonic() {
130
129
  return MASTER_PASSWORD.trim();
131
130
  // Priority 2: credentials.json mnemonic field
132
131
  try {
133
- const data = fs.readFileSync(setup_js_1.CREDENTIALS_PATH, 'utf-8');
134
- const parsed = JSON.parse(data);
132
+ const credentialsRaw = fs.readFileSync(setup_js_1.CREDENTIALS_PATH, 'utf-8');
133
+ const parsed = JSON.parse(credentialsRaw);
135
134
  if (parsed.mnemonic && typeof parsed.mnemonic === 'string') {
136
135
  const trimmed = parsed.mnemonic.trim();
137
136
  const words = trimmed.split(/\s+/);
@@ -199,6 +198,20 @@ function getMaxCandidatePool(k) {
199
198
  // Fallback to local formula
200
199
  return Math.max(k * 50, 400);
201
200
  }
201
+ /**
202
+ * Build the getSubgraphConfig override for a managed-service write, threading
203
+ * the billing-resolved chain + DataEdge onto every on-chain write site (#439).
204
+ */
205
+ function stateWriteOverrides(state) {
206
+ return (0, chain_config_js_1.buildSubgraphOverrides)({
207
+ relayUrl: state.serverUrl,
208
+ mnemonic: state.mnemonic,
209
+ authKeyHex: Buffer.from(state.authKey).toString('hex'),
210
+ walletAddress: state.smartAccountAddress,
211
+ chainId: state.chainId,
212
+ dataEdgeAddress: state.dataEdgeAddress,
213
+ });
214
+ }
202
215
  let subgraphState = null;
203
216
  /**
204
217
  * Detect server mode based on environment configuration.
@@ -254,12 +267,14 @@ async function initSubgraphState(mnemonic) {
254
267
  },
255
268
  });
256
269
  const smartAccountAddress = smartAccount.address.toLowerCase();
257
- // Determine chain ID: always auto-detect from billing tier.
258
- // Free tier → Base Sepolia (84532, testnet — Pimlico sponsors gas for free).
259
- // Pro tier → Gnosis mainnet (100, permanent on-chain storage).
260
- // TOTALRECLAW_CHAIN_ID user-facing override was removed in v1.
261
- let chainId = 84532; // default free tier
262
- // Auto-detect Pro tier from billing endpoint.
270
+ // Resolve chain + DataEdge from the relay's billing response, verbatim (#439).
271
+ // The relay is authoritative: it returns `chain_id` + `data_edge_address` in
272
+ // GET /v1/billing/status. After ops-1 both tiers run on Gnosis (chain 100);
273
+ // the legacy Free → Base Sepolia (84532) mapping was retired. Consuming the
274
+ // relay's values verbatim means a future chain move needs zero client release.
275
+ // (The client `TOTALRECLAW_CHAIN_ID` override was removed in v1.)
276
+ let chainId = 100; // Gnosis default when billing is unreachable
277
+ let dataEdgeAddress; // undefined ⇒ env/store default
263
278
  {
264
279
  try {
265
280
  const billingUrl = `${SERVER_URL.replace(/\/+$/, '')}/v1/billing/status?wallet_address=${encodeURIComponent(smartAccountAddress)}`;
@@ -272,14 +287,15 @@ async function initSubgraphState(mnemonic) {
272
287
  });
273
288
  if (resp.ok) {
274
289
  const billing = (await resp.json());
275
- if (billing.tier === 'pro') {
276
- chainId = 100;
277
- console.error('TotalReclaw: Pro tier detected — using Gnosis mainnet (chain 100).');
278
- }
290
+ const resolved = (0, chain_config_js_1.resolveChainConfig)(billing);
291
+ chainId = resolved.chainId;
292
+ dataEdgeAddress = resolved.dataEdgeAddress;
293
+ console.error(`TotalReclaw: tier=${billing.tier ?? 'unknown'}, chain=${chainId}` +
294
+ (dataEdgeAddress ? `, dataEdge=${dataEdgeAddress}` : '') + '.');
279
295
  }
280
296
  }
281
297
  catch {
282
- // Best-effort — default to free tier chain if billing is unreachable.
298
+ // Best-effort — fall back to the Gnosis default if billing is unreachable.
283
299
  }
284
300
  }
285
301
  // Register auth key with relay (idempotent — relay returns 200 for existing users).
@@ -305,6 +321,8 @@ async function initSubgraphState(mnemonic) {
305
321
  lshHasher,
306
322
  serverUrl: SERVER_URL,
307
323
  smartAccountAddress,
324
+ chainId,
325
+ dataEdgeAddress,
308
326
  };
309
327
  }
310
328
  const clientState = {
@@ -349,8 +367,8 @@ async function credentialsExist(path) {
349
367
  }
350
368
  async function loadCredentials(path) {
351
369
  const fs = await import('fs/promises');
352
- const data = await fs.readFile(path, 'utf-8');
353
- const parsed = JSON.parse(data);
370
+ const fileContents = await fs.readFile(path, 'utf-8');
371
+ const parsed = JSON.parse(fileContents);
354
372
  return {
355
373
  userId: parsed.userId,
356
374
  salt: Buffer.from(parsed.salt, 'hex'),
@@ -360,11 +378,11 @@ async function saveCredentials(path, credentials) {
360
378
  const fs = await import('fs/promises');
361
379
  const dir = path.substring(0, path.lastIndexOf('/'));
362
380
  await fs.mkdir(dir, { recursive: true }).catch(() => { });
363
- const data = {
381
+ const storedCredentials = {
364
382
  userId: credentials.userId,
365
383
  salt: credentials.salt.toString('hex'),
366
384
  };
367
- await fs.writeFile(path, JSON.stringify(data, null, 2), 'utf-8');
385
+ await fs.writeFile(path, JSON.stringify(storedCredentials, null, 2), 'utf-8');
368
386
  }
369
387
  // ── Subgraph handlers ───────────────────────────────────────────────────────
370
388
  /**
@@ -413,8 +431,8 @@ async function handleRememberSubgraph(state, args) {
413
431
  text: f.text.trim(),
414
432
  importance: f.importance ?? 5,
415
433
  type: resolveType(f.type),
416
- typeV1: (0, remember_js_2.normalizeTypeToV1)(f.type),
417
- scope: (0, remember_js_2.normalizeScope)(f.scope),
434
+ typeV1: (0, remember_js_1.normalizeTypeToV1)(f.type),
435
+ scope: (0, remember_js_1.normalizeScope)(f.scope),
418
436
  reasoning: typeof f.reasoning === 'string' && f.reasoning.trim().length > 0
419
437
  ? f.reasoning.trim()
420
438
  : undefined,
@@ -430,13 +448,13 @@ async function handleRememberSubgraph(state, args) {
430
448
  const topLevelReasoning = typeof input?.reasoning === 'string'
431
449
  ? input.reasoning
432
450
  : undefined;
433
- const resolvedScope = (0, remember_js_2.normalizeScope)(topLevelScope ?? singleMetadata?.scope);
451
+ const resolvedScope = (0, remember_js_1.normalizeScope)(topLevelScope ?? singleMetadata?.scope);
434
452
  const resolvedReasoning = topLevelReasoning ?? (typeof singleMetadata?.reasoning === 'string' ? singleMetadata.reasoning : undefined);
435
453
  textsToStore.push({
436
454
  text: factText.trim(),
437
455
  importance: input?.importance ?? 5,
438
456
  type: resolveType(singleMetadata?.type),
439
- typeV1: (0, remember_js_2.normalizeTypeToV1)(singleMetadata?.type),
457
+ typeV1: (0, remember_js_1.normalizeTypeToV1)(singleMetadata?.type),
440
458
  scope: resolvedScope,
441
459
  reasoning: resolvedReasoning && resolvedReasoning.trim().length > 0
442
460
  ? resolvedReasoning.trim()
@@ -722,12 +740,7 @@ async function handleRememberSubgraph(state, args) {
722
740
  // Batch-submit all payloads (tombstones + facts) in a single UserOp
723
741
  if (pendingPayloads.length > 0) {
724
742
  try {
725
- const batchConfig = (0, store_js_1.getSubgraphConfig)({
726
- relayUrl: state.serverUrl,
727
- mnemonic: state.mnemonic,
728
- authKeyHex: Buffer.from(state.authKey).toString('hex'),
729
- walletAddress: state.smartAccountAddress,
730
- });
743
+ const batchConfig = (0, store_js_1.getSubgraphConfig)(stateWriteOverrides(state));
731
744
  const batchResult = await (0, store_js_1.submitFactBatchOnChain)(pendingPayloads, batchConfig);
732
745
  for (const meta of pendingFactMeta) {
733
746
  results.push({
@@ -826,12 +839,7 @@ async function handleDebriefSubgraph(state, args) {
826
839
  agentId: 'mcp-server',
827
840
  encryptedEmbedding: encryptedEmb,
828
841
  };
829
- const batchConfig = (0, store_js_1.getSubgraphConfig)({
830
- relayUrl: state.serverUrl,
831
- mnemonic: state.mnemonic,
832
- authKeyHex: Buffer.from(state.authKey).toString('hex'),
833
- walletAddress: state.smartAccountAddress,
834
- });
842
+ const batchConfig = (0, store_js_1.getSubgraphConfig)(stateWriteOverrides(state));
835
843
  const batchResult = await (0, store_js_1.submitFactBatchOnChain)([(0, store_js_1.encodeFactProtobuf)(factPayload)], batchConfig);
836
844
  console.error(`Crystal debrief stored (tx=${batchResult.txHash.slice(0, 10)}...)`);
837
845
  return {
@@ -853,7 +861,7 @@ async function handleDebriefSubgraph(state, args) {
853
861
  }],
854
862
  };
855
863
  }
856
- const validated = (0, index_js_2.parseDebriefResponse)(JSON.stringify(factsInput));
864
+ const validated = (0, index_js_1.parseDebriefResponse)(JSON.stringify(factsInput));
857
865
  if (validated.length === 0) {
858
866
  return {
859
867
  content: [{ type: 'text', text: JSON.stringify({ success: true, stored: 0, message: 'No valid debrief items to store (filtered by validation)' }) }],
@@ -899,12 +907,7 @@ async function handleDebriefSubgraph(state, args) {
899
907
  const results = [];
900
908
  if (pendingPayloads.length > 0) {
901
909
  try {
902
- const batchConfig = (0, store_js_1.getSubgraphConfig)({
903
- relayUrl: state.serverUrl,
904
- mnemonic: state.mnemonic,
905
- authKeyHex: Buffer.from(state.authKey).toString('hex'),
906
- walletAddress: state.smartAccountAddress,
907
- });
910
+ const batchConfig = (0, store_js_1.getSubgraphConfig)(stateWriteOverrides(state));
908
911
  const batchResult = await (0, store_js_1.submitFactBatchOnChain)(pendingPayloads, batchConfig);
909
912
  for (const meta of pendingFactMeta) {
910
913
  results.push({ success: batchResult.success, fact_id: meta.factId, tx_hash: batchResult.txHash });
@@ -1050,8 +1053,10 @@ async function handleRecallSubgraph(state, args) {
1050
1053
  // argument is accepted for API stability but ignored -- core handles
1051
1054
  // intent-weighting internally based on per-candidate cosine scores.
1052
1055
  const reranked = (0, reranker_js_1.rerank)(query.trim(), queryEmbedding, decryptedCandidates, k, weights,
1053
- /* applySourceWeights (Retrieval v2 Tier 1) */ true);
1056
+ /* applySourceWeights (Retrieval v2 Tier 1) */ false);
1054
1057
  // 8. Format results
1058
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
1059
+ const subgraphCore = require('@totalreclaw/core');
1055
1060
  const memories = reranked.map((r) => ({
1056
1061
  fact_id: r.id,
1057
1062
  fact_text: r.text,
@@ -1066,6 +1071,9 @@ async function handleRecallSubgraph(state, args) {
1066
1071
  age_days: r.createdAt
1067
1072
  ? Math.floor((Date.now() / 1000 - r.createdAt) / 86400)
1068
1073
  : 0,
1074
+ date: r.createdAt != null
1075
+ ? subgraphCore.formatMemoryDate(BigInt(r.createdAt))
1076
+ : '',
1069
1077
  }));
1070
1078
  return {
1071
1079
  content: [{
@@ -1134,12 +1142,7 @@ async function handleForgetSubgraph(state, args) {
1134
1142
  agentId: 'mcp-server',
1135
1143
  };
1136
1144
  const protobuf = (0, store_js_1.encodeFactProtobuf)(tombstonePayload);
1137
- const config = (0, store_js_1.getSubgraphConfig)({
1138
- relayUrl: state.serverUrl,
1139
- mnemonic: state.mnemonic,
1140
- authKeyHex: Buffer.from(state.authKey).toString('hex'),
1141
- walletAddress: state.smartAccountAddress,
1142
- });
1145
+ const config = (0, store_js_1.getSubgraphConfig)(stateWriteOverrides(state));
1143
1146
  const { txHash, success } = await (0, store_js_1.submitFactOnChain)(protobuf, config);
1144
1147
  // Read-after-write: poll the subgraph until the fact is no longer
1145
1148
  // active (forget flips isActive=false). On timeout we still report
@@ -1203,14 +1206,9 @@ function buildPinDepsFromState(state) {
1203
1206
  return Buffer.from(base64, 'base64').toString('hex');
1204
1207
  },
1205
1208
  submitBatch: async (payloads) => {
1206
- const config = (0, store_js_1.getSubgraphConfig)({
1207
- relayUrl: state.serverUrl,
1208
- mnemonic: state.mnemonic,
1209
- authKeyHex: Buffer.from(state.authKey).toString('hex'),
1210
- walletAddress: state.smartAccountAddress,
1211
- });
1212
- const result = await (0, store_js_1.submitFactBatchOnChain)(payloads, config);
1213
- return { txHash: result.txHash, success: result.success };
1209
+ const config = (0, store_js_1.getSubgraphConfig)(stateWriteOverrides(state));
1210
+ const batchResult = await (0, store_js_1.submitFactBatchOnChain)(payloads, config);
1211
+ return { txHash: batchResult.txHash, success: batchResult.success };
1214
1212
  },
1215
1213
  generateIndices: async (text, entityNames) => {
1216
1214
  if (!text)
@@ -1234,12 +1232,12 @@ function buildPinDepsFromState(state) {
1234
1232
  },
1235
1233
  confirmIndexed: async (factId, expect) => {
1236
1234
  const subgraphUrl = process.env.TOTALRECLAW_SUBGRAPH_URL || `${state.serverUrl}/v1/subgraph`;
1237
- const result = await (0, confirm_indexed_js_1.confirmIndexed)(factId, {
1235
+ const confirmation = await (0, confirm_indexed_js_1.confirmIndexed)(factId, {
1238
1236
  subgraphUrl,
1239
1237
  authKeyHex: Buffer.from(state.authKey).toString('hex'),
1240
1238
  expect,
1241
1239
  });
1242
- return result.indexed;
1240
+ return confirmation.indexed;
1243
1241
  },
1244
1242
  };
1245
1243
  }
@@ -1269,238 +1267,6 @@ async function handleUnpinSubgraph(state, args) {
1269
1267
  const deps = buildPinDepsFromState(state);
1270
1268
  return await (0, pin_js_1.handleUnpinSubgraphWithDeps)(args, deps);
1271
1269
  }
1272
- // ── Migration handler ─────────────────────────────────────────────────────────
1273
- /** Maximum facts per UserOp batch during migration */
1274
- const MIGRATION_BATCH_SIZE = 15;
1275
- /**
1276
- * Handle the testnet-to-mainnet migration tool call.
1277
- *
1278
- * This function:
1279
- * 1. Validates the user is on subgraph mode with Pro tier
1280
- * 2. Fetches all active facts from the testnet (Base Sepolia) subgraph
1281
- * 3. Fetches existing mainnet content fingerprints for idempotency
1282
- * 4. In dry-run mode: returns a preview of what would be migrated
1283
- * 5. In confirm mode: re-encodes and batch-submits facts to mainnet
1284
- */
1285
- async function handleMigrateFromIndex(args) {
1286
- const input = args;
1287
- const confirm = input?.confirm === true;
1288
- // Must be in subgraph mode
1289
- if (!subgraphState) {
1290
- return {
1291
- content: [{
1292
- type: 'text',
1293
- text: JSON.stringify({
1294
- success: false,
1295
- error: 'Migration is only available with the managed service (subgraph mode). Self-hosted mode does not use chain-based storage.',
1296
- }),
1297
- }],
1298
- };
1299
- }
1300
- const authKeyHex = Buffer.from(subgraphState.authKey).toString('hex');
1301
- // 1. Check billing tier — must be Pro
1302
- const billing = await (0, index_js_2.checkBillingTier)(SERVER_URL, subgraphState.smartAccountAddress, authKeyHex);
1303
- if (billing.error) {
1304
- return {
1305
- content: [{
1306
- type: 'text',
1307
- text: JSON.stringify({
1308
- success: false,
1309
- error: `Failed to verify billing tier: ${billing.error}`,
1310
- }),
1311
- }],
1312
- };
1313
- }
1314
- if (billing.tier !== 'pro') {
1315
- return {
1316
- content: [{
1317
- type: 'text',
1318
- text: JSON.stringify({
1319
- success: false,
1320
- error: 'Migration requires Pro tier. Use totalreclaw_upgrade to upgrade first, then run migration.',
1321
- current_tier: billing.tier,
1322
- }),
1323
- }],
1324
- };
1325
- }
1326
- // 2. Fetch all active facts from the TESTNET subgraph
1327
- // The relay routes Pro users to the mainnet subgraph, so we need to
1328
- // explicitly request the testnet subgraph via the ?chain=testnet query param.
1329
- const testnetSubgraphUrl = `${SERVER_URL.replace(/\/+$/, '')}/v1/subgraph?chain=testnet`;
1330
- const mainnetSubgraphUrl = `${SERVER_URL.replace(/\/+$/, '')}/v1/subgraph`;
1331
- console.error(`[migrate] Fetching testnet facts for owner ${subgraphState.smartAccountAddress}...`);
1332
- const testnetFacts = await (0, index_js_2.fetchAllFactsFromSubgraph)(testnetSubgraphUrl, subgraphState.smartAccountAddress, authKeyHex);
1333
- if (testnetFacts.length === 0) {
1334
- return {
1335
- content: [{
1336
- type: 'text',
1337
- text: JSON.stringify({
1338
- success: true,
1339
- mode: 'dry_run',
1340
- testnet_facts: 0,
1341
- already_on_mainnet: 0,
1342
- to_migrate: 0,
1343
- migrated: 0,
1344
- failed_batches: 0,
1345
- batch_results: [],
1346
- message: 'No facts found on testnet. Nothing to migrate.',
1347
- }),
1348
- }],
1349
- };
1350
- }
1351
- // 3. Check which facts already exist on mainnet (by contentFp)
1352
- console.error(`[migrate] Checking mainnet for existing facts...`);
1353
- const mainnetFps = await (0, index_js_2.fetchMainnetContentFps)(mainnetSubgraphUrl, subgraphState.smartAccountAddress, authKeyHex);
1354
- // Filter to facts that need migration
1355
- const factsToMigrate = testnetFacts.filter(f => {
1356
- if (!f.contentFp)
1357
- return true; // No fingerprint — migrate it
1358
- return !mainnetFps.has(f.contentFp);
1359
- });
1360
- const alreadyOnMainnet = testnetFacts.length - factsToMigrate.length;
1361
- console.error(`[migrate] Testnet: ${testnetFacts.length} facts, already on mainnet: ${alreadyOnMainnet}, to migrate: ${factsToMigrate.length}`);
1362
- // 4. Dry-run mode: just report
1363
- if (!confirm) {
1364
- return {
1365
- content: [{
1366
- type: 'text',
1367
- text: JSON.stringify({
1368
- success: true,
1369
- mode: 'dry_run',
1370
- testnet_facts: testnetFacts.length,
1371
- already_on_mainnet: alreadyOnMainnet,
1372
- to_migrate: factsToMigrate.length,
1373
- migrated: 0,
1374
- failed_batches: 0,
1375
- batch_results: [],
1376
- message: factsToMigrate.length === 0
1377
- ? `All ${testnetFacts.length} testnet facts already exist on mainnet. Nothing to migrate.`
1378
- : `Found ${factsToMigrate.length} facts to migrate from testnet to Gnosis mainnet (${alreadyOnMainnet} already on mainnet). Call with confirm=true to proceed.`,
1379
- }),
1380
- }],
1381
- };
1382
- }
1383
- // 5. Execute migration: re-encode and batch-submit
1384
- if (factsToMigrate.length === 0) {
1385
- return {
1386
- content: [{
1387
- type: 'text',
1388
- text: JSON.stringify({
1389
- success: true,
1390
- mode: 'executed',
1391
- testnet_facts: testnetFacts.length,
1392
- already_on_mainnet: alreadyOnMainnet,
1393
- to_migrate: 0,
1394
- migrated: 0,
1395
- failed_batches: 0,
1396
- batch_results: [],
1397
- message: `All ${testnetFacts.length} testnet facts already exist on mainnet. Nothing to migrate.`,
1398
- }),
1399
- }],
1400
- };
1401
- }
1402
- // Fetch blind indices from testnet for all facts to migrate.
1403
- // The protobuf payload must include blind indices for the subgraph to create
1404
- // BlindIndex entities on mainnet (required for search to work).
1405
- console.error(`[migrate] Fetching blind indices for ${factsToMigrate.length} facts...`);
1406
- const factIdsToMigrate = factsToMigrate.map(f => f.id);
1407
- const blindIndicesMap = await (0, index_js_2.fetchBlindIndicesForFacts)(testnetSubgraphUrl, factIdsToMigrate, authKeyHex);
1408
- // Build protobuf payloads with blind indices
1409
- const finalPayloads = [];
1410
- for (const fact of factsToMigrate) {
1411
- const blobHex = fact.encryptedBlob.startsWith('0x')
1412
- ? fact.encryptedBlob.slice(2)
1413
- : fact.encryptedBlob;
1414
- const indices = blindIndicesMap.get(fact.id) || [];
1415
- const factPayload = {
1416
- id: fact.id,
1417
- timestamp: new Date().toISOString(),
1418
- owner: subgraphState.smartAccountAddress,
1419
- encryptedBlob: blobHex,
1420
- blindIndices: indices,
1421
- decayScore: parseFloat(fact.decayScore) || 0.5,
1422
- source: fact.source || 'migration',
1423
- contentFp: fact.contentFp || '',
1424
- agentId: fact.agentId || 'mcp-server',
1425
- encryptedEmbedding: fact.encryptedEmbedding || undefined,
1426
- };
1427
- finalPayloads.push((0, store_js_1.encodeFactProtobuf)(factPayload));
1428
- }
1429
- // Batch into groups of MIGRATION_BATCH_SIZE
1430
- const batches = [];
1431
- for (let i = 0; i < finalPayloads.length; i += MIGRATION_BATCH_SIZE) {
1432
- batches.push(finalPayloads.slice(i, i + MIGRATION_BATCH_SIZE));
1433
- }
1434
- console.error(`[migrate] Submitting ${finalPayloads.length} facts in ${batches.length} batch(es)...`);
1435
- const batchConfig = (0, store_js_1.getSubgraphConfig)({
1436
- relayUrl: subgraphState.serverUrl,
1437
- mnemonic: subgraphState.mnemonic,
1438
- authKeyHex,
1439
- walletAddress: subgraphState.smartAccountAddress,
1440
- });
1441
- let migrated = 0;
1442
- let failedBatches = 0;
1443
- const batchResults = [];
1444
- for (let i = 0; i < batches.length; i++) {
1445
- const batch = batches[i];
1446
- const batchNum = i + 1;
1447
- console.error(`[migrate] Batch ${batchNum}/${batches.length} (${batch.length} facts)...`);
1448
- try {
1449
- const result = await (0, store_js_1.submitFactBatchOnChain)(batch, batchConfig);
1450
- if (result.success) {
1451
- migrated += batch.length;
1452
- batchResults.push({
1453
- batch_number: batchNum,
1454
- size: batch.length,
1455
- success: true,
1456
- tx_hash: result.txHash,
1457
- });
1458
- console.error(`[migrate] Batch ${batchNum} succeeded (tx=${result.txHash.slice(0, 10)}...)`);
1459
- }
1460
- else {
1461
- failedBatches++;
1462
- batchResults.push({
1463
- batch_number: batchNum,
1464
- size: batch.length,
1465
- success: false,
1466
- tx_hash: result.txHash,
1467
- error: 'UserOp included but marked as failed',
1468
- });
1469
- console.error(`[migrate] Batch ${batchNum} included but failed (tx=${result.txHash.slice(0, 10)}...)`);
1470
- }
1471
- }
1472
- catch (err) {
1473
- failedBatches++;
1474
- const errMsg = err instanceof Error ? err.message : String(err);
1475
- batchResults.push({
1476
- batch_number: batchNum,
1477
- size: batch.length,
1478
- success: false,
1479
- error: errMsg,
1480
- });
1481
- console.error(`[migrate] Batch ${batchNum} error: ${errMsg}`);
1482
- }
1483
- }
1484
- const resultMessage = failedBatches === 0
1485
- ? `Successfully migrated ${migrated} memories from testnet to Gnosis mainnet in ${batches.length} batch(es).`
1486
- : `Migrated ${migrated}/${factsToMigrate.length} memories. ${failedBatches} batch(es) failed — re-run to retry (idempotent).`;
1487
- return {
1488
- content: [{
1489
- type: 'text',
1490
- text: JSON.stringify({
1491
- success: failedBatches === 0,
1492
- mode: 'executed',
1493
- testnet_facts: testnetFacts.length,
1494
- already_on_mainnet: alreadyOnMainnet,
1495
- to_migrate: factsToMigrate.length,
1496
- migrated,
1497
- failed_batches: failedBatches,
1498
- batch_results: batchResults,
1499
- message: resultMessage,
1500
- }),
1501
- }],
1502
- };
1503
- }
1504
1270
  // ── Auth error helper ────────────────────────────────────────────────────────
1505
1271
  const AUTH_HINT_MESSAGE = 'Authentication failed. If using a recovery phrase, check that all 12 words are in the correct order and spelled correctly.';
1506
1272
  /**
@@ -1534,7 +1300,7 @@ function quotaExceededResponse() {
1534
1300
  type: 'text',
1535
1301
  text: JSON.stringify({
1536
1302
  error: 'quota_exceeded',
1537
- message: 'Free tier limit reached. Upgrade to Pro for unlimited memories.',
1303
+ message: 'Free tier monthly limit reached (250 memories). Upgrade to Pro for 1,500 memories/month on Gnosis mainnet.',
1538
1304
  upgrade_url: 'Use totalreclaw_upgrade tool to get a checkout link',
1539
1305
  }),
1540
1306
  }],
@@ -1551,26 +1317,16 @@ function quotaExceededResponse() {
1551
1317
  // phrase from the OpenClaw / Hermes browser pair flow (or an offline BIP-39
1552
1318
  // generator) and paste it into the MCP host config themselves. No tool path
1553
1319
  // exists for the agent to ever see the phrase.
1554
- // ── Layer 1: Server with instructions ────────────────────────────────────────
1555
- const server = new index_js_1.Server({ name: 'totalreclaw', version: '1.0.0' }, {
1556
- capabilities: {
1557
- tools: {},
1558
- prompts: {},
1559
- resources: { subscribe: true, listChanged: true },
1560
- },
1561
- instructions: prompts_js_1.SERVER_INSTRUCTIONS,
1562
- });
1563
- // ── Wire up cache invalidation ───────────────────────────────────────────────
1564
- // When facts are stored, invalidate the memory context resource cache
1565
- (0, remember_js_1.setOnRememberCallback)(() => {
1566
- (0, index_js_3.invalidateMemoryContextCache)();
1567
- // Notify subscribed clients that the resource has been updated
1568
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1569
- });
1320
+ // ── Server wiring ─────────────────────────────────────────────────────────
1321
+ // The MCP `Server` is constructed in `main()` via `createTotalReclawServer`
1322
+ // (see `./server-setup.js`) and its request routing is delegated to the single
1323
+ // dispatch table in `./dispatch.js`. This section builds the mode-appropriate
1324
+ // handler bundles + cross-cutting deps the dispatcher needs.
1325
+ let server;
1570
1326
  // ── Client identification (resolved after initialize handshake) ──────────────
1571
1327
  function getClientIdentifier() {
1572
1328
  if (!clientIdentifierResolved) {
1573
- const clientInfo = server.getClientVersion();
1329
+ const clientInfo = server?.getClientVersion();
1574
1330
  if (clientInfo?.name) {
1575
1331
  const name = clientInfo.name.toLowerCase().replace(/\s+/g, '-');
1576
1332
  (0, client_id_js_1.setClientId)(`mcp-server:${name}`);
@@ -1580,441 +1336,152 @@ function getClientIdentifier() {
1580
1336
  }
1581
1337
  return (0, client_id_js_1.getClientId)();
1582
1338
  }
1583
- // ── Layer 2 + 3: Tool handlers ───────────────────────────────────────────────
1584
- server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
1585
- tools: [
1586
- index_js_2.rememberToolDefinition,
1587
- index_js_2.recallToolDefinition,
1588
- index_js_2.forgetToolDefinition,
1589
- index_js_2.exportToolDefinition,
1590
- index_js_2.importToolDefinition,
1591
- index_js_2.importFromToolDefinition,
1592
- index_js_2.importBatchToolDefinition,
1593
- index_js_2.consolidateToolDefinition,
1594
- index_js_2.statusToolDefinition,
1595
- index_js_2.upgradeToolDefinition,
1596
- index_js_2.migrateToolDefinition,
1597
- index_js_2.debriefToolDefinition,
1598
- index_js_2.supportToolDefinition,
1599
- index_js_2.accountToolDefinition,
1600
- pin_js_1.pinToolDefinition,
1601
- pin_js_1.unpinToolDefinition,
1602
- retype_js_1.retypeToolDefinition,
1603
- set_scope_js_1.setScopeToolDefinition,
1604
- index_js_2.pairToolDefinition,
1605
- ],
1606
- }));
1607
- server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
1608
- const { name, arguments: args } = request.params;
1609
- // `totalreclaw_setup` was removed in 3.2.1 (security: phrase-safety).
1610
- // Onboarding now follows the URL-driven flow at
1611
- // `docs/guides/claude-code-setup.md`. If a stale agent / host catalog
1612
- // still calls the old tool name, return a structured error pointing at
1613
- // the canonical install guide — without surfacing any phrase in payload.
1614
- if (name === 'totalreclaw_setup') {
1615
- return {
1616
- content: [{
1617
- type: 'text',
1618
- text: JSON.stringify({
1619
- error: 'tool_removed',
1620
- message: 'The totalreclaw_setup tool was removed in @totalreclaw/mcp-server@3.2.1 ' +
1621
- 'for phrase-safety. Follow the URL-driven install flow at ' +
1622
- 'https://github.com/p-diogo/totalreclaw/blob/main/docs/guides/claude-code-setup.md. ' +
1623
- 'The user sources their recovery phrase out-of-band (OpenClaw or Hermes ' +
1624
- 'browser pair flow, or an offline BIP-39 generator) and pastes it directly ' +
1625
- 'into TOTALRECLAW_RECOVERY_PHRASE in the MCP host config — never into chat.',
1626
- }),
1627
- }],
1628
- isError: true,
1629
- };
1630
- }
1631
- // Handle support tool (available in all modes, including unconfigured)
1632
- if (name === 'totalreclaw_support') {
1633
- const walletAddress = subgraphState?.smartAccountAddress ?? null;
1634
- return (0, index_js_2.handleSupport)(walletAddress);
1635
- }
1636
- // Handle pair tool (available in all modes — primary unconfigured-mode entry
1637
- // point so a user with no credentials can run an MCP-only install end-to-end:
1638
- // host adds MCP server → agent calls totalreclaw_pair → tool returns URL+PIN
1639
- // → user pairs in browser → server writes ~/.totalreclaw/credentials.json
1640
- // → user restarts host → server boots in subgraph mode).
1641
- if (name === 'totalreclaw_pair') {
1642
- return await (0, index_js_2.handlePair)(args);
1643
- }
1644
- // In unconfigured mode, all other tools return setup guidance pointing at
1645
- // the URL-driven install flow (NOT the deleted totalreclaw_setup tool).
1646
- if (currentMode === 'unconfigured') {
1647
- return {
1648
- content: [{
1649
- type: 'text',
1650
- text: JSON.stringify({
1651
- error: 'not_configured',
1652
- message: 'TotalReclaw is not configured yet. Follow the URL-driven install flow ' +
1653
- 'at https://github.com/p-diogo/totalreclaw/blob/main/docs/guides/claude-code-setup.md — ' +
1654
- 'the user pastes their recovery phrase directly into the MCP host config (TOTALRECLAW_RECOVERY_PHRASE), ' +
1655
- 'never into chat.',
1656
- }),
1657
- }],
1658
- isError: true,
1659
- };
1660
- }
1661
- const mode = subgraphState ? 'subgraph' : 'http';
1339
+ // ── Cross-cutting dispatch deps ──────────────────────────────────────────────
1340
+ /** Invalidate the memory-context resource cache + notify subscribed clients. */
1341
+ function onMutate() {
1342
+ (0, index_js_2.invalidateMemoryContextCache)();
1343
+ server
1344
+ ?.sendResourceUpdated({ uri: index_js_2.memoryContextResource.uri })
1345
+ .catch((err) => console.error('Failed to send resource update:', err));
1346
+ }
1347
+ /** Standard authentication-failure envelope (shared quota → auth funnel). */
1348
+ function authHintResponse() {
1349
+ return {
1350
+ content: [{ type: 'text', text: JSON.stringify({ error: AUTH_HINT_MESSAGE }) }],
1351
+ isError: true,
1352
+ };
1353
+ }
1354
+ // ── Mode-independent tool handlers (status / upgrade / account) ───────────────
1355
+ // These talk to the relay directly and behave identically in both storage
1356
+ // modes. `subgraphState` supplies the auth key + wallet when present.
1357
+ async function statusHandler(args) {
1358
+ const authKeyHex = subgraphState
1359
+ ? Buffer.from(subgraphState.authKey).toString('hex')
1360
+ : '';
1361
+ const enrichedArgs = {
1362
+ ...args,
1363
+ wallet_address: args?.wallet_address ||
1364
+ subgraphState?.smartAccountAddress,
1365
+ };
1366
+ const statusResult = await (0, index_js_1.handleStatus)({ serverUrl: SERVER_URL, authKeyHex }, enrichedArgs);
1367
+ // Cache billing features for candidate-pool sizing. handleStatus stores the
1368
+ // raw response; extract max_candidate_pool from it.
1662
1369
  try {
1663
- // ── Billing tools (mode-independent, always use HTTP relay) ────────────
1664
- if (name === 'totalreclaw_status') {
1665
- const authKeyHex = subgraphState
1666
- ? Buffer.from(subgraphState.authKey).toString('hex')
1667
- : '';
1668
- const enrichedArgs = {
1669
- ...args,
1670
- wallet_address: args?.wallet_address ||
1671
- subgraphState?.smartAccountAddress,
1370
+ const raw = (0, status_js_1.getLastBillingResponse)();
1371
+ if (raw?.features) {
1372
+ billingCache = {
1373
+ max_candidate_pool: raw.features.max_candidate_pool,
1374
+ checked_at: Date.now(),
1672
1375
  };
1673
- const statusResult = await (0, index_js_2.handleStatus)(SERVER_URL, authKeyHex, enrichedArgs);
1674
- // Cache billing features for candidate pool sizing.
1675
- // handleStatus stores the raw response; extract max_candidate_pool from it.
1676
- try {
1677
- const raw = (0, status_js_1.getLastBillingResponse)();
1678
- if (raw?.features) {
1679
- billingCache = {
1680
- max_candidate_pool: raw.features.max_candidate_pool,
1681
- checked_at: Date.now(),
1682
- };
1683
- }
1684
- }
1685
- catch {
1686
- // Best-effort cache — don't fail the status call
1687
- }
1688
- return statusResult;
1689
- }
1690
- if (name === 'totalreclaw_upgrade') {
1691
- const authKeyHex = subgraphState
1692
- ? Buffer.from(subgraphState.authKey).toString('hex')
1693
- : '';
1694
- return await (0, index_js_2.handleUpgrade)(SERVER_URL, authKeyHex, args);
1695
- }
1696
- if (name === 'totalreclaw_account') {
1697
- if (!subgraphState) {
1698
- return {
1699
- content: [{
1700
- type: 'text',
1701
- text: JSON.stringify({
1702
- error: 'Account details require managed service mode (subgraph). Self-hosted mode does not track billing.',
1703
- }),
1704
- }],
1705
- isError: true,
1706
- };
1707
- }
1708
- const authKeyHex = Buffer.from(subgraphState.authKey).toString('hex');
1709
- const words = subgraphState.mnemonic.split(/\s+/);
1710
- const mnemonicHint = `${words[0]} ... ${words[words.length - 1]}`;
1711
- const getFactCount = () => (0, search_js_1.getOwnerFactCount)(subgraphState.smartAccountAddress, subgraphState.serverUrl, authKeyHex);
1712
- return await (0, index_js_2.handleAccount)(SERVER_URL, authKeyHex, subgraphState.smartAccountAddress, mnemonicHint, getFactCount);
1713
- }
1714
- if (name === 'totalreclaw_migrate') {
1715
- return await handleMigrateFromIndex(args);
1716
- }
1717
- // ── Subgraph mode ─────────────────────────────────────────────────────
1718
- if (subgraphState) {
1719
- switch (name) {
1720
- case 'totalreclaw_remember': {
1721
- try {
1722
- const result = await handleRememberSubgraph(subgraphState, args);
1723
- // Invalidate cache after successful store
1724
- (0, index_js_3.invalidateMemoryContextCache)();
1725
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1726
- return result;
1727
- }
1728
- catch (error) {
1729
- if (isQuotaExceededError(error)) {
1730
- return quotaExceededResponse();
1731
- }
1732
- throw error;
1733
- }
1734
- }
1735
- case 'totalreclaw_recall':
1736
- return await handleRecallSubgraph(subgraphState, args);
1737
- case 'totalreclaw_forget': {
1738
- const result = await handleForgetSubgraph(subgraphState, args);
1739
- (0, index_js_3.invalidateMemoryContextCache)();
1740
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1741
- return result;
1742
- }
1743
- case 'totalreclaw_export':
1744
- // Export not yet implemented for the managed service -- fall through to error
1745
- return {
1746
- content: [{
1747
- type: 'text',
1748
- text: JSON.stringify({
1749
- error: 'Export is not yet supported with the managed service. Use self-hosted mode for export.',
1750
- }),
1751
- }],
1752
- isError: true,
1753
- };
1754
- case 'totalreclaw_import':
1755
- return {
1756
- content: [{
1757
- type: 'text',
1758
- text: JSON.stringify({
1759
- error: 'Import is not yet supported with the managed service. Use self-hosted mode for import.',
1760
- }),
1761
- }],
1762
- isError: true,
1763
- };
1764
- case 'totalreclaw_import_from':
1765
- return {
1766
- content: [{
1767
- type: 'text',
1768
- text: JSON.stringify({
1769
- error: 'Import from external sources is not yet supported with the managed service. Use self-hosted mode for import.',
1770
- }),
1771
- }],
1772
- isError: true,
1773
- };
1774
- case 'totalreclaw_consolidate':
1775
- return {
1776
- content: [{
1777
- type: 'text',
1778
- text: JSON.stringify({
1779
- error: 'Consolidation is not supported with the managed service. On-chain facts require tombstone-based dedup which is handled automatically at store time.',
1780
- }),
1781
- }],
1782
- isError: true,
1783
- };
1784
- case 'totalreclaw_debrief': {
1785
- try {
1786
- const result = await handleDebriefSubgraph(subgraphState, args);
1787
- (0, index_js_3.invalidateMemoryContextCache)();
1788
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1789
- return result;
1790
- }
1791
- catch (error) {
1792
- if (isQuotaExceededError(error)) {
1793
- return quotaExceededResponse();
1794
- }
1795
- throw error;
1796
- }
1797
- }
1798
- case 'totalreclaw_pin': {
1799
- try {
1800
- const result = await handlePinSubgraph(subgraphState, args);
1801
- (0, index_js_3.invalidateMemoryContextCache)();
1802
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1803
- return result;
1804
- }
1805
- catch (error) {
1806
- if (isQuotaExceededError(error)) {
1807
- return quotaExceededResponse();
1808
- }
1809
- throw error;
1810
- }
1811
- }
1812
- case 'totalreclaw_unpin': {
1813
- try {
1814
- const result = await handleUnpinSubgraph(subgraphState, args);
1815
- (0, index_js_3.invalidateMemoryContextCache)();
1816
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1817
- return result;
1818
- }
1819
- catch (error) {
1820
- if (isQuotaExceededError(error)) {
1821
- return quotaExceededResponse();
1822
- }
1823
- throw error;
1824
- }
1825
- }
1826
- case 'totalreclaw_retype': {
1827
- try {
1828
- const deps = buildMetadataOpDepsFromState(subgraphState);
1829
- const result = await (0, retype_js_1.handleRetypeWithDeps)(args, deps);
1830
- (0, index_js_3.invalidateMemoryContextCache)();
1831
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1832
- return result;
1833
- }
1834
- catch (error) {
1835
- if (isQuotaExceededError(error)) {
1836
- return quotaExceededResponse();
1837
- }
1838
- throw error;
1839
- }
1840
- }
1841
- case 'totalreclaw_set_scope': {
1842
- try {
1843
- const deps = buildMetadataOpDepsFromState(subgraphState);
1844
- const result = await (0, set_scope_js_1.handleSetScopeWithDeps)(args, deps);
1845
- (0, index_js_3.invalidateMemoryContextCache)();
1846
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1847
- return result;
1848
- }
1849
- catch (error) {
1850
- if (isQuotaExceededError(error)) {
1851
- return quotaExceededResponse();
1852
- }
1853
- throw error;
1854
- }
1855
- }
1856
- default:
1857
- return {
1858
- content: [{
1859
- type: 'text',
1860
- text: JSON.stringify({ error: `Unknown tool: ${name}` }),
1861
- }],
1862
- isError: true,
1863
- };
1864
- }
1865
- }
1866
- // ── HTTP mode (existing behavior) ─────────────────────────────────────
1867
- const client = await getClient();
1868
- switch (name) {
1869
- case 'totalreclaw_remember': {
1870
- try {
1871
- const result = await (0, index_js_2.handleRemember)(client, args);
1872
- return result;
1873
- }
1874
- catch (error) {
1875
- if (isQuotaExceededError(error)) {
1876
- return quotaExceededResponse();
1877
- }
1878
- throw error;
1879
- }
1880
- }
1881
- case 'totalreclaw_recall':
1882
- return await (0, index_js_2.handleRecall)(client, args);
1883
- case 'totalreclaw_forget': {
1884
- const result = await (0, index_js_2.handleForget)(client, args);
1885
- // Invalidate cache on forget too
1886
- (0, index_js_3.invalidateMemoryContextCache)();
1887
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1888
- return result;
1889
- }
1890
- case 'totalreclaw_export':
1891
- return await (0, index_js_2.handleExport)(client, args);
1892
- case 'totalreclaw_import':
1893
- return await (0, index_js_2.handleImport)(client, args);
1894
- case 'totalreclaw_import_from':
1895
- return await (0, index_js_2.handleImportFrom)(client, args);
1896
- case 'totalreclaw_import_batch':
1897
- return await (0, index_js_2.handleImportBatch)(args);
1898
- case 'totalreclaw_consolidate': {
1899
- const result = await (0, index_js_2.handleConsolidate)(client, args);
1900
- // Invalidate cache after consolidation (facts may have been deleted)
1901
- (0, index_js_3.invalidateMemoryContextCache)();
1902
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1903
- return result;
1904
- }
1905
- case 'totalreclaw_debrief': {
1906
- try {
1907
- const result = await (0, index_js_2.handleDebrief)(client, args);
1908
- return result;
1909
- }
1910
- catch (error) {
1911
- if (isQuotaExceededError(error)) {
1912
- return quotaExceededResponse();
1913
- }
1914
- throw error;
1915
- }
1916
- }
1917
- case 'totalreclaw_pin':
1918
- return await (0, pin_js_1.handlePin)(args);
1919
- case 'totalreclaw_unpin':
1920
- return await (0, pin_js_1.handleUnpin)(args);
1921
- case 'totalreclaw_retype':
1922
- return await (0, retype_js_1.handleRetype)(args);
1923
- case 'totalreclaw_set_scope':
1924
- return await (0, set_scope_js_1.handleSetScope)(args);
1925
- default:
1926
- return {
1927
- content: [{
1928
- type: 'text',
1929
- text: JSON.stringify({ error: `Unknown tool: ${name}` }),
1930
- }],
1931
- isError: true,
1932
- };
1933
1376
  }
1934
1377
  }
1935
- catch (error) {
1936
- // Final catch-all: check for quota error at the top level too
1937
- if (isQuotaExceededError(error)) {
1938
- return quotaExceededResponse();
1939
- }
1940
- // Provide a helpful hint for authentication failures
1941
- if (isAuthError(error)) {
1942
- return {
1943
- content: [{
1944
- type: 'text',
1945
- text: JSON.stringify({
1946
- error: AUTH_HINT_MESSAGE,
1947
- }),
1948
- }],
1949
- isError: true,
1950
- };
1951
- }
1378
+ catch {
1379
+ // Best-effort cache — don't fail the status call.
1380
+ }
1381
+ return statusResult;
1382
+ }
1383
+ async function upgradeHandler(args) {
1384
+ const authKeyHex = subgraphState
1385
+ ? Buffer.from(subgraphState.authKey).toString('hex')
1386
+ : '';
1387
+ return (0, index_js_1.handleUpgrade)({ serverUrl: SERVER_URL, authKeyHex }, args);
1388
+ }
1389
+ async function accountHandler(args) {
1390
+ if (!subgraphState) {
1952
1391
  return {
1953
1392
  content: [{
1954
1393
  type: 'text',
1955
1394
  text: JSON.stringify({
1956
- error: error instanceof Error ? error.message : 'Unknown error',
1395
+ error: 'Account details require managed service mode (subgraph). Self-hosted mode does not track billing.',
1957
1396
  }),
1958
1397
  }],
1959
1398
  isError: true,
1960
1399
  };
1961
1400
  }
1962
- });
1963
- // ── Layer 4: Resources ───────────────────────────────────────────────────────
1964
- server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => ({
1965
- resources: [index_js_3.memoryContextResource],
1966
- }));
1967
- server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request) => {
1968
- const { uri } = request.params;
1969
- if (uri === index_js_3.memoryContextResource.uri) {
1970
- // With the managed service, resource reading is not supported yet
1971
- if (subgraphState) {
1972
- return {
1973
- contents: [
1974
- {
1975
- uri: index_js_3.memoryContextResource.uri,
1976
- mimeType: 'text/markdown',
1977
- text: '*Memory context resource is not available with the managed service. Use totalreclaw_recall to search memories.*',
1978
- },
1979
- ],
1980
- };
1981
- }
1982
- const client = await getClient();
1983
- const content = await (0, index_js_3.readMemoryContext)(client);
1984
- return {
1985
- contents: [
1986
- {
1987
- uri: index_js_3.memoryContextResource.uri,
1988
- mimeType: 'text/markdown',
1989
- text: content,
1990
- },
1991
- ],
1992
- };
1993
- }
1994
- throw new Error(`Unknown resource: ${uri}`);
1995
- });
1996
- // ── Layer 5: Prompts ─────────────────────────────────────────────────────────
1997
- server.setRequestHandler(types_js_1.ListPromptsRequestSchema, async () => ({
1998
- prompts: [
1999
- // Legacy instructions prompt (backward compat)
2000
- {
2001
- name: 'totalreclaw_instructions',
2002
- description: 'Instructions for using TotalReclaw tools',
2003
- },
2004
- // New auto-memory prompt fallbacks
2005
- ...prompts_js_1.PROMPT_DEFINITIONS,
2006
- ],
2007
- }));
2008
- server.setRequestHandler(types_js_1.GetPromptRequestSchema, async (request) => {
2009
- const { name, arguments: args } = request.params;
2010
- const messages = (0, prompts_js_1.getPromptMessages)(name, args);
2011
- return { messages };
1401
+ const authKeyHex = Buffer.from(subgraphState.authKey).toString('hex');
1402
+ const words = subgraphState.mnemonic.split(/\s+/);
1403
+ const mnemonicHint = `${words[0]} ... ${words[words.length - 1]}`;
1404
+ const getFactCount = () => (0, search_js_1.getOwnerFactCount)(subgraphState.smartAccountAddress, subgraphState.serverUrl, authKeyHex);
1405
+ return (0, index_js_1.handleAccount)({
1406
+ serverUrl: SERVER_URL,
1407
+ authKeyHex,
1408
+ walletAddress: subgraphState.smartAccountAddress,
1409
+ mnemonicHint,
1410
+ getFactCount,
1411
+ }, args);
1412
+ }
1413
+ const commonHandlers = {
1414
+ totalreclaw_status: statusHandler,
1415
+ totalreclaw_upgrade: upgradeHandler,
1416
+ totalreclaw_account: accountHandler,
1417
+ };
1418
+ // ── Managed-service (subgraph) tool bundle ───────────────────────────────────
1419
+ // Tools with no managed-service equivalent return an explicit "use self-hosted
1420
+ // mode" envelope; `totalreclaw_import_batch` is intentionally absent so it
1421
+ // falls through to the standard unknown-tool error, matching pre-refactor
1422
+ // behaviour.
1423
+ function unsupportedInSubgraph(message) {
1424
+ return { content: [{ type: 'text', text: JSON.stringify({ error: message }) }], isError: true };
1425
+ }
1426
+ function subgraphBundle(state) {
1427
+ return {
1428
+ totalreclaw_remember: (args) => handleRememberSubgraph(state, args),
1429
+ totalreclaw_recall: (args) => handleRecallSubgraph(state, args),
1430
+ totalreclaw_forget: (args) => handleForgetSubgraph(state, args),
1431
+ totalreclaw_debrief: (args) => handleDebriefSubgraph(state, args),
1432
+ totalreclaw_pin: (args) => handlePinSubgraph(state, args),
1433
+ totalreclaw_unpin: (args) => handleUnpinSubgraph(state, args),
1434
+ totalreclaw_retype: (args) => (0, retype_js_1.handleRetypeWithDeps)(args, buildMetadataOpDepsFromState(state)),
1435
+ totalreclaw_set_scope: (args) => (0, set_scope_js_1.handleSetScopeWithDeps)(args, buildMetadataOpDepsFromState(state)),
1436
+ totalreclaw_export: async () => unsupportedInSubgraph('Export is not yet supported with the managed service. Use self-hosted mode for export.'),
1437
+ totalreclaw_import: async () => unsupportedInSubgraph('Import is not yet supported with the managed service. Use self-hosted mode for import.'),
1438
+ totalreclaw_import_from: async () => unsupportedInSubgraph('Import from external sources is not yet supported with the managed service. Use self-hosted mode for import.'),
1439
+ totalreclaw_consolidate: async () => unsupportedInSubgraph('Consolidation is not supported with the managed service. On-chain facts require tombstone-based dedup which is handled automatically at store time.'),
1440
+ };
1441
+ }
1442
+ // ── Self-hosted (HTTP) tool bundle ───────────────────────────────────────────
1443
+ function httpBundle(ctx) {
1444
+ return {
1445
+ totalreclaw_remember: (args) => (0, index_js_1.handleRemember)(ctx, args),
1446
+ totalreclaw_recall: (args) => (0, index_js_1.handleRecall)(ctx, args),
1447
+ totalreclaw_forget: (args) => (0, index_js_1.handleForget)(ctx, args),
1448
+ totalreclaw_export: (args) => (0, index_js_1.handleExport)(ctx, args),
1449
+ totalreclaw_import: (args) => (0, index_js_1.handleImport)(ctx, args),
1450
+ totalreclaw_import_from: (args) => (0, index_js_1.handleImportFrom)(ctx, args),
1451
+ totalreclaw_import_batch: (args) => (0, index_js_1.handleImportBatch)(ctx, args),
1452
+ totalreclaw_consolidate: (args) => (0, index_js_1.handleConsolidate)(ctx, args),
1453
+ totalreclaw_debrief: (args) => (0, index_js_1.handleDebrief)(ctx, args),
1454
+ totalreclaw_pin: (args) => (0, pin_js_1.handlePin)(ctx, args),
1455
+ totalreclaw_unpin: (args) => (0, pin_js_1.handleUnpin)(ctx, args),
1456
+ totalreclaw_retype: (args) => (0, retype_js_1.handleRetype)(ctx, args),
1457
+ totalreclaw_set_scope: (args) => (0, set_scope_js_1.handleSetScope)(ctx, args),
1458
+ };
1459
+ }
1460
+ /** Resolve the handler bundle for the current storage mode. */
1461
+ async function resolveBundle(mode) {
1462
+ if (mode === 'subgraph')
1463
+ return subgraphBundle(subgraphState);
1464
+ const client = await getClient();
1465
+ return httpBundle({ client });
1466
+ }
1467
+ // ── The single CallTool router ───────────────────────────────────────────────
1468
+ const callToolHandler = (0, dispatch_js_1.createCallToolHandler)({
1469
+ getMode: () => currentMode,
1470
+ handleSupport: (args) => (0, index_js_1.handleSupport)({ walletAddress: subgraphState?.smartAccountAddress ?? null }, args),
1471
+ handlePair: (args) => (0, index_js_1.handlePair)({}, args),
1472
+ common: commonHandlers,
1473
+ resolveBundle,
1474
+ isQuotaExceededError,
1475
+ quotaExceededResponse,
1476
+ isAuthError,
1477
+ authHintResponse,
1478
+ onMutate,
2012
1479
  });
2013
1480
  // ── Show-phrase CLI subcommand ────────────────────────────────────────────────
2014
1481
  async function showPhrase() {
2015
1482
  try {
2016
- const data = fs.readFileSync(setup_js_1.CREDENTIALS_PATH, 'utf-8');
2017
- const parsed = JSON.parse(data);
1483
+ const credentialsRaw = fs.readFileSync(setup_js_1.CREDENTIALS_PATH, 'utf-8');
1484
+ const parsed = JSON.parse(credentialsRaw);
2018
1485
  if (parsed.mnemonic) {
2019
1486
  console.log(parsed.mnemonic);
2020
1487
  }
@@ -2069,6 +1536,14 @@ async function main() {
2069
1536
  // recovery phrase never crosses into the extraction LLM — see the
2070
1537
  // top-of-file rationale in `extraction/extractor.ts`.
2071
1538
  startPollerSafely();
1539
+ // Construct the MCP server and wire its request handlers to the single
1540
+ // dispatch router. Created here (not at module load) so importing this file
1541
+ // in tests does not stand up a server or connect a transport.
1542
+ server = (0, server_setup_js_1.createTotalReclawServer)({
1543
+ callTool: callToolHandler,
1544
+ isManagedMode: () => !!subgraphState,
1545
+ getClient,
1546
+ });
2072
1547
  const transport = new stdio_js_1.StdioServerTransport();
2073
1548
  await server.connect(transport);
2074
1549
  }