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