@kolivri/memoreal-mcp 1.0.2 → 1.1.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.
@@ -1,429 +0,0 @@
1
- import { describe, it, before, after } from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import fs from 'node:fs';
4
- import http from 'node:http';
5
- import os from 'node:os';
6
- import path from 'node:path';
7
- import { fileURLToPath } from 'node:url';
8
- import {
9
- normalizeInput,
10
- readApifyInput,
11
- executeMemorealActorAction,
12
- executeMemoriaActorAction,
13
- outputApifyResult,
14
- main,
15
- VALID_ACTIONS,
16
- } from '../src/apify-main.mjs';
17
-
18
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
19
- const PKG_ROOT = path.resolve(__dirname, '..');
20
-
21
- describe('Apify Actor Specification and Runner Suite', () => {
22
- let mockServer;
23
- let mockServerUrl;
24
- let recordedRequests = [];
25
-
26
- before(async () => {
27
- mockServer = http.createServer((req, res) => {
28
- let body = '';
29
- req.on('data', (chunk) => {
30
- body += chunk;
31
- });
32
- req.on('end', () => {
33
- let parsed = {};
34
- try {
35
- parsed = JSON.parse(body);
36
- } catch {
37
- // ignore
38
- }
39
- recordedRequests.push({
40
- method: req.method,
41
- headers: req.headers,
42
- body: parsed,
43
- });
44
-
45
- res.writeHead(200, { 'content-type': 'application/json' });
46
- res.end(
47
- JSON.stringify({
48
- jsonrpc: '2.0',
49
- id: parsed.id || 'test_id',
50
- result: {
51
- content: [
52
- {
53
- type: 'text',
54
- text: JSON.stringify({
55
- dispatched_tool: parsed.params?.name,
56
- dispatched_args: parsed.params?.arguments,
57
- received_auth: req.headers.authorization,
58
- }),
59
- },
60
- ],
61
- },
62
- })
63
- );
64
- });
65
- });
66
-
67
- await new Promise((resolve) => mockServer.listen(0, '127.0.0.1', resolve));
68
- const addr = mockServer.address();
69
- mockServerUrl = `http://127.0.0.1:${addr.port}`;
70
- });
71
-
72
- after(async () => {
73
- if (mockServer) {
74
- await new Promise((resolve) => mockServer.close(resolve));
75
- }
76
- });
77
-
78
- it('validates .actor/actor.json specification metadata', () => {
79
- const actorJsonPath = path.join(PKG_ROOT, '.actor/actor.json');
80
- assert.ok(fs.existsSync(actorJsonPath), '.actor/actor.json must exist');
81
- const actorConfig = JSON.parse(fs.readFileSync(actorJsonPath, 'utf8'));
82
-
83
- assert.equal(actorConfig.actorSpecification, 1);
84
- assert.equal(actorConfig.name, 'memoreal-mcp');
85
- assert.equal(actorConfig.input, './input_schema.json');
86
- assert.equal(actorConfig.dockerfile, './Dockerfile');
87
- assert.equal(actorConfig.readme, '../README.md');
88
- assert.equal(actorConfig.environmentVariables?.MEMOREAL_API_URL, 'https://memoreal.kolivri.com');
89
- assert.equal(actorConfig.environmentVariables?.MEMORIA_API_URL, 'https://memoria.kolivri.com');
90
- });
91
-
92
- it('validates .actor/input_schema.json schema properties and action enum', () => {
93
- const schemaPath = path.join(PKG_ROOT, '.actor/input_schema.json');
94
- assert.ok(fs.existsSync(schemaPath), '.actor/input_schema.json must exist');
95
- const schema = JSON.parse(fs.readFileSync(schemaPath, 'utf8'));
96
-
97
- assert.equal(schema.type, 'object');
98
- assert.ok(schema.properties.apiKey, 'apiKey field declared');
99
- assert.equal(schema.properties.apiKey.isSecret, true, 'apiKey marked secret');
100
- assert.ok(schema.properties.namespace, 'namespace field declared');
101
- assert.ok(schema.properties.action, 'action field declared');
102
- assert.deepEqual(schema.properties.action.enum, VALID_ACTIONS);
103
- assert.ok(schema.properties.query, 'query field declared');
104
- assert.ok(schema.properties.content, 'content field declared');
105
- assert.ok(schema.properties.type, 'type field declared');
106
- assert.deepEqual(schema.properties.type.enum, ['episodic', 'semantic', 'buffer', 'core']);
107
- assert.ok(schema.properties.salience, 'salience field declared');
108
- assert.ok(schema.properties.tokenBudget, 'tokenBudget field declared');
109
- });
110
-
111
- it('validates .actor/Dockerfile uses Node 20 actor base and invokes apify-main.mjs', () => {
112
- const dockerfilePath = path.join(PKG_ROOT, '.actor/Dockerfile');
113
- assert.ok(fs.existsSync(dockerfilePath), '.actor/Dockerfile must exist');
114
- const dockerfile = fs.readFileSync(dockerfilePath, 'utf8');
115
-
116
- assert.match(dockerfile, /FROM apify\/actor-node:20/);
117
- assert.match(dockerfile, /RUN npm ci --omit=dev/);
118
- assert.match(dockerfile, /CMD \["node", "\.\/src\/apify-main\.mjs"\]/);
119
- });
120
-
121
- it('normalizes raw input with secure defaults and clamps salience', () => {
122
- const defaults = normalizeInput({});
123
- assert.equal(defaults.namespace, 'default');
124
- assert.equal(defaults.action, 'context');
125
- assert.equal(defaults.type, 'episodic');
126
- assert.equal(defaults.salience, 0.5);
127
- assert.equal(defaults.tokenBudget, 4096);
128
-
129
- const custom = normalizeInput({
130
- apiKey: ' mem_test_key ',
131
- namespace: ' custom-workspace ',
132
- action: 'recall',
133
- query: ' how does memory work? ',
134
- salience: 1.5,
135
- tokenBudget: '1024',
136
- type: 'invalid_type',
137
- });
138
- assert.equal(custom.apiKey, 'mem_test_key');
139
- assert.equal(custom.namespace, 'custom-workspace');
140
- assert.equal(custom.action, 'recall');
141
- assert.equal(custom.query, 'how does memory work?');
142
- assert.equal(custom.salience, 1.0, 'clamped to 1.0');
143
- assert.equal(custom.tokenBudget, 1024);
144
- assert.equal(custom.type, 'episodic', 'fallback to episodic on invalid type');
145
-
146
- assert.equal(normalizeInput({ apiKey: 'mem_dev_your_key_here' }).apiKey, '');
147
- assert.equal(normalizeInput({ apiKey: 'mem_dev_...' }).apiKey, '');
148
- assert.equal(normalizeInput({ apiKey: 'YOUR_API_KEY' }).apiKey, '');
149
- assert.equal(normalizeInput({ apiKey: '<MEMOREAL_API_KEY>' }).apiKey, '');
150
- });
151
-
152
- it('resolves input from explicit object, env JSON, and fallback files', async () => {
153
- const explicit = await readApifyInput({ action: 'health', namespace: 'explicit-ns' });
154
- assert.equal(explicit.namespace, 'explicit-ns');
155
-
156
- const origEnv = process.env.APIFY_INPUT_JSON;
157
- try {
158
- process.env.APIFY_INPUT_JSON = JSON.stringify({ action: 'recall', query: 'env-query' });
159
- const fromEnv = await readApifyInput(null);
160
- assert.equal(fromEnv.action, 'recall');
161
- assert.equal(fromEnv.query, 'env-query');
162
- } finally {
163
- if (origEnv !== undefined) {
164
- process.env.APIFY_INPUT_JSON = origEnv;
165
- } else {
166
- delete process.env.APIFY_INPUT_JSON;
167
- }
168
- }
169
- });
170
-
171
- it('throws descriptive error when API key is missing for tool actions or using placeholders without leaking ambient config.env', async () => {
172
- const origMemoreal = process.env.MEMOREAL_API_KEY;
173
- const origMemoria = process.env.MEMORIA_API_KEY;
174
- delete process.env.MEMOREAL_API_KEY;
175
- delete process.env.MEMORIA_API_KEY;
176
- try {
177
- await assert.rejects(
178
- () =>
179
- executeMemorealActorAction({
180
- action: 'context',
181
- apiKey: '',
182
- apiUrl: mockServerUrl,
183
- }),
184
- /Missing Memoreal API key: set MEMOREAL_API_KEY.*Polite Onboarding Action/s
185
- );
186
-
187
- await assert.rejects(
188
- () =>
189
- executeMemorealActorAction({
190
- action: 'health',
191
- apiKey: '',
192
- apiUrl: mockServerUrl,
193
- }),
194
- /Missing Memoreal API key: set MEMOREAL_API_KEY.*Polite Onboarding Action/s
195
- );
196
-
197
- await assert.rejects(
198
- () =>
199
- executeMemorealActorAction({
200
- action: 'context',
201
- apiKey: 'mem_dev_your_key_here',
202
- apiUrl: mockServerUrl,
203
- }),
204
- /Missing Memoreal API key: set MEMOREAL_API_KEY.*Polite Onboarding Action/s
205
- );
206
-
207
- await assert.rejects(
208
- () =>
209
- executeMemorealActorAction({
210
- action: 'health',
211
- apiKey: 'YOUR_API_KEY',
212
- apiUrl: mockServerUrl,
213
- }),
214
- /Missing Memoreal API key: set MEMOREAL_API_KEY.*Polite Onboarding Action/s
215
- );
216
-
217
- await assert.rejects(
218
- () =>
219
- executeMemorealActorAction({
220
- action: 'context',
221
- apiKey: '<MEMOREAL_API_KEY>',
222
- apiUrl: mockServerUrl,
223
- }),
224
- /Missing Memoreal API key: set MEMOREAL_API_KEY.*Polite Onboarding Action/s
225
- );
226
- } finally {
227
- if (origMemoreal !== undefined) {
228
- process.env.MEMOREAL_API_KEY = origMemoreal;
229
- }
230
- if (origMemoria !== undefined) {
231
- process.env.MEMORIA_API_KEY = origMemoria;
232
- }
233
- }
234
- });
235
-
236
- it('rejects unsupported actions with helpful allowed actions list', async () => {
237
- await assert.rejects(
238
- () =>
239
- executeMemorealActorAction({
240
- action: 'invalid_action_xyz',
241
- apiKey: 'test-key',
242
- }),
243
- /Unsupported action: "invalid_action_xyz"\. Valid actions are: recall, context, encode, search_code, health, standby_mcp\./
244
- );
245
- });
246
-
247
- it('dispatches action: "context" to build_context tool', async () => {
248
- recordedRequests = [];
249
- const res = await executeMemorealActorAction({
250
- action: 'context',
251
- apiKey: 'mem_test_token_ctx',
252
- apiUrl: mockServerUrl,
253
- namespace: 'ctx-namespace',
254
- query: 'active architectural decisions',
255
- tokenBudget: 2048,
256
- });
257
-
258
- assert.equal(res.ok, true);
259
- assert.equal(res.action, 'context');
260
- assert.equal(res.namespace, 'ctx-namespace');
261
- assert.equal(res.result.dispatched_tool, 'build_context');
262
- assert.equal(res.result.dispatched_args.query, 'active architectural decisions');
263
- assert.equal(res.result.dispatched_args.token_budget, 2048);
264
- assert.equal(res.result.dispatched_args.namespace, 'ctx-namespace');
265
- assert.equal(res.result.received_auth, 'Bearer mem_test_token_ctx');
266
- });
267
-
268
- it('dispatches action: "recall" to recall_memories tool', async () => {
269
- recordedRequests = [];
270
- const res = await executeMemorealActorAction({
271
- action: 'recall',
272
- apiKey: 'mem_test_token_recall',
273
- apiUrl: mockServerUrl,
274
- namespace: 'recall-namespace',
275
- query: 'find invariant rules',
276
- tokenBudget: 1024,
277
- });
278
-
279
- assert.equal(res.ok, true);
280
- assert.equal(res.action, 'recall');
281
- assert.equal(res.result.dispatched_tool, 'recall_memories');
282
- assert.equal(res.result.dispatched_args.query, 'find invariant rules');
283
- assert.equal(res.result.dispatched_args.token_budget, 1024);
284
- });
285
-
286
- it('dispatches action: "encode" to encode_memory tool and enforces content', async () => {
287
- await assert.rejects(
288
- () =>
289
- executeMemorealActorAction({
290
- action: 'encode',
291
- apiKey: 'mem_test_key',
292
- apiUrl: mockServerUrl,
293
- content: '',
294
- }),
295
- /Action "encode" requires non-empty "content" parameter/
296
- );
297
-
298
- recordedRequests = [];
299
- const res = await executeMemorealActorAction({
300
- action: 'encode',
301
- apiKey: 'mem_test_token_encode',
302
- apiUrl: mockServerUrl,
303
- namespace: 'encode-ns',
304
- content: 'Always use integration tests before merging to main.',
305
- type: 'semantic',
306
- salience: 0.9,
307
- });
308
-
309
- assert.equal(res.ok, true);
310
- assert.equal(res.action, 'encode');
311
- assert.equal(res.result.dispatched_tool, 'encode_memory');
312
- assert.equal(res.result.dispatched_args.content, 'Always use integration tests before merging to main.');
313
- assert.equal(res.result.dispatched_args.type, 'semantic');
314
- assert.equal(res.result.dispatched_args.salience, 0.9);
315
- });
316
-
317
- it('dispatches action: "health" to health tool', async () => {
318
- recordedRequests = [];
319
- const res = await executeMemorealActorAction({
320
- action: 'health',
321
- apiKey: 'mem_test_token_health',
322
- apiUrl: mockServerUrl,
323
- });
324
-
325
- assert.equal(res.ok, true);
326
- assert.equal(res.action, 'health');
327
- assert.equal(res.result.dispatched_tool, 'health');
328
- });
329
-
330
- it('dispatches action: "search_code" to search_code tool', async () => {
331
- recordedRequests = [];
332
- const res = await executeMemorealActorAction({
333
- action: 'search_code',
334
- apiKey: 'mem_test_token_code',
335
- apiUrl: mockServerUrl,
336
- namespace: 'code-ns',
337
- query: 'createMemorealMcpService',
338
- });
339
-
340
- assert.equal(res.ok, true);
341
- assert.equal(res.action, 'search_code');
342
- assert.equal(res.result.dispatched_tool, 'search_code');
343
- assert.equal(res.result.dispatched_args.query, 'createMemorealMcpService');
344
- });
345
-
346
- it('supports action: "standby_mcp" and boots stdio server', async () => {
347
- const res = await executeMemorealActorAction({
348
- action: 'standby_mcp',
349
- apiKey: 'mem_test_token_standby',
350
- apiUrl: mockServerUrl,
351
- namespace: 'standby-ns',
352
- });
353
-
354
- assert.equal(res.ok, true);
355
- assert.equal(res.action, 'standby_mcp');
356
- assert.equal(res.status, 'standby_mcp_running');
357
- assert.ok(res.server && typeof res.server.close === 'function');
358
- res.server.close();
359
- });
360
-
361
- it('writes output to local storage directory when configured', async () => {
362
- const tempStorage = fs.mkdtempSync(path.join(os.tmpdir(), 'apify-storage-test-'));
363
- const origStorage = process.env.APIFY_LOCAL_STORAGE_DIR;
364
- process.env.APIFY_LOCAL_STORAGE_DIR = tempStorage;
365
-
366
- try {
367
- const outputData = { ok: true, testValue: 42 };
368
- await outputApifyResult(outputData);
369
-
370
- const writtenFile = path.join(tempStorage, 'key_value_stores', 'default', 'OUTPUT.json');
371
- assert.ok(fs.existsSync(writtenFile), 'OUTPUT.json was written to local storage');
372
- const loaded = JSON.parse(fs.readFileSync(writtenFile, 'utf8'));
373
- assert.deepEqual(loaded, outputData);
374
- } finally {
375
- if (origStorage !== undefined) {
376
- process.env.APIFY_LOCAL_STORAGE_DIR = origStorage;
377
- } else {
378
- delete process.env.APIFY_LOCAL_STORAGE_DIR;
379
- }
380
- fs.rmSync(tempStorage, { recursive: true, force: true });
381
- }
382
- });
383
-
384
- it('runs main() gracefully catching errors and returning error payload', async () => {
385
- const errorResult = await main({
386
- input: {
387
- action: 'invalid_xyz',
388
- },
389
- throwOnError: false,
390
- });
391
- assert.equal(errorResult.ok, false);
392
- assert.match(errorResult.error, /Unsupported action/);
393
- });
394
-
395
- it('supports MEMOREAL_API_KEY and legacy MEMORIA_API_KEY and executeMemoriaActorAction alias', async () => {
396
- recordedRequests = [];
397
- const origMemoreal = process.env.MEMOREAL_API_KEY;
398
- const origMemoria = process.env.MEMORIA_API_KEY;
399
- delete process.env.MEMOREAL_API_KEY;
400
- process.env.MEMORIA_API_KEY = 'legacy_env_key_apify';
401
- try {
402
- const resLegacy = await executeMemoriaActorAction({
403
- action: 'health',
404
- apiUrl: mockServerUrl,
405
- });
406
- assert.equal(resLegacy.ok, true);
407
- assert.equal(resLegacy.result.received_auth, 'Bearer legacy_env_key_apify');
408
-
409
- process.env.MEMOREAL_API_KEY = 'canonical_env_key_apify';
410
- const resCanonical = await executeMemorealActorAction({
411
- action: 'health',
412
- apiUrl: mockServerUrl,
413
- });
414
- assert.equal(resCanonical.ok, true);
415
- assert.equal(resCanonical.result.received_auth, 'Bearer canonical_env_key_apify');
416
- } finally {
417
- if (origMemoreal !== undefined) {
418
- process.env.MEMOREAL_API_KEY = origMemoreal;
419
- } else {
420
- delete process.env.MEMOREAL_API_KEY;
421
- }
422
- if (origMemoria !== undefined) {
423
- process.env.MEMORIA_API_KEY = origMemoria;
424
- } else {
425
- delete process.env.MEMORIA_API_KEY;
426
- }
427
- }
428
- });
429
- });