@totalreclaw/mcp-server 1.0.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/README.md +113 -0
- package/dist/cli/setup.d.ts +43 -0
- package/dist/cli/setup.d.ts.map +1 -0
- package/dist/cli/setup.js +276 -0
- package/dist/cli/setup.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +700 -0
- package/dist/index.js.map +1 -0
- package/dist/prompts.d.ts +27 -0
- package/dist/prompts.d.ts.map +1 -0
- package/dist/prompts.js +219 -0
- package/dist/prompts.js.map +1 -0
- package/dist/resources/index.d.ts +2 -0
- package/dist/resources/index.d.ts.map +1 -0
- package/dist/resources/index.js +8 -0
- package/dist/resources/index.js.map +1 -0
- package/dist/resources/memory-context.d.ts +16 -0
- package/dist/resources/memory-context.d.ts.map +1 -0
- package/dist/resources/memory-context.js +111 -0
- package/dist/resources/memory-context.js.map +1 -0
- package/dist/server.d.ts +4 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +25 -0
- package/dist/server.js.map +1 -0
- package/dist/subgraph/crypto.d.ts +106 -0
- package/dist/subgraph/crypto.d.ts.map +1 -0
- package/dist/subgraph/crypto.js +287 -0
- package/dist/subgraph/crypto.js.map +1 -0
- package/dist/subgraph/embedding.d.ts +47 -0
- package/dist/subgraph/embedding.d.ts.map +1 -0
- package/dist/subgraph/embedding.js +77 -0
- package/dist/subgraph/embedding.js.map +1 -0
- package/dist/subgraph/index.d.ts +7 -0
- package/dist/subgraph/index.d.ts.map +1 -0
- package/dist/subgraph/index.js +23 -0
- package/dist/subgraph/index.js.map +1 -0
- package/dist/subgraph/lsh.d.ts +95 -0
- package/dist/subgraph/lsh.d.ts.map +1 -0
- package/dist/subgraph/lsh.js +211 -0
- package/dist/subgraph/lsh.js.map +1 -0
- package/dist/subgraph/reranker.d.ts +157 -0
- package/dist/subgraph/reranker.d.ts.map +1 -0
- package/dist/subgraph/reranker.js +427 -0
- package/dist/subgraph/reranker.js.map +1 -0
- package/dist/subgraph/search.d.ts +62 -0
- package/dist/subgraph/search.d.ts.map +1 -0
- package/dist/subgraph/search.js +208 -0
- package/dist/subgraph/search.js.map +1 -0
- package/dist/subgraph/store.d.ts +97 -0
- package/dist/subgraph/store.d.ts.map +1 -0
- package/dist/subgraph/store.js +270 -0
- package/dist/subgraph/store.js.map +1 -0
- package/dist/tools/export.d.ts +48 -0
- package/dist/tools/export.d.ts.map +1 -0
- package/dist/tools/export.js +126 -0
- package/dist/tools/export.js.map +1 -0
- package/dist/tools/forget.d.ts +43 -0
- package/dist/tools/forget.d.ts.map +1 -0
- package/dist/tools/forget.js +96 -0
- package/dist/tools/forget.js.map +1 -0
- package/dist/tools/import.d.ts +73 -0
- package/dist/tools/import.d.ts.map +1 -0
- package/dist/tools/import.js +248 -0
- package/dist/tools/import.js.map +1 -0
- package/dist/tools/index.d.ts +8 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +25 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/recall.d.ts +65 -0
- package/dist/tools/recall.d.ts.map +1 -0
- package/dist/tools/recall.js +113 -0
- package/dist/tools/recall.js.map +1 -0
- package/dist/tools/remember.d.ts +109 -0
- package/dist/tools/remember.d.ts.map +1 -0
- package/dist/tools/remember.js +227 -0
- package/dist/tools/remember.js.map +1 -0
- package/dist/tools/status.d.ts +43 -0
- package/dist/tools/status.d.ts.map +1 -0
- package/dist/tools/status.js +110 -0
- package/dist/tools/status.js.map +1 -0
- package/dist/tools/upgrade.d.ts +48 -0
- package/dist/tools/upgrade.d.ts.map +1 -0
- package/dist/tools/upgrade.js +122 -0
- package/dist/tools/upgrade.js.map +1 -0
- package/package.json +61 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,700 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
4
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
5
|
+
};
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
|
|
8
|
+
const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
|
|
9
|
+
const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
|
|
10
|
+
const client_1 = require("@totalreclaw/client");
|
|
11
|
+
const index_js_2 = require("./tools/index.js");
|
|
12
|
+
const remember_js_1 = require("./tools/remember.js");
|
|
13
|
+
const prompts_js_1 = require("./prompts.js");
|
|
14
|
+
const index_js_3 = require("./resources/index.js");
|
|
15
|
+
// Subgraph imports (lazy usage -- only when subgraph mode is active)
|
|
16
|
+
const crypto_js_1 = require("./subgraph/crypto.js");
|
|
17
|
+
const lsh_js_1 = require("./subgraph/lsh.js");
|
|
18
|
+
const embedding_js_1 = require("./subgraph/embedding.js");
|
|
19
|
+
const reranker_js_1 = require("./subgraph/reranker.js");
|
|
20
|
+
const store_js_1 = require("./subgraph/store.js");
|
|
21
|
+
const search_js_1 = require("./subgraph/search.js");
|
|
22
|
+
const bip39_1 = require("@scure/bip39");
|
|
23
|
+
const english_js_1 = require("@scure/bip39/wordlists/english.js");
|
|
24
|
+
const accounts_1 = require("viem/accounts");
|
|
25
|
+
const node_crypto_1 = __importDefault(require("node:crypto"));
|
|
26
|
+
// ── Configuration ───────────────────────────────────────────────────────────
|
|
27
|
+
const SERVER_URL = process.env.TOTALRECLAW_SERVER_URL || 'http://127.0.0.1:8080';
|
|
28
|
+
const DEFAULT_NAMESPACE = process.env.TOTALRECLAW_NAMESPACE || 'default';
|
|
29
|
+
const MASTER_PASSWORD = process.env.TOTALRECLAW_MASTER_PASSWORD;
|
|
30
|
+
let subgraphState = null;
|
|
31
|
+
/**
|
|
32
|
+
* Detect server mode based on environment configuration.
|
|
33
|
+
*
|
|
34
|
+
* Subgraph mode requires:
|
|
35
|
+
* 1. TOTALRECLAW_MASTER_PASSWORD is a valid BIP-39 mnemonic
|
|
36
|
+
* 2. TOTALRECLAW_SUBGRAPH_MODE=true
|
|
37
|
+
*/
|
|
38
|
+
function detectServerMode() {
|
|
39
|
+
if (!MASTER_PASSWORD)
|
|
40
|
+
return 'http';
|
|
41
|
+
if (process.env.TOTALRECLAW_SUBGRAPH_MODE !== 'true')
|
|
42
|
+
return 'http';
|
|
43
|
+
const words = MASTER_PASSWORD.trim().split(/\s+/);
|
|
44
|
+
if (words.length !== 12 && words.length !== 24)
|
|
45
|
+
return 'http';
|
|
46
|
+
if (!(0, bip39_1.validateMnemonic)(MASTER_PASSWORD.trim(), english_js_1.wordlist))
|
|
47
|
+
return 'http';
|
|
48
|
+
return 'subgraph';
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Initialize subgraph state from the BIP-39 mnemonic.
|
|
52
|
+
* Derives all cryptographic keys and creates the LSH hasher.
|
|
53
|
+
*/
|
|
54
|
+
function initSubgraphState() {
|
|
55
|
+
const mnemonic = MASTER_PASSWORD.trim();
|
|
56
|
+
const { authKey, encryptionKey, dedupKey, salt } = (0, crypto_js_1.deriveKeys)(mnemonic);
|
|
57
|
+
// Derive LSH seed and create hasher
|
|
58
|
+
const lshSeed = (0, crypto_js_1.deriveLshSeed)(mnemonic, salt);
|
|
59
|
+
const dims = (0, embedding_js_1.getEmbeddingDims)(); // 384 for bge-small-en-v1.5
|
|
60
|
+
const lshHasher = new lsh_js_1.LSHHasher(lshSeed, dims);
|
|
61
|
+
// Derive Smart Account address from mnemonic
|
|
62
|
+
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;
|
|
66
|
+
return {
|
|
67
|
+
mode: 'subgraph',
|
|
68
|
+
mnemonic,
|
|
69
|
+
authKey,
|
|
70
|
+
encryptionKey,
|
|
71
|
+
dedupKey,
|
|
72
|
+
salt,
|
|
73
|
+
lshHasher,
|
|
74
|
+
serverUrl: SERVER_URL,
|
|
75
|
+
smartAccountAddress,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
const clientState = {
|
|
79
|
+
client: null,
|
|
80
|
+
userId: null,
|
|
81
|
+
salt: null,
|
|
82
|
+
};
|
|
83
|
+
async function getClient() {
|
|
84
|
+
if (clientState.client && clientState.client.isReady()) {
|
|
85
|
+
return clientState.client;
|
|
86
|
+
}
|
|
87
|
+
const client = new client_1.TotalReclaw({ serverUrl: SERVER_URL });
|
|
88
|
+
await client.init();
|
|
89
|
+
const credentialsPath = process.env.TOTALRECLAW_CREDENTIALS_PATH || '/workspace/.totalreclaw/credentials.json';
|
|
90
|
+
if (await credentialsExist(credentialsPath)) {
|
|
91
|
+
const credentials = await loadCredentials(credentialsPath);
|
|
92
|
+
await client.login(credentials.userId, MASTER_PASSWORD || 'default-password', credentials.salt);
|
|
93
|
+
clientState.userId = credentials.userId;
|
|
94
|
+
clientState.salt = credentials.salt;
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
const userId = await client.register(MASTER_PASSWORD || 'default-password');
|
|
98
|
+
clientState.userId = userId;
|
|
99
|
+
clientState.salt = client.getSalt();
|
|
100
|
+
await saveCredentials(credentialsPath, {
|
|
101
|
+
userId: clientState.userId,
|
|
102
|
+
salt: clientState.salt,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
clientState.client = client;
|
|
106
|
+
return client;
|
|
107
|
+
}
|
|
108
|
+
async function credentialsExist(path) {
|
|
109
|
+
try {
|
|
110
|
+
const fs = await import('fs/promises');
|
|
111
|
+
await fs.access(path);
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
async function loadCredentials(path) {
|
|
119
|
+
const fs = await import('fs/promises');
|
|
120
|
+
const data = await fs.readFile(path, 'utf-8');
|
|
121
|
+
const parsed = JSON.parse(data);
|
|
122
|
+
return {
|
|
123
|
+
userId: parsed.userId,
|
|
124
|
+
salt: Buffer.from(parsed.salt, 'hex'),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
async function saveCredentials(path, credentials) {
|
|
128
|
+
const fs = await import('fs/promises');
|
|
129
|
+
const dir = path.substring(0, path.lastIndexOf('/'));
|
|
130
|
+
await fs.mkdir(dir, { recursive: true }).catch(() => { });
|
|
131
|
+
const data = {
|
|
132
|
+
userId: credentials.userId,
|
|
133
|
+
salt: credentials.salt.toString('hex'),
|
|
134
|
+
};
|
|
135
|
+
await fs.writeFile(path, JSON.stringify(data, null, 2), 'utf-8');
|
|
136
|
+
}
|
|
137
|
+
// ── Subgraph handlers ───────────────────────────────────────────────────────
|
|
138
|
+
/**
|
|
139
|
+
* Encrypt an embedding vector for on-chain storage.
|
|
140
|
+
*
|
|
141
|
+
* Concatenates the float array into a Buffer, encrypts with AES-256-GCM,
|
|
142
|
+
* and returns base64. The subgraph stores this as a string field.
|
|
143
|
+
*/
|
|
144
|
+
function encryptEmbedding(embedding, encryptionKey) {
|
|
145
|
+
const buf = Buffer.alloc(embedding.length * 4);
|
|
146
|
+
for (let i = 0; i < embedding.length; i++) {
|
|
147
|
+
buf.writeFloatLE(embedding[i], i * 4);
|
|
148
|
+
}
|
|
149
|
+
return (0, crypto_js_1.encrypt)(buf.toString('base64'), encryptionKey);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Decrypt an encrypted embedding back to a number array.
|
|
153
|
+
*/
|
|
154
|
+
function decryptEmbedding(encryptedEmbedding, encryptionKey) {
|
|
155
|
+
const decryptedBase64 = (0, crypto_js_1.decrypt)(encryptedEmbedding, encryptionKey);
|
|
156
|
+
const buf = Buffer.from(decryptedBase64, 'base64');
|
|
157
|
+
const floats = [];
|
|
158
|
+
for (let i = 0; i < buf.length; i += 4) {
|
|
159
|
+
floats.push(buf.readFloatLE(i));
|
|
160
|
+
}
|
|
161
|
+
return floats;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Handle remember in subgraph mode: encrypt, generate indices, submit on-chain.
|
|
165
|
+
*/
|
|
166
|
+
async function handleRememberSubgraph(state, args) {
|
|
167
|
+
const input = args;
|
|
168
|
+
// Support both single fact and batch mode (single only for subgraph for now)
|
|
169
|
+
const factText = input?.fact || '';
|
|
170
|
+
const factsArray = input?.facts;
|
|
171
|
+
const textsToStore = [];
|
|
172
|
+
if (factsArray && Array.isArray(factsArray) && factsArray.length > 0) {
|
|
173
|
+
for (const f of factsArray) {
|
|
174
|
+
if (f.text && typeof f.text === 'string' && f.text.trim().length > 0) {
|
|
175
|
+
textsToStore.push({ text: f.text.trim(), importance: f.importance ?? 5 });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
else if (factText && typeof factText === 'string' && factText.trim().length > 0) {
|
|
180
|
+
textsToStore.push({
|
|
181
|
+
text: factText.trim(),
|
|
182
|
+
importance: input?.importance ?? 5,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
if (textsToStore.length === 0) {
|
|
186
|
+
return {
|
|
187
|
+
content: [{
|
|
188
|
+
type: 'text',
|
|
189
|
+
text: JSON.stringify({
|
|
190
|
+
success: false,
|
|
191
|
+
error: 'Invalid input: provide either a "fact" string or a "facts" array',
|
|
192
|
+
}),
|
|
193
|
+
}],
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
const results = [];
|
|
197
|
+
for (const item of textsToStore) {
|
|
198
|
+
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)
|
|
202
|
+
const wordIndices = (0, crypto_js_1.generateBlindIndices)(item.text);
|
|
203
|
+
// 3. Generate embedding and LSH indices
|
|
204
|
+
const embedding = await (0, embedding_js_1.generateEmbedding)(item.text);
|
|
205
|
+
const lshIndices = state.lshHasher.hash(embedding);
|
|
206
|
+
// 4. Combine word + LSH indices
|
|
207
|
+
const allIndices = [...wordIndices, ...lshIndices];
|
|
208
|
+
// 5. Generate content fingerprint for dedup
|
|
209
|
+
const contentFp = (0, crypto_js_1.generateContentFingerprint)(item.text, state.dedupKey);
|
|
210
|
+
// 6. Encrypt the embedding for on-chain storage
|
|
211
|
+
const encryptedEmbedding = encryptEmbedding(embedding, state.encryptionKey);
|
|
212
|
+
// 7. Build fact payload
|
|
213
|
+
const factId = node_crypto_1.default.randomUUID();
|
|
214
|
+
const factPayload = {
|
|
215
|
+
id: factId,
|
|
216
|
+
timestamp: new Date().toISOString(),
|
|
217
|
+
owner: state.smartAccountAddress,
|
|
218
|
+
encryptedBlob: Buffer.from(encryptedBlob, 'base64').toString('hex'),
|
|
219
|
+
blindIndices: allIndices,
|
|
220
|
+
decayScore: item.importance / 10,
|
|
221
|
+
source: 'mcp_remember',
|
|
222
|
+
contentFp,
|
|
223
|
+
agentId: 'mcp-server',
|
|
224
|
+
encryptedEmbedding,
|
|
225
|
+
};
|
|
226
|
+
// 8. Encode as protobuf and submit on-chain
|
|
227
|
+
const protobuf = (0, store_js_1.encodeFactProtobuf)(factPayload);
|
|
228
|
+
const config = (0, store_js_1.getSubgraphConfig)({
|
|
229
|
+
relayUrl: state.serverUrl,
|
|
230
|
+
mnemonic: state.mnemonic,
|
|
231
|
+
});
|
|
232
|
+
const { txHash, success } = await (0, store_js_1.submitFactOnChain)(protobuf, config);
|
|
233
|
+
results.push({ success, fact_id: factId, tx_hash: txHash });
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
237
|
+
results.push({ success: false, fact_id: '', tx_hash: undefined });
|
|
238
|
+
console.error(`Failed to store fact on-chain: ${message}`);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const created = results.filter(r => r.success).length;
|
|
242
|
+
return {
|
|
243
|
+
content: [{
|
|
244
|
+
type: 'text',
|
|
245
|
+
text: JSON.stringify({
|
|
246
|
+
success: created > 0,
|
|
247
|
+
results,
|
|
248
|
+
total: textsToStore.length,
|
|
249
|
+
created,
|
|
250
|
+
skipped: textsToStore.length - created,
|
|
251
|
+
mode: 'subgraph',
|
|
252
|
+
}),
|
|
253
|
+
}],
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Handle recall in subgraph mode: search subgraph, decrypt, rerank.
|
|
258
|
+
*/
|
|
259
|
+
async function handleRecallSubgraph(state, args) {
|
|
260
|
+
const input = args;
|
|
261
|
+
const query = input?.query || '';
|
|
262
|
+
const startTime = Date.now();
|
|
263
|
+
if (!query || typeof query !== 'string' || query.trim().length === 0) {
|
|
264
|
+
return {
|
|
265
|
+
content: [{
|
|
266
|
+
type: 'text',
|
|
267
|
+
text: JSON.stringify({
|
|
268
|
+
memories: [],
|
|
269
|
+
latency_ms: 0,
|
|
270
|
+
error: 'Invalid input: query is required',
|
|
271
|
+
}),
|
|
272
|
+
}],
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
let k = input?.k ?? 8;
|
|
276
|
+
if (k < 1)
|
|
277
|
+
k = 8;
|
|
278
|
+
if (k > 50)
|
|
279
|
+
k = 50;
|
|
280
|
+
try {
|
|
281
|
+
// 1. Generate blind indices for the query (word + LSH trapdoors)
|
|
282
|
+
const wordTrapdoors = (0, crypto_js_1.generateBlindIndices)(query.trim());
|
|
283
|
+
// 2. Generate query embedding for LSH trapdoors and cosine reranking
|
|
284
|
+
const queryEmbedding = await (0, embedding_js_1.generateEmbedding)(query.trim(), { isQuery: true });
|
|
285
|
+
const lshTrapdoors = state.lshHasher.hash(queryEmbedding);
|
|
286
|
+
// 3. Combine trapdoors
|
|
287
|
+
const allTrapdoors = [...wordTrapdoors, ...lshTrapdoors];
|
|
288
|
+
// 4. Search the subgraph
|
|
289
|
+
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);
|
|
291
|
+
if (candidates.length === 0) {
|
|
292
|
+
return {
|
|
293
|
+
content: [{
|
|
294
|
+
type: 'text',
|
|
295
|
+
text: JSON.stringify({
|
|
296
|
+
memories: [],
|
|
297
|
+
latency_ms: Date.now() - startTime,
|
|
298
|
+
mode: 'subgraph',
|
|
299
|
+
}),
|
|
300
|
+
}],
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
// 5. Decrypt candidates
|
|
304
|
+
const decryptedCandidates = [];
|
|
305
|
+
for (const c of candidates) {
|
|
306
|
+
try {
|
|
307
|
+
// Decrypt the fact text (encryptedBlob is hex on subgraph, base64 internally)
|
|
308
|
+
const blobBase64 = Buffer.from(c.encryptedBlob, 'hex').toString('base64');
|
|
309
|
+
const text = (0, crypto_js_1.decrypt)(blobBase64, state.encryptionKey);
|
|
310
|
+
// Decrypt embedding if available
|
|
311
|
+
let embedding;
|
|
312
|
+
if (c.encryptedEmbedding) {
|
|
313
|
+
try {
|
|
314
|
+
embedding = decryptEmbedding(c.encryptedEmbedding, state.encryptionKey);
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
// Skip embedding if decryption fails
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
decryptedCandidates.push({
|
|
321
|
+
id: c.id,
|
|
322
|
+
text,
|
|
323
|
+
embedding,
|
|
324
|
+
importance: parseFloat(c.decayScore) || 0.5,
|
|
325
|
+
createdAt: parseInt(c.timestamp) || undefined,
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
// Skip candidates that fail to decrypt
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
// 6. Detect query intent for dynamic weight selection
|
|
333
|
+
const intent = (0, reranker_js_1.detectQueryIntent)(query.trim());
|
|
334
|
+
const weights = reranker_js_1.INTENT_WEIGHTS[intent];
|
|
335
|
+
// 7. Rerank with BM25 + cosine + importance + recency via weighted RRF
|
|
336
|
+
const reranked = (0, reranker_js_1.rerank)(query.trim(), queryEmbedding, decryptedCandidates, k, weights);
|
|
337
|
+
// 8. Format results
|
|
338
|
+
const memories = reranked.map(r => ({
|
|
339
|
+
fact_id: r.id,
|
|
340
|
+
fact_text: r.text,
|
|
341
|
+
score: r.rrfScore,
|
|
342
|
+
cosine_similarity: r.cosineSimilarity ?? 0,
|
|
343
|
+
importance: Math.round((r.importance ?? 0.5) * 10),
|
|
344
|
+
age_days: r.createdAt
|
|
345
|
+
? Math.floor((Date.now() / 1000 - r.createdAt) / 86400)
|
|
346
|
+
: 0,
|
|
347
|
+
}));
|
|
348
|
+
return {
|
|
349
|
+
content: [{
|
|
350
|
+
type: 'text',
|
|
351
|
+
text: JSON.stringify({
|
|
352
|
+
memories,
|
|
353
|
+
latency_ms: Date.now() - startTime,
|
|
354
|
+
candidates_searched: candidates.length,
|
|
355
|
+
mode: 'subgraph',
|
|
356
|
+
query_intent: intent,
|
|
357
|
+
}),
|
|
358
|
+
}],
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
catch (error) {
|
|
362
|
+
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
363
|
+
return {
|
|
364
|
+
content: [{
|
|
365
|
+
type: 'text',
|
|
366
|
+
text: JSON.stringify({
|
|
367
|
+
memories: [],
|
|
368
|
+
latency_ms: Date.now() - startTime,
|
|
369
|
+
error: `Failed to recall memories: ${message}`,
|
|
370
|
+
mode: 'subgraph',
|
|
371
|
+
}),
|
|
372
|
+
}],
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Handle forget in subgraph mode: submit a tombstone fact with isActive=false.
|
|
378
|
+
*
|
|
379
|
+
* On-chain facts are immutable, so we submit a new record that marks the
|
|
380
|
+
* original fact as inactive. The subgraph mapping updates isActive accordingly.
|
|
381
|
+
*/
|
|
382
|
+
async function handleForgetSubgraph(state, args) {
|
|
383
|
+
const input = args;
|
|
384
|
+
const factId = input?.fact_id;
|
|
385
|
+
if (!factId || typeof factId !== 'string') {
|
|
386
|
+
return {
|
|
387
|
+
content: [{
|
|
388
|
+
type: 'text',
|
|
389
|
+
text: JSON.stringify({
|
|
390
|
+
deleted_count: 0,
|
|
391
|
+
fact_ids: [],
|
|
392
|
+
error: 'fact_id is required for subgraph forget (query-based forget not supported in subgraph mode)',
|
|
393
|
+
}),
|
|
394
|
+
}],
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
try {
|
|
398
|
+
// Build a tombstone payload: same fact ID with isActive=false
|
|
399
|
+
// The protobuf encoder always sets isActive=true, so we build a minimal
|
|
400
|
+
// tombstone payload manually. For now, we re-encode the fact with
|
|
401
|
+
// a special "tombstone" marker that the subgraph mapping recognizes.
|
|
402
|
+
const tombstonePayload = {
|
|
403
|
+
id: factId,
|
|
404
|
+
timestamp: new Date().toISOString(),
|
|
405
|
+
owner: state.smartAccountAddress,
|
|
406
|
+
encryptedBlob: Buffer.from('tombstone').toString('hex'),
|
|
407
|
+
blindIndices: [],
|
|
408
|
+
decayScore: 0,
|
|
409
|
+
source: 'mcp_forget',
|
|
410
|
+
contentFp: '',
|
|
411
|
+
agentId: 'mcp-server',
|
|
412
|
+
};
|
|
413
|
+
const protobuf = (0, store_js_1.encodeFactProtobuf)(tombstonePayload);
|
|
414
|
+
const config = (0, store_js_1.getSubgraphConfig)({
|
|
415
|
+
relayUrl: state.serverUrl,
|
|
416
|
+
mnemonic: state.mnemonic,
|
|
417
|
+
});
|
|
418
|
+
const { txHash, success } = await (0, store_js_1.submitFactOnChain)(protobuf, config);
|
|
419
|
+
return {
|
|
420
|
+
content: [{
|
|
421
|
+
type: 'text',
|
|
422
|
+
text: JSON.stringify({
|
|
423
|
+
deleted_count: success ? 1 : 0,
|
|
424
|
+
fact_ids: success ? [factId] : [],
|
|
425
|
+
tx_hash: txHash,
|
|
426
|
+
mode: 'subgraph',
|
|
427
|
+
}),
|
|
428
|
+
}],
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
catch (error) {
|
|
432
|
+
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
433
|
+
return {
|
|
434
|
+
content: [{
|
|
435
|
+
type: 'text',
|
|
436
|
+
text: JSON.stringify({
|
|
437
|
+
deleted_count: 0,
|
|
438
|
+
fact_ids: [],
|
|
439
|
+
error: `Failed to forget memory: ${message}`,
|
|
440
|
+
mode: 'subgraph',
|
|
441
|
+
}),
|
|
442
|
+
}],
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
// ── Quota error helper ──────────────────────────────────────────────────────
|
|
447
|
+
/**
|
|
448
|
+
* Check if an error is a quota exceeded error (HTTP 403 with error_code: QUOTA_EXCEEDED).
|
|
449
|
+
*/
|
|
450
|
+
function isQuotaExceededError(error) {
|
|
451
|
+
if (error instanceof Error) {
|
|
452
|
+
const msg = error.message.toLowerCase();
|
|
453
|
+
return msg.includes('quota_exceeded') || msg.includes('quota exceeded');
|
|
454
|
+
}
|
|
455
|
+
return false;
|
|
456
|
+
}
|
|
457
|
+
function quotaExceededResponse() {
|
|
458
|
+
return {
|
|
459
|
+
content: [{
|
|
460
|
+
type: 'text',
|
|
461
|
+
text: JSON.stringify({
|
|
462
|
+
error: 'quota_exceeded',
|
|
463
|
+
message: 'Free tier limit reached. Upgrade to Pro for unlimited memories.',
|
|
464
|
+
upgrade_url: 'Use totalreclaw_upgrade tool to get a checkout link',
|
|
465
|
+
}),
|
|
466
|
+
}],
|
|
467
|
+
isError: true,
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
// ── Layer 1: Server with instructions ────────────────────────────────────────
|
|
471
|
+
const server = new index_js_1.Server({ name: 'totalreclaw', version: '1.0.0' }, {
|
|
472
|
+
capabilities: {
|
|
473
|
+
tools: {},
|
|
474
|
+
prompts: {},
|
|
475
|
+
resources: { subscribe: true, listChanged: true },
|
|
476
|
+
},
|
|
477
|
+
instructions: prompts_js_1.SERVER_INSTRUCTIONS,
|
|
478
|
+
});
|
|
479
|
+
// ── Wire up cache invalidation ───────────────────────────────────────────────
|
|
480
|
+
// When facts are stored, invalidate the memory context resource cache
|
|
481
|
+
(0, remember_js_1.setOnRememberCallback)(() => {
|
|
482
|
+
(0, index_js_3.invalidateMemoryContextCache)();
|
|
483
|
+
// Notify subscribed clients that the resource has been updated
|
|
484
|
+
server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch(() => { });
|
|
485
|
+
});
|
|
486
|
+
// ── Layer 2 + 3: Tool handlers ───────────────────────────────────────────────
|
|
487
|
+
server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
|
|
488
|
+
tools: [
|
|
489
|
+
index_js_2.rememberToolDefinition,
|
|
490
|
+
index_js_2.recallToolDefinition,
|
|
491
|
+
index_js_2.forgetToolDefinition,
|
|
492
|
+
index_js_2.exportToolDefinition,
|
|
493
|
+
index_js_2.importToolDefinition,
|
|
494
|
+
index_js_2.statusToolDefinition,
|
|
495
|
+
index_js_2.upgradeToolDefinition,
|
|
496
|
+
],
|
|
497
|
+
}));
|
|
498
|
+
server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
|
|
499
|
+
const { name, arguments: args } = request.params;
|
|
500
|
+
const mode = subgraphState ? 'subgraph' : 'http';
|
|
501
|
+
try {
|
|
502
|
+
// ── Billing tools (mode-independent, always use HTTP relay) ────────────
|
|
503
|
+
if (name === 'totalreclaw_status') {
|
|
504
|
+
const authKey = subgraphState
|
|
505
|
+
? (0, crypto_js_1.computeAuthKeyHash)(subgraphState.authKey)
|
|
506
|
+
: '';
|
|
507
|
+
return await (0, index_js_2.handleStatus)(SERVER_URL, authKey, args);
|
|
508
|
+
}
|
|
509
|
+
if (name === 'totalreclaw_upgrade') {
|
|
510
|
+
const authKey = subgraphState
|
|
511
|
+
? (0, crypto_js_1.computeAuthKeyHash)(subgraphState.authKey)
|
|
512
|
+
: '';
|
|
513
|
+
return await (0, index_js_2.handleUpgrade)(SERVER_URL, authKey, args);
|
|
514
|
+
}
|
|
515
|
+
// ── Subgraph mode ─────────────────────────────────────────────────────
|
|
516
|
+
if (subgraphState) {
|
|
517
|
+
switch (name) {
|
|
518
|
+
case 'totalreclaw_remember': {
|
|
519
|
+
try {
|
|
520
|
+
const result = await handleRememberSubgraph(subgraphState, args);
|
|
521
|
+
// Invalidate cache after successful store
|
|
522
|
+
(0, index_js_3.invalidateMemoryContextCache)();
|
|
523
|
+
server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch(() => { });
|
|
524
|
+
return result;
|
|
525
|
+
}
|
|
526
|
+
catch (error) {
|
|
527
|
+
if (isQuotaExceededError(error)) {
|
|
528
|
+
return quotaExceededResponse();
|
|
529
|
+
}
|
|
530
|
+
throw error;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
case 'totalreclaw_recall':
|
|
534
|
+
return await handleRecallSubgraph(subgraphState, args);
|
|
535
|
+
case 'totalreclaw_forget': {
|
|
536
|
+
const result = await handleForgetSubgraph(subgraphState, args);
|
|
537
|
+
(0, index_js_3.invalidateMemoryContextCache)();
|
|
538
|
+
server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch(() => { });
|
|
539
|
+
return result;
|
|
540
|
+
}
|
|
541
|
+
case 'totalreclaw_export':
|
|
542
|
+
// Export in subgraph mode not yet implemented -- fall through to error
|
|
543
|
+
return {
|
|
544
|
+
content: [{
|
|
545
|
+
type: 'text',
|
|
546
|
+
text: JSON.stringify({
|
|
547
|
+
error: 'Export is not yet supported in subgraph mode. Use HTTP mode for export.',
|
|
548
|
+
}),
|
|
549
|
+
}],
|
|
550
|
+
isError: true,
|
|
551
|
+
};
|
|
552
|
+
case 'totalreclaw_import':
|
|
553
|
+
return {
|
|
554
|
+
content: [{
|
|
555
|
+
type: 'text',
|
|
556
|
+
text: JSON.stringify({
|
|
557
|
+
error: 'Import is not yet supported in subgraph mode. Use HTTP mode for import.',
|
|
558
|
+
}),
|
|
559
|
+
}],
|
|
560
|
+
isError: true,
|
|
561
|
+
};
|
|
562
|
+
default:
|
|
563
|
+
return {
|
|
564
|
+
content: [{
|
|
565
|
+
type: 'text',
|
|
566
|
+
text: JSON.stringify({ error: `Unknown tool: ${name}` }),
|
|
567
|
+
}],
|
|
568
|
+
isError: true,
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
// ── HTTP mode (existing behavior) ─────────────────────────────────────
|
|
573
|
+
const client = await getClient();
|
|
574
|
+
switch (name) {
|
|
575
|
+
case 'totalreclaw_remember': {
|
|
576
|
+
try {
|
|
577
|
+
const result = await (0, index_js_2.handleRemember)(client, args, DEFAULT_NAMESPACE);
|
|
578
|
+
return result;
|
|
579
|
+
}
|
|
580
|
+
catch (error) {
|
|
581
|
+
if (isQuotaExceededError(error)) {
|
|
582
|
+
return quotaExceededResponse();
|
|
583
|
+
}
|
|
584
|
+
throw error;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
case 'totalreclaw_recall':
|
|
588
|
+
return await (0, index_js_2.handleRecall)(client, args, DEFAULT_NAMESPACE);
|
|
589
|
+
case 'totalreclaw_forget': {
|
|
590
|
+
const result = await (0, index_js_2.handleForget)(client, args, DEFAULT_NAMESPACE);
|
|
591
|
+
// Invalidate cache on forget too
|
|
592
|
+
(0, index_js_3.invalidateMemoryContextCache)();
|
|
593
|
+
server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch(() => { });
|
|
594
|
+
return result;
|
|
595
|
+
}
|
|
596
|
+
case 'totalreclaw_export':
|
|
597
|
+
return await (0, index_js_2.handleExport)(client, args, DEFAULT_NAMESPACE);
|
|
598
|
+
case 'totalreclaw_import':
|
|
599
|
+
return await (0, index_js_2.handleImport)(client, args, DEFAULT_NAMESPACE);
|
|
600
|
+
default:
|
|
601
|
+
return {
|
|
602
|
+
content: [{
|
|
603
|
+
type: 'text',
|
|
604
|
+
text: JSON.stringify({ error: `Unknown tool: ${name}` }),
|
|
605
|
+
}],
|
|
606
|
+
isError: true,
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
catch (error) {
|
|
611
|
+
// Final catch-all: check for quota error at the top level too
|
|
612
|
+
if (isQuotaExceededError(error)) {
|
|
613
|
+
return quotaExceededResponse();
|
|
614
|
+
}
|
|
615
|
+
return {
|
|
616
|
+
content: [{
|
|
617
|
+
type: 'text',
|
|
618
|
+
text: JSON.stringify({
|
|
619
|
+
error: error instanceof Error ? error.message : 'Unknown error',
|
|
620
|
+
}),
|
|
621
|
+
}],
|
|
622
|
+
isError: true,
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
});
|
|
626
|
+
// ── Layer 4: Resources ───────────────────────────────────────────────────────
|
|
627
|
+
server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => ({
|
|
628
|
+
resources: [index_js_3.memoryContextResource],
|
|
629
|
+
}));
|
|
630
|
+
server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request) => {
|
|
631
|
+
const { uri } = request.params;
|
|
632
|
+
if (uri === index_js_3.memoryContextResource.uri) {
|
|
633
|
+
// In subgraph mode, resource reading is not supported yet
|
|
634
|
+
if (subgraphState) {
|
|
635
|
+
return {
|
|
636
|
+
contents: [
|
|
637
|
+
{
|
|
638
|
+
uri: index_js_3.memoryContextResource.uri,
|
|
639
|
+
mimeType: 'text/markdown',
|
|
640
|
+
text: '*Memory context resource is not available in subgraph mode. Use totalreclaw_recall to search memories.*',
|
|
641
|
+
},
|
|
642
|
+
],
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
const client = await getClient();
|
|
646
|
+
const content = await (0, index_js_3.readMemoryContext)(client, DEFAULT_NAMESPACE);
|
|
647
|
+
return {
|
|
648
|
+
contents: [
|
|
649
|
+
{
|
|
650
|
+
uri: index_js_3.memoryContextResource.uri,
|
|
651
|
+
mimeType: 'text/markdown',
|
|
652
|
+
text: content,
|
|
653
|
+
},
|
|
654
|
+
],
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
throw new Error(`Unknown resource: ${uri}`);
|
|
658
|
+
});
|
|
659
|
+
// ── Layer 5: Prompts ─────────────────────────────────────────────────────────
|
|
660
|
+
server.setRequestHandler(types_js_1.ListPromptsRequestSchema, async () => ({
|
|
661
|
+
prompts: [
|
|
662
|
+
// Legacy instructions prompt (backward compat)
|
|
663
|
+
{
|
|
664
|
+
name: 'totalreclaw_instructions',
|
|
665
|
+
description: 'Instructions for using TotalReclaw tools',
|
|
666
|
+
},
|
|
667
|
+
// New auto-memory prompt fallbacks
|
|
668
|
+
...prompts_js_1.PROMPT_DEFINITIONS,
|
|
669
|
+
],
|
|
670
|
+
}));
|
|
671
|
+
server.setRequestHandler(types_js_1.GetPromptRequestSchema, async (request) => {
|
|
672
|
+
const { name, arguments: args } = request.params;
|
|
673
|
+
const messages = (0, prompts_js_1.getPromptMessages)(name, args);
|
|
674
|
+
return { messages };
|
|
675
|
+
});
|
|
676
|
+
// ── Main ─────────────────────────────────────────────────────────────────────
|
|
677
|
+
async function main() {
|
|
678
|
+
// CLI subcommand routing
|
|
679
|
+
if (process.argv[2] === 'setup') {
|
|
680
|
+
const { runSetup } = await import('./cli/setup.js');
|
|
681
|
+
await runSetup();
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
// Detect and initialize server mode
|
|
685
|
+
const mode = detectServerMode();
|
|
686
|
+
if (mode === 'subgraph') {
|
|
687
|
+
subgraphState = initSubgraphState();
|
|
688
|
+
console.error(`TotalReclaw MCP server started (subgraph mode, owner: ${subgraphState.smartAccountAddress})`);
|
|
689
|
+
}
|
|
690
|
+
else {
|
|
691
|
+
console.error('TotalReclaw MCP server started (HTTP mode)');
|
|
692
|
+
}
|
|
693
|
+
const transport = new stdio_js_1.StdioServerTransport();
|
|
694
|
+
await server.connect(transport);
|
|
695
|
+
}
|
|
696
|
+
main().catch((error) => {
|
|
697
|
+
console.error('Server error:', error);
|
|
698
|
+
process.exit(1);
|
|
699
|
+
});
|
|
700
|
+
//# sourceMappingURL=index.js.map
|