@mnemocyte/mcp 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +36 -2
- package/dist/cli.mjs +733 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/index.d.mts +75 -0
- package/dist/index.mjs +1 -0
- package/dist/server-Bwa4mQjX.mjs +424 -0
- package/dist/server-Bwa4mQjX.mjs.map +1 -0
- package/dist/server-only.cjs +2 -0
- package/package.json +67 -3
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,733 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { n as createMemoryMcpServer, r as toolNames, t as SERVER_INFO } from "./server-Bwa4mQjX.mjs";
|
|
3
|
+
import { createRequire, registerHooks } from "node:module";
|
|
4
|
+
import { readFileSync, statSync } from "node:fs";
|
|
5
|
+
import { isMnemocyteError } from "mnemocyte";
|
|
6
|
+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
7
|
+
import { Console } from "node:console";
|
|
8
|
+
import { dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
|
|
9
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
10
|
+
import { parseArgs } from "node:util";
|
|
11
|
+
// src/cli/console.ts
|
|
12
|
+
const STDOUT_METHODS = [
|
|
13
|
+
"log",
|
|
14
|
+
"info",
|
|
15
|
+
"debug",
|
|
16
|
+
"dir",
|
|
17
|
+
"dirxml",
|
|
18
|
+
"table",
|
|
19
|
+
"group",
|
|
20
|
+
"groupCollapsed",
|
|
21
|
+
"groupEnd",
|
|
22
|
+
"count",
|
|
23
|
+
"countReset",
|
|
24
|
+
"time",
|
|
25
|
+
"timeEnd",
|
|
26
|
+
"timeLog"
|
|
27
|
+
];
|
|
28
|
+
/**
|
|
29
|
+
* Send everything `console` would print to standard output to standard
|
|
30
|
+
* error instead. On stdio, standard output carries only MCP messages, so a
|
|
31
|
+
* `console.log` in the app's memory file or a module it imports would
|
|
32
|
+
* corrupt the stream. Writes to `process.stdout` itself are not caught.
|
|
33
|
+
*/
|
|
34
|
+
function redirectConsoleToStderr() {
|
|
35
|
+
const toStderr = new Console({
|
|
36
|
+
stdout: process.stderr,
|
|
37
|
+
stderr: process.stderr
|
|
38
|
+
});
|
|
39
|
+
for (const method of STDOUT_METHODS) Object.defineProperty(console, method, {
|
|
40
|
+
value: toStderr[method],
|
|
41
|
+
writable: true,
|
|
42
|
+
configurable: true,
|
|
43
|
+
enumerable: true
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
// ../loader/src/env-files.ts
|
|
47
|
+
/**
|
|
48
|
+
* The environment files read from the project, in order: Next.js's order
|
|
49
|
+
* for these two (ARCHITECTURE decision 78). The `.env.$(NODE_ENV)` files
|
|
50
|
+
* are left out, since the bins run outside a mode.
|
|
51
|
+
*/
|
|
52
|
+
const ENV_FILE_NAMES = [".env.local", ".env"];
|
|
53
|
+
function isFile$4(path) {
|
|
54
|
+
return statSync(path, { throwIfNoEntry: false })?.isFile() === true;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Load `.env.local`, then `.env`, from the project into `process.env`, each
|
|
58
|
+
* when it exists. `.env.local` is skipped when `NODE_ENV` is `test`, as in
|
|
59
|
+
* Next.js, so tests do not depend on one machine's overrides; only the real
|
|
60
|
+
* environment's `NODE_ENV` counts, since no file is read before the check.
|
|
61
|
+
* `process.loadEnvFile` keeps a variable that is already set, so the real
|
|
62
|
+
* environment wins over both files and `.env.local` over `.env`.
|
|
63
|
+
*
|
|
64
|
+
* @returns The names of the files that were read, in order.
|
|
65
|
+
*/
|
|
66
|
+
function loadEnvFiles(input) {
|
|
67
|
+
const skipLocal = process.env.NODE_ENV === "test";
|
|
68
|
+
const loaded = [];
|
|
69
|
+
for (const name of ENV_FILE_NAMES) {
|
|
70
|
+
if (skipLocal && name === ".env.local") continue;
|
|
71
|
+
const path = join(input.directory, name);
|
|
72
|
+
if (isFile$4(path)) {
|
|
73
|
+
process.loadEnvFile(path);
|
|
74
|
+
loaded.push(name);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return loaded;
|
|
78
|
+
}
|
|
79
|
+
// ../loader/src/memory-file.ts
|
|
80
|
+
/** Folders searched for a memory file, in order, relative to the project. */
|
|
81
|
+
const MEMORY_FILE_DIRECTORIES = [
|
|
82
|
+
"",
|
|
83
|
+
"lib",
|
|
84
|
+
"src",
|
|
85
|
+
"src/lib"
|
|
86
|
+
];
|
|
87
|
+
/** File names tried in each folder, in order. */
|
|
88
|
+
const MEMORY_FILE_NAMES = [
|
|
89
|
+
"memory.ts",
|
|
90
|
+
"memory.mts",
|
|
91
|
+
"memory.js",
|
|
92
|
+
"memory.mjs"
|
|
93
|
+
];
|
|
94
|
+
function isFile$3(path) {
|
|
95
|
+
return statSync(path, { throwIfNoEntry: false })?.isFile() === true;
|
|
96
|
+
}
|
|
97
|
+
/** The first memory file in the project, or null. */
|
|
98
|
+
function findMemoryFile(cwd) {
|
|
99
|
+
for (const directory of MEMORY_FILE_DIRECTORIES) for (const name of MEMORY_FILE_NAMES) {
|
|
100
|
+
const candidate = join(cwd, directory, name);
|
|
101
|
+
if (isFile$3(candidate)) return candidate;
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
// ../loader/src/tsconfig.ts
|
|
106
|
+
function isRecord$1(value) {
|
|
107
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
108
|
+
}
|
|
109
|
+
function isFile$2(path) {
|
|
110
|
+
return statSync(path, { throwIfNoEntry: false })?.isFile() === true;
|
|
111
|
+
}
|
|
112
|
+
/** Index just past the string literal that starts at `start`. */
|
|
113
|
+
function stringEnd(text, start) {
|
|
114
|
+
let index = start + 1;
|
|
115
|
+
while (index < text.length) if (text[index] === "\\") index += 2;
|
|
116
|
+
else if (text[index] === "\"") return index + 1;
|
|
117
|
+
else index += 1;
|
|
118
|
+
return text.length;
|
|
119
|
+
}
|
|
120
|
+
const BEFORE_CLOSING_BRACKET = /\s*[}\]]/y;
|
|
121
|
+
/**
|
|
122
|
+
* Parse JSON with comments and trailing commas, which `tsconfig.json`
|
|
123
|
+
* allows and `JSON.parse` rejects. String literals are copied untouched, so
|
|
124
|
+
* a `//` or a comma inside one survives.
|
|
125
|
+
*
|
|
126
|
+
* @throws {SyntaxError} When what is left is not JSON.
|
|
127
|
+
*/
|
|
128
|
+
function parseJsonc(text) {
|
|
129
|
+
let withoutComments = "";
|
|
130
|
+
for (let index = 0; index < text.length;) if (text[index] === "\"") {
|
|
131
|
+
const end = stringEnd(text, index);
|
|
132
|
+
withoutComments += text.slice(index, end);
|
|
133
|
+
index = end;
|
|
134
|
+
} else if (text.startsWith("//", index)) {
|
|
135
|
+
const newline = text.indexOf("\n", index);
|
|
136
|
+
index = newline === -1 ? text.length : newline;
|
|
137
|
+
} else if (text.startsWith("/*", index)) {
|
|
138
|
+
const close = text.indexOf("*/", index + 2);
|
|
139
|
+
index = close === -1 ? text.length : close + 2;
|
|
140
|
+
} else {
|
|
141
|
+
withoutComments += text[index];
|
|
142
|
+
index += 1;
|
|
143
|
+
}
|
|
144
|
+
let json = "";
|
|
145
|
+
for (let index = 0; index < withoutComments.length;) {
|
|
146
|
+
if (withoutComments[index] === "\"") {
|
|
147
|
+
const end = stringEnd(withoutComments, index);
|
|
148
|
+
json += withoutComments.slice(index, end);
|
|
149
|
+
index = end;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (withoutComments[index] === ",") {
|
|
153
|
+
BEFORE_CLOSING_BRACKET.lastIndex = index + 1;
|
|
154
|
+
if (BEFORE_CLOSING_BRACKET.test(withoutComments)) {
|
|
155
|
+
index += 1;
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
json += withoutComments[index];
|
|
160
|
+
index += 1;
|
|
161
|
+
}
|
|
162
|
+
return JSON.parse(json.replace(/^/, ""));
|
|
163
|
+
}
|
|
164
|
+
/** The file an `extends` entry names, or null when it cannot be found. */
|
|
165
|
+
function resolveExtends(entry, from) {
|
|
166
|
+
if (entry.startsWith("./") || entry.startsWith("../") || isAbsolute(entry)) {
|
|
167
|
+
const path = resolve(dirname(from), entry);
|
|
168
|
+
return [path, `${path}.json`].find(isFile$2) ?? null;
|
|
169
|
+
}
|
|
170
|
+
const require = createRequire(from);
|
|
171
|
+
for (const specifier of [
|
|
172
|
+
entry,
|
|
173
|
+
`${entry}.json`,
|
|
174
|
+
`${entry}/tsconfig.json`
|
|
175
|
+
]) try {
|
|
176
|
+
return require.resolve(specifier);
|
|
177
|
+
} catch {}
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
function toPatterns(paths) {
|
|
181
|
+
const patterns = [];
|
|
182
|
+
for (const [key, value] of Object.entries(paths)) {
|
|
183
|
+
if (!Array.isArray(value)) continue;
|
|
184
|
+
const targets = value.filter((target) => typeof target === "string");
|
|
185
|
+
const star = key.indexOf("*");
|
|
186
|
+
patterns.push(star === -1 ? {
|
|
187
|
+
prefix: key,
|
|
188
|
+
suffix: null,
|
|
189
|
+
targets
|
|
190
|
+
} : {
|
|
191
|
+
prefix: key.slice(0, star),
|
|
192
|
+
suffix: key.slice(star + 1),
|
|
193
|
+
targets
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
return patterns;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* `baseUrl` and `paths` of a tsconfig, with what it `extends` underneath.
|
|
200
|
+
* As in TypeScript, a config's own value replaces the inherited one whole.
|
|
201
|
+
* A file that cannot be read or parsed contributes nothing: the CLI then
|
|
202
|
+
* resolves no aliases, and Node reports the import it could not find.
|
|
203
|
+
*/
|
|
204
|
+
function readOptions(file, seen) {
|
|
205
|
+
if (seen.has(file)) return {};
|
|
206
|
+
seen.add(file);
|
|
207
|
+
let config;
|
|
208
|
+
try {
|
|
209
|
+
config = parseJsonc(readFileSync(file, "utf8"));
|
|
210
|
+
} catch {
|
|
211
|
+
return {};
|
|
212
|
+
}
|
|
213
|
+
if (!isRecord$1(config)) return {};
|
|
214
|
+
let options = {};
|
|
215
|
+
const parents = typeof config.extends === "string" ? [config.extends] : Array.isArray(config.extends) ? config.extends.filter((entry) => typeof entry === "string") : [];
|
|
216
|
+
for (const entry of parents) {
|
|
217
|
+
const parent = resolveExtends(entry, file);
|
|
218
|
+
if (parent !== null) options = {
|
|
219
|
+
...options,
|
|
220
|
+
...readOptions(parent, seen)
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
const compilerOptions = config.compilerOptions;
|
|
224
|
+
if (isRecord$1(compilerOptions)) {
|
|
225
|
+
if (typeof compilerOptions.baseUrl === "string") options.baseUrl = resolve(dirname(file), compilerOptions.baseUrl);
|
|
226
|
+
if (isRecord$1(compilerOptions.paths)) {
|
|
227
|
+
options.paths = toPatterns(compilerOptions.paths);
|
|
228
|
+
options.pathsDirectory = dirname(file);
|
|
229
|
+
}
|
|
230
|
+
for (const key of ["module", "moduleResolution"]) {
|
|
231
|
+
const value = compilerOptions[key];
|
|
232
|
+
if (typeof value === "string") options[key] = value.toLowerCase();
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return options;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* The `paths` mapping of a tsconfig file, or null when it (and what it
|
|
239
|
+
* extends) defines none. Targets are relative to `baseUrl` when one is set,
|
|
240
|
+
* otherwise to the folder of the config that defines `paths`.
|
|
241
|
+
*/
|
|
242
|
+
function loadPathMapping(tsconfigPath) {
|
|
243
|
+
const options = readOptions(tsconfigPath, /* @__PURE__ */ new Set());
|
|
244
|
+
if (options.paths === void 0 || options.pathsDirectory === void 0) return null;
|
|
245
|
+
return {
|
|
246
|
+
base: options.baseUrl ?? options.pathsDirectory,
|
|
247
|
+
patterns: options.paths
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
/** The nearest `tsconfig.json` in `directory` or a folder above it. */
|
|
251
|
+
function findTsconfig(directory) {
|
|
252
|
+
for (let current = directory;;) {
|
|
253
|
+
const candidate = join(current, "tsconfig.json");
|
|
254
|
+
if (isFile$2(candidate)) return candidate;
|
|
255
|
+
const parent = dirname(current);
|
|
256
|
+
if (parent === current) return null;
|
|
257
|
+
current = parent;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* The absolute paths `specifier` maps to, in order, or none when no pattern
|
|
262
|
+
* matches. An exact pattern wins; among wildcard patterns the longest
|
|
263
|
+
* prefix wins, as in TypeScript.
|
|
264
|
+
*/
|
|
265
|
+
function mapSpecifier(specifier, mapping) {
|
|
266
|
+
let best;
|
|
267
|
+
let matched = "";
|
|
268
|
+
for (const pattern of mapping.patterns) {
|
|
269
|
+
if (pattern.suffix === null) {
|
|
270
|
+
if (pattern.prefix === specifier) {
|
|
271
|
+
best = pattern;
|
|
272
|
+
matched = "";
|
|
273
|
+
break;
|
|
274
|
+
}
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
if (specifier.length >= pattern.prefix.length + pattern.suffix.length && specifier.startsWith(pattern.prefix) && specifier.endsWith(pattern.suffix) && (best === void 0 || pattern.prefix.length > best.prefix.length)) {
|
|
278
|
+
best = pattern;
|
|
279
|
+
matched = specifier.slice(pattern.prefix.length, specifier.length - pattern.suffix.length);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
if (best === void 0) return [];
|
|
283
|
+
return best.targets.map((target) => resolve(mapping.base, target.replace("*", matched)));
|
|
284
|
+
}
|
|
285
|
+
// ../loader/src/resolve-hook.ts
|
|
286
|
+
/** The TypeScript source a JavaScript extension in an import stands for. */
|
|
287
|
+
const SOURCE_EXTENSION = {
|
|
288
|
+
".js": ".ts",
|
|
289
|
+
".mjs": ".mts",
|
|
290
|
+
".cjs": ".cts"
|
|
291
|
+
};
|
|
292
|
+
const APPENDED_EXTENSIONS = [
|
|
293
|
+
".ts",
|
|
294
|
+
".mts",
|
|
295
|
+
".cts",
|
|
296
|
+
".js",
|
|
297
|
+
".mjs",
|
|
298
|
+
".cjs"
|
|
299
|
+
];
|
|
300
|
+
const INDEX_FILES = [
|
|
301
|
+
"index.ts",
|
|
302
|
+
"index.mts",
|
|
303
|
+
"index.js",
|
|
304
|
+
"index.mjs"
|
|
305
|
+
];
|
|
306
|
+
function isFile$1(path) {
|
|
307
|
+
return statSync(path, { throwIfNoEntry: false })?.isFile() === true;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* The files an import of `path` can mean, in the order tried: the path
|
|
311
|
+
* itself, the `.ts` behind a `.js` name (how TypeScript projects with
|
|
312
|
+
* `module: nodenext` write imports), then an added extension and a folder's
|
|
313
|
+
* index file for an extensionless import.
|
|
314
|
+
*/
|
|
315
|
+
function importCandidates(path) {
|
|
316
|
+
const extension = extname(path);
|
|
317
|
+
const source = SOURCE_EXTENSION[extension];
|
|
318
|
+
if (source !== void 0) return [path, `${path.slice(0, -extension.length)}${source}`];
|
|
319
|
+
return [
|
|
320
|
+
path,
|
|
321
|
+
...APPENDED_EXTENSIONS.map((appended) => `${path}${appended}`),
|
|
322
|
+
...INDEX_FILES.map((index) => join(path, index))
|
|
323
|
+
];
|
|
324
|
+
}
|
|
325
|
+
const mappings = /* @__PURE__ */ new Map();
|
|
326
|
+
function pathMappingFor(directory) {
|
|
327
|
+
let mapping = mappings.get(directory);
|
|
328
|
+
if (mapping === void 0) {
|
|
329
|
+
const tsconfig = findTsconfig(directory);
|
|
330
|
+
mapping = tsconfig === null ? null : loadPathMapping(tsconfig);
|
|
331
|
+
mappings.set(directory, mapping);
|
|
332
|
+
}
|
|
333
|
+
return mapping;
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* The file an import in `importer` means when Node's own resolution found
|
|
337
|
+
* nothing, or null. Relative imports get the candidates of
|
|
338
|
+
* {@link importCandidates}; any other specifier goes through the `paths` of
|
|
339
|
+
* the nearest `tsconfig.json`.
|
|
340
|
+
*/
|
|
341
|
+
function resolveAppImport(specifier, importer) {
|
|
342
|
+
const directory = dirname(importer);
|
|
343
|
+
let targets;
|
|
344
|
+
if (specifier.startsWith("./") || specifier.startsWith("../")) targets = [resolve(directory, specifier)];
|
|
345
|
+
else if (specifier.startsWith("node:")) return null;
|
|
346
|
+
else {
|
|
347
|
+
const mapping = pathMappingFor(directory);
|
|
348
|
+
targets = mapping === null ? [] : mapSpecifier(specifier, mapping);
|
|
349
|
+
}
|
|
350
|
+
for (const target of targets) {
|
|
351
|
+
const found = importCandidates(target).find(isFile$1);
|
|
352
|
+
if (found !== void 0) return found;
|
|
353
|
+
}
|
|
354
|
+
return null;
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* The file `server-only` resolves to, next to the bundled loader: each
|
|
358
|
+
* bin's build writes an empty `dist/server-only.cjs` (the
|
|
359
|
+
* `server-only-stub` plugin in its `tsdown.config.ts`). React's marker
|
|
360
|
+
* package throws at import outside the `react-server` condition, and an
|
|
361
|
+
* app's memory file may import it (Next.js's convention for server code).
|
|
362
|
+
* The bins are server code, so it loads as nothing instead (decisions 81
|
|
363
|
+
* and 97). A real file, because Node 22.18 skips resolve hooks for
|
|
364
|
+
* `require()` in CommonJS loaded by `import` once any load hook is
|
|
365
|
+
* registered, and `require()` cannot load a `data:` URL.
|
|
366
|
+
*/
|
|
367
|
+
const SERVER_ONLY_FILE = "server-only.cjs";
|
|
368
|
+
/**
|
|
369
|
+
* The resolve hook. `server-only`, the exact bare specifier, maps to
|
|
370
|
+
* {@link SERVER_ONLY_FILE} before Node resolves it, from any importer, so
|
|
371
|
+
* an installed copy is not loaded either. Everything else asks Node first
|
|
372
|
+
* and looks further only when Node fails, for an importer that is a file
|
|
373
|
+
* outside `node_modules`.
|
|
374
|
+
*/
|
|
375
|
+
const resolveHook = (specifier, context, nextResolve) => {
|
|
376
|
+
if (specifier === "server-only") return {
|
|
377
|
+
url: new URL(SERVER_ONLY_FILE, import.meta.url).href,
|
|
378
|
+
shortCircuit: true
|
|
379
|
+
};
|
|
380
|
+
try {
|
|
381
|
+
return nextResolve(specifier, context);
|
|
382
|
+
} catch (error) {
|
|
383
|
+
const parent = context.parentURL;
|
|
384
|
+
if (parent === void 0 || !parent.startsWith("file:")) throw error;
|
|
385
|
+
const importer = fileURLToPath(parent);
|
|
386
|
+
if (importer.split(/[\\/]/).includes("node_modules")) throw error;
|
|
387
|
+
const found = resolveAppImport(specifier, importer);
|
|
388
|
+
if (found === null) throw error;
|
|
389
|
+
return nextResolve(pathToFileURL(found).href, context);
|
|
390
|
+
}
|
|
391
|
+
};
|
|
392
|
+
let registered = false;
|
|
393
|
+
/**
|
|
394
|
+
* Teach this process the imports a TypeScript app writes that Node's type
|
|
395
|
+
* stripping does not resolve: extensionless and `.js`-for-`.ts` relative
|
|
396
|
+
* imports, and tsconfig `paths`; and load `server-only` as an empty module.
|
|
397
|
+
*
|
|
398
|
+
* `module.registerHooks` installs a synchronous resolve hook on the current
|
|
399
|
+
* thread, for `import` and `require` alike (`module.register`, the
|
|
400
|
+
* asynchronous one, is deprecated from Node 26). Apart from `server-only`,
|
|
401
|
+
* the resolve hook asks Node first and only looks further when Node fails,
|
|
402
|
+
* so anything Node resolves, every other package included, is untouched.
|
|
403
|
+
* Registering twice does nothing.
|
|
404
|
+
*/
|
|
405
|
+
function registerAppResolver() {
|
|
406
|
+
if (registered) return;
|
|
407
|
+
registered = true;
|
|
408
|
+
registerHooks({ resolve: resolveHook });
|
|
409
|
+
}
|
|
410
|
+
// src/cli/args.ts
|
|
411
|
+
/** A usage error: bad flags. The bin prints it with the usage and exits 2. */
|
|
412
|
+
var UsageError = class extends Error {
|
|
413
|
+
name = "UsageError";
|
|
414
|
+
};
|
|
415
|
+
const USAGE = `Usage: mnemocyte-mcp --entity-id <id> [options]
|
|
416
|
+
|
|
417
|
+
Serves Mnemocyte memory over MCP on stdio, for one scope fixed here.
|
|
418
|
+
|
|
419
|
+
Scope:
|
|
420
|
+
--entity-id <id> The user or entity whose memories the tools use. Required.
|
|
421
|
+
--namespace <name> Defaults to the memory file's createMemory({ namespace }).
|
|
422
|
+
--agent-id <id> Narrow the scope to one agent.
|
|
423
|
+
--session-id <id> Narrow the scope to one session.
|
|
424
|
+
|
|
425
|
+
Memory file:
|
|
426
|
+
--project <dir> The app's folder. --config, --env-file and the lookup
|
|
427
|
+
are relative to it. Default: the working directory.
|
|
428
|
+
--config <file> The app's memory file. Default: the first of memory.ts,
|
|
429
|
+
memory.mts, memory.js, memory.mjs in ., lib, src, src/lib.
|
|
430
|
+
--env-file <file> Load this file into the environment first. Default:
|
|
431
|
+
.env.local, then .env, in the app's folder, each when
|
|
432
|
+
it exists (no .env.local when NODE_ENV is test).
|
|
433
|
+
|
|
434
|
+
Tools:
|
|
435
|
+
--allow-forget Also list forgetMemory, which deletes for good.
|
|
436
|
+
--read-only List searchMemories only.
|
|
437
|
+
|
|
438
|
+
-h, --help Show this help.
|
|
439
|
+
-v, --version Show the version.
|
|
440
|
+
`;
|
|
441
|
+
const SCOPE_FLAGS = [
|
|
442
|
+
["namespace", "namespace"],
|
|
443
|
+
["entity-id", "entityId"],
|
|
444
|
+
["agent-id", "agentId"],
|
|
445
|
+
["session-id", "sessionId"]
|
|
446
|
+
];
|
|
447
|
+
function nonEmpty(flag, value) {
|
|
448
|
+
if (value !== void 0 && value.trim() === "") throw new UsageError(`--${flag} cannot be empty.`);
|
|
449
|
+
return value;
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Parse the bin's arguments.
|
|
453
|
+
*
|
|
454
|
+
* @throws {UsageError} For an unknown flag, a positional argument, a missing
|
|
455
|
+
* or empty `--entity-id`, an empty value, or `--read-only` with
|
|
456
|
+
* `--allow-forget`.
|
|
457
|
+
*/
|
|
458
|
+
function parseCliArgs(argv) {
|
|
459
|
+
let parsed;
|
|
460
|
+
try {
|
|
461
|
+
parsed = parse(argv);
|
|
462
|
+
} catch (error) {
|
|
463
|
+
throw new UsageError(error instanceof Error ? error.message : String(error));
|
|
464
|
+
}
|
|
465
|
+
const { values, positionals } = parsed;
|
|
466
|
+
if (values.help === true) return { command: "help" };
|
|
467
|
+
if (values.version === true) return { command: "version" };
|
|
468
|
+
if (positionals.length > 0) throw new UsageError(`Unexpected argument ${positionals[0]}.`);
|
|
469
|
+
const scope = {};
|
|
470
|
+
for (const [flag, field] of SCOPE_FLAGS) {
|
|
471
|
+
const value = nonEmpty(flag, values[flag]);
|
|
472
|
+
if (value !== void 0) scope[field] = value;
|
|
473
|
+
}
|
|
474
|
+
const entityId = scope.entityId;
|
|
475
|
+
if (entityId === void 0) throw new UsageError("--entity-id is required: the server serves one entity's memories.");
|
|
476
|
+
const allowForget = values["allow-forget"] === true;
|
|
477
|
+
const readOnly = values["read-only"] === true;
|
|
478
|
+
if (allowForget && readOnly) throw new UsageError("--read-only and --allow-forget cannot be combined.");
|
|
479
|
+
return {
|
|
480
|
+
command: "serve",
|
|
481
|
+
scope: {
|
|
482
|
+
...scope,
|
|
483
|
+
entityId
|
|
484
|
+
},
|
|
485
|
+
project: nonEmpty("project", values.project),
|
|
486
|
+
config: nonEmpty("config", values.config),
|
|
487
|
+
envFile: nonEmpty("env-file", values["env-file"]),
|
|
488
|
+
allowForget,
|
|
489
|
+
readOnly
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
function parse(argv) {
|
|
493
|
+
return parseArgs({
|
|
494
|
+
args: [...argv],
|
|
495
|
+
allowPositionals: true,
|
|
496
|
+
strict: true,
|
|
497
|
+
options: {
|
|
498
|
+
namespace: { type: "string" },
|
|
499
|
+
"entity-id": { type: "string" },
|
|
500
|
+
"agent-id": { type: "string" },
|
|
501
|
+
"session-id": { type: "string" },
|
|
502
|
+
project: { type: "string" },
|
|
503
|
+
config: { type: "string" },
|
|
504
|
+
"env-file": { type: "string" },
|
|
505
|
+
"allow-forget": { type: "boolean" },
|
|
506
|
+
"read-only": { type: "boolean" },
|
|
507
|
+
help: {
|
|
508
|
+
type: "boolean",
|
|
509
|
+
short: "h"
|
|
510
|
+
},
|
|
511
|
+
version: {
|
|
512
|
+
type: "boolean",
|
|
513
|
+
short: "v"
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
// src/cli/memory-file.ts
|
|
519
|
+
function isFile(path) {
|
|
520
|
+
return statSync(path, { throwIfNoEntry: false })?.isFile() === true;
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* The memory file to load: `--config` when given, which must exist,
|
|
524
|
+
* otherwise the first one found.
|
|
525
|
+
*
|
|
526
|
+
* @throws {UsageError} When `--config` names no file or no file is found.
|
|
527
|
+
*/
|
|
528
|
+
function locateMemoryFile(cwd, config) {
|
|
529
|
+
if (config !== void 0) {
|
|
530
|
+
const file = resolve(cwd, config);
|
|
531
|
+
if (!isFile(file)) throw new UsageError(`--config: ${config} is not a file.`);
|
|
532
|
+
return file;
|
|
533
|
+
}
|
|
534
|
+
const found = findMemoryFile(cwd);
|
|
535
|
+
if (found === null) throw new UsageError(`No memory file found in ${cwd}. Pass --config <file> with the file that exports createMemory()'s client.`);
|
|
536
|
+
return found;
|
|
537
|
+
}
|
|
538
|
+
function errorCode(error) {
|
|
539
|
+
if (typeof error !== "object" || error === null || !("code" in error)) return;
|
|
540
|
+
return typeof error.code === "string" ? error.code : void 0;
|
|
541
|
+
}
|
|
542
|
+
function firstLine(error) {
|
|
543
|
+
return (error instanceof Error ? error.message : String(error)).split("\n")[0]?.trim() ?? "";
|
|
544
|
+
}
|
|
545
|
+
const BUILD_HINT = "Build the file and pass --config <built .js>.";
|
|
546
|
+
function loadError(name, error) {
|
|
547
|
+
const detail = firstLine(error);
|
|
548
|
+
switch (errorCode(error)) {
|
|
549
|
+
case "ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX": return new UsageError(`${name} uses TypeScript syntax Node cannot run (${detail}). Node loads TypeScript by removing the types, so enums, namespaces with code and parameter properties do not load. ${BUILD_HINT}`, { cause: error });
|
|
550
|
+
case "ERR_UNKNOWN_FILE_EXTENSION": return new UsageError(`Node cannot load ${name} (${detail}). .tsx files are not supported, and neither is a Node started with type stripping turned off. ${BUILD_HINT}`, { cause: error });
|
|
551
|
+
case "ERR_MODULE_NOT_FOUND": return new UsageError(`${name} imports a module that was not found (${detail}). Relative imports resolve without an extension or with ".js" for a ".ts" file, and through tsconfig "paths"; for other aliases, build the file and pass --config <built .js>.`, { cause: error });
|
|
552
|
+
default: return new UsageError(`Loading ${name} failed: ${detail}`, { cause: error });
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
function isRecord(value) {
|
|
556
|
+
return typeof value === "object" && value !== null;
|
|
557
|
+
}
|
|
558
|
+
function isUnboundClient(value) {
|
|
559
|
+
return isRecord(value) && typeof value.for === "function" && typeof value.search === "function" && typeof value.add === "function" && typeof value.delete === "function";
|
|
560
|
+
}
|
|
561
|
+
function isBoundClient(value) {
|
|
562
|
+
return isRecord(value) && isRecord(value.scope) && typeof value.search === "function" && !("for" in value);
|
|
563
|
+
}
|
|
564
|
+
/**
|
|
565
|
+
* Import the app's memory file and return its client: the `memory` export,
|
|
566
|
+
* else the default export's `memory`, else the default export, as the
|
|
567
|
+
* `mnemocyte` CLI reads it. A `.ts` file loads through Node's type stripping
|
|
568
|
+
* with the shared resolve hook (`@mnemocyte/loader`) for extensionless,
|
|
569
|
+
* `.js`-for-`.ts` and tsconfig `paths` imports.
|
|
570
|
+
*
|
|
571
|
+
* @throws {UsageError} When the file does not load, or exports a bound
|
|
572
|
+
* client or no client.
|
|
573
|
+
*/
|
|
574
|
+
async function loadMemoryClient(file, cwd) {
|
|
575
|
+
const name = relative(cwd, file).replaceAll("\\", "/") || file;
|
|
576
|
+
registerAppResolver();
|
|
577
|
+
let exports;
|
|
578
|
+
try {
|
|
579
|
+
exports = await import(pathToFileURL(file).href);
|
|
580
|
+
} catch (error) {
|
|
581
|
+
throw loadError(name, error);
|
|
582
|
+
}
|
|
583
|
+
const fallback = exports.default;
|
|
584
|
+
const candidates = [
|
|
585
|
+
exports.memory,
|
|
586
|
+
isRecord(fallback) && "memory" in fallback ? fallback.memory : void 0,
|
|
587
|
+
fallback
|
|
588
|
+
].filter((candidate) => candidate !== void 0);
|
|
589
|
+
const client = candidates.find(isUnboundClient);
|
|
590
|
+
if (client !== void 0) return client;
|
|
591
|
+
if (candidates.some(isBoundClient)) throw new UsageError(`${name} exports a bound client from memory.for(...). Export the client from createMemory() itself; mnemocyte-mcp binds it to the scope in its flags.`);
|
|
592
|
+
throw new UsageError(`${name} does not export a memory client. Export the result of createMemory() as "memory": export const memory = createMemory({ ... });`);
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* `--env-file` when given, else `.env.local` and then `.env` in the app's
|
|
596
|
+
* folder, each when it exists (`.env.local` not when `NODE_ENV` is `test`),
|
|
597
|
+
* as the `mnemocyte` CLI does. A variable that is already set is kept.
|
|
598
|
+
*
|
|
599
|
+
* @returns The files that were read, for the startup line.
|
|
600
|
+
*/
|
|
601
|
+
function loadEnvironment(cwd, envFile) {
|
|
602
|
+
if (envFile === void 0) return loadEnvFiles({ directory: cwd });
|
|
603
|
+
try {
|
|
604
|
+
process.loadEnvFile(resolve(cwd, envFile));
|
|
605
|
+
} catch (error) {
|
|
606
|
+
throw new UsageError(`--env-file: could not read ${envFile}.`, { cause: error });
|
|
607
|
+
}
|
|
608
|
+
return [envFile];
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* The app's folder: `--project` resolved against the working directory, or
|
|
612
|
+
* the working directory itself. MCP clients do not all say which folder
|
|
613
|
+
* they start a server in.
|
|
614
|
+
*
|
|
615
|
+
* @throws {UsageError} When `--project` is not a folder.
|
|
616
|
+
*/
|
|
617
|
+
function projectFolder(cwd, project) {
|
|
618
|
+
if (project === void 0) return cwd;
|
|
619
|
+
const folder = resolve(cwd, project);
|
|
620
|
+
if (statSync(folder, { throwIfNoEntry: false })?.isDirectory() !== true) throw new UsageError(`--project: ${project} is not a folder.`);
|
|
621
|
+
return folder;
|
|
622
|
+
}
|
|
623
|
+
function describeError(error) {
|
|
624
|
+
return `mnemocyte-mcp: ${error instanceof Error ? error.message : String(error)}\n`;
|
|
625
|
+
}
|
|
626
|
+
function describeScope(scope) {
|
|
627
|
+
return Object.entries(scope).filter(([, value]) => value !== void 0).map(([field, value]) => `${field}=${String(value)}`).join(" ");
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Parse the arguments, load the memory file and bind its client to the
|
|
631
|
+
* scope in the flags. Resolves with what to do next; never rejects. Errors
|
|
632
|
+
* are written to `io.error`: bad flags and an unusable memory file exit 2,
|
|
633
|
+
* anything else 1.
|
|
634
|
+
*/
|
|
635
|
+
async function prepare(argv, io, version) {
|
|
636
|
+
let args;
|
|
637
|
+
try {
|
|
638
|
+
args = parseCliArgs(argv);
|
|
639
|
+
} catch (error) {
|
|
640
|
+
io.error(`${describeError(error)}\n${USAGE}`);
|
|
641
|
+
return {
|
|
642
|
+
kind: "exit",
|
|
643
|
+
code: 2
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
if (args.command === "help") {
|
|
647
|
+
io.write(USAGE);
|
|
648
|
+
return {
|
|
649
|
+
kind: "exit",
|
|
650
|
+
code: 0
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
if (args.command === "version") {
|
|
654
|
+
io.write(`${version}\n`);
|
|
655
|
+
return {
|
|
656
|
+
kind: "exit",
|
|
657
|
+
code: 0
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
try {
|
|
661
|
+
const project = projectFolder(io.cwd, args.project);
|
|
662
|
+
const envFiles = loadEnvironment(project, args.envFile);
|
|
663
|
+
const file = locateMemoryFile(project, args.config);
|
|
664
|
+
const memory = bind(await loadMemoryClient(file, project), args.scope);
|
|
665
|
+
const { allowForget, readOnly } = args;
|
|
666
|
+
createMemoryMcpServer({
|
|
667
|
+
memory,
|
|
668
|
+
allowForget,
|
|
669
|
+
readOnly
|
|
670
|
+
});
|
|
671
|
+
const label = relative(project, file).replaceAll("\\", "/") || file;
|
|
672
|
+
io.error(`mnemocyte-mcp ${version}: ${label}, scope ${describeScope(memory.scope)}, tools ${toolNames({
|
|
673
|
+
allowForget,
|
|
674
|
+
readOnly
|
|
675
|
+
}).join(", ")}, env ${envFiles.length === 0 ? "none" : envFiles.join(", ")}\n`);
|
|
676
|
+
return {
|
|
677
|
+
kind: "serve",
|
|
678
|
+
createServer: () => createMemoryMcpServer({
|
|
679
|
+
memory,
|
|
680
|
+
allowForget,
|
|
681
|
+
readOnly
|
|
682
|
+
})
|
|
683
|
+
};
|
|
684
|
+
} catch (error) {
|
|
685
|
+
io.error(describeError(error));
|
|
686
|
+
return {
|
|
687
|
+
kind: "exit",
|
|
688
|
+
code: error instanceof UsageError || isMnemocyteError(error) && (error.code === "VALIDATION" || error.code === "CONFIG") ? 2 : 1
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
function bind(client, scope) {
|
|
693
|
+
try {
|
|
694
|
+
return client.for(scope);
|
|
695
|
+
} catch (error) {
|
|
696
|
+
if (isMnemocyteError(error) && error.code === "VALIDATION") {
|
|
697
|
+
const hint = scope.namespace === void 0 ? " Pass --namespace, or set namespace in the memory file's createMemory()." : "";
|
|
698
|
+
throw new UsageError(`The scope in the flags is not valid: ${error.message}${hint}`, { cause: error });
|
|
699
|
+
}
|
|
700
|
+
throw error;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
// src/cli.ts
|
|
704
|
+
const io = {
|
|
705
|
+
cwd: process.cwd(),
|
|
706
|
+
write: (text) => process.stdout.write(text),
|
|
707
|
+
error: (text) => process.stderr.write(text)
|
|
708
|
+
};
|
|
709
|
+
function exit(code) {
|
|
710
|
+
process.stdout.write("", () => {
|
|
711
|
+
process.stderr.write("", () => process.exit(code));
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
redirectConsoleToStderr();
|
|
715
|
+
prepare(process.argv.slice(2), io, SERVER_INFO.version).then((prepared) => {
|
|
716
|
+
if (prepared.kind === "exit") {
|
|
717
|
+
exit(prepared.code);
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
serveStdio(prepared.createServer, { onerror: (error) => io.error(`mnemocyte-mcp: ${error.message}\n`) });
|
|
721
|
+
let ended = false;
|
|
722
|
+
const end = () => {
|
|
723
|
+
if (!ended) {
|
|
724
|
+
ended = true;
|
|
725
|
+
exit(0);
|
|
726
|
+
}
|
|
727
|
+
};
|
|
728
|
+
process.stdin.once("end", end);
|
|
729
|
+
process.stdin.once("close", end);
|
|
730
|
+
});
|
|
731
|
+
export {};
|
|
732
|
+
|
|
733
|
+
//# sourceMappingURL=cli.mjs.map
|