@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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.mjs","names":["isFile","isFile","isRecord","isFile","isFile"],"sources":["../src/cli/console.ts","../../loader/src/env-files.ts","../../loader/src/memory-file.ts","../../loader/src/tsconfig.ts","../../loader/src/resolve-hook.ts","../src/cli/args.ts","../src/cli/memory-file.ts","../src/cli/main.ts","../src/cli.ts"],"sourcesContent":["import { Console } from \"node:console\";\n\n// The console methods that write to standard output.\nconst STDOUT_METHODS = [\n\t\"log\",\n\t\"info\",\n\t\"debug\",\n\t\"dir\",\n\t\"dirxml\",\n\t\"table\",\n\t\"group\",\n\t\"groupCollapsed\",\n\t\"groupEnd\",\n\t\"count\",\n\t\"countReset\",\n\t\"time\",\n\t\"timeEnd\",\n\t\"timeLog\",\n] as const;\n\n/**\n * Send everything `console` would print to standard output to standard\n * error instead. On stdio, standard output carries only MCP messages, so a\n * `console.log` in the app's memory file or a module it imports would\n * corrupt the stream. Writes to `process.stdout` itself are not caught.\n */\nexport function redirectConsoleToStderr(): void {\n\tconst toStderr = new Console({\n\t\tstdout: process.stderr,\n\t\tstderr: process.stderr,\n\t});\n\tfor (const method of STDOUT_METHODS) {\n\t\t// Console binds its methods to the instance, so they can move.\n\t\tObject.defineProperty(console, method, {\n\t\t\tvalue: toStderr[method],\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t\tenumerable: true,\n\t\t});\n\t}\n}\n","import { statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * The environment files read from the project, in order: Next.js's order\n * for these two (ARCHITECTURE decision 78). The `.env.$(NODE_ENV)` files\n * are left out, since the bins run outside a mode.\n */\nexport const ENV_FILE_NAMES: readonly string[] = [\".env.local\", \".env\"];\n\n/** Input of {@link loadEnvFiles}. */\nexport interface LoadEnvFilesInput {\n\t/** The project folder the files are read from. */\n\treadonly directory: string;\n}\n\nfunction isFile(path: string): boolean {\n\treturn statSync(path, { throwIfNoEntry: false })?.isFile() === true;\n}\n\n/**\n * Load `.env.local`, then `.env`, from the project into `process.env`, each\n * when it exists. `.env.local` is skipped when `NODE_ENV` is `test`, as in\n * Next.js, so tests do not depend on one machine's overrides; only the real\n * environment's `NODE_ENV` counts, since no file is read before the check.\n * `process.loadEnvFile` keeps a variable that is already set, so the real\n * environment wins over both files and `.env.local` over `.env`.\n *\n * @returns The names of the files that were read, in order.\n */\nexport function loadEnvFiles(input: LoadEnvFilesInput): string[] {\n\tconst skipLocal = process.env.NODE_ENV === \"test\";\n\tconst loaded: string[] = [];\n\tfor (const name of ENV_FILE_NAMES) {\n\t\tif (skipLocal && name === \".env.local\") {\n\t\t\tcontinue;\n\t\t}\n\t\tconst path = join(input.directory, name);\n\t\tif (isFile(path)) {\n\t\t\tprocess.loadEnvFile(path);\n\t\t\tloaded.push(name);\n\t\t}\n\t}\n\treturn loaded;\n}\n","import { statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/** Folders searched for a memory file, in order, relative to the project. */\nexport const MEMORY_FILE_DIRECTORIES: readonly string[] = [\n\t\"\",\n\t\"lib\",\n\t\"src\",\n\t\"src/lib\",\n];\n\n/** File names tried in each folder, in order. */\nexport const MEMORY_FILE_NAMES: readonly string[] = [\n\t\"memory.ts\",\n\t\"memory.mts\",\n\t\"memory.js\",\n\t\"memory.mjs\",\n];\n\nfunction isFile(path: string): boolean {\n\treturn statSync(path, { throwIfNoEntry: false })?.isFile() === true;\n}\n\n/** The first memory file in the project, or null. */\nexport function findMemoryFile(cwd: string): string | null {\n\tfor (const directory of MEMORY_FILE_DIRECTORIES) {\n\t\tfor (const name of MEMORY_FILE_NAMES) {\n\t\t\tconst candidate = join(cwd, directory, name);\n\t\t\tif (isFile(candidate)) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}\n","import { readFileSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\n\n/** One `compilerOptions.paths` entry: `prefix*suffix`, or an exact name. */\ninterface PathPattern {\n\treadonly prefix: string;\n\t/** `null` for a pattern without `*`, which must match exactly. */\n\treadonly suffix: string | null;\n\treadonly targets: readonly string[];\n}\n\n/** The `paths` of a tsconfig and the folder its targets are relative to. */\nexport interface PathMapping {\n\treadonly base: string;\n\treadonly patterns: readonly PathPattern[];\n}\n\ninterface RawOptions {\n\tbaseUrl?: string;\n\tpaths?: PathPattern[];\n\tpathsDirectory?: string;\n\tmodule?: string;\n\tmoduleResolution?: string;\n}\n\n/** `compilerOptions.module` and `moduleResolution`, in lower case. */\nexport interface ModuleOptions {\n\treadonly module?: string;\n\treadonly moduleResolution?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isFile(path: string): boolean {\n\treturn statSync(path, { throwIfNoEntry: false })?.isFile() === true;\n}\n\n/** Index just past the string literal that starts at `start`. */\nfunction stringEnd(text: string, start: number): number {\n\tlet index = start + 1;\n\twhile (index < text.length) {\n\t\tif (text[index] === \"\\\\\") {\n\t\t\tindex += 2;\n\t\t} else if (text[index] === '\"') {\n\t\t\treturn index + 1;\n\t\t} else {\n\t\t\tindex += 1;\n\t\t}\n\t}\n\treturn text.length;\n}\n\nconst BEFORE_CLOSING_BRACKET = /\\s*[}\\]]/y;\n\n/**\n * Parse JSON with comments and trailing commas, which `tsconfig.json`\n * allows and `JSON.parse` rejects. String literals are copied untouched, so\n * a `//` or a comma inside one survives.\n *\n * @throws {SyntaxError} When what is left is not JSON.\n */\nexport function parseJsonc(text: string): unknown {\n\tlet withoutComments = \"\";\n\tfor (let index = 0; index < text.length; ) {\n\t\tif (text[index] === '\"') {\n\t\t\tconst end = stringEnd(text, index);\n\t\t\twithoutComments += text.slice(index, end);\n\t\t\tindex = end;\n\t\t} else if (text.startsWith(\"//\", index)) {\n\t\t\tconst newline = text.indexOf(\"\\n\", index);\n\t\t\tindex = newline === -1 ? text.length : newline;\n\t\t} else if (text.startsWith(\"/*\", index)) {\n\t\t\tconst close = text.indexOf(\"*/\", index + 2);\n\t\t\tindex = close === -1 ? text.length : close + 2;\n\t\t} else {\n\t\t\twithoutComments += text[index];\n\t\t\tindex += 1;\n\t\t}\n\t}\n\n\tlet json = \"\";\n\tfor (let index = 0; index < withoutComments.length; ) {\n\t\tif (withoutComments[index] === '\"') {\n\t\t\tconst end = stringEnd(withoutComments, index);\n\t\t\tjson += withoutComments.slice(index, end);\n\t\t\tindex = end;\n\t\t\tcontinue;\n\t\t}\n\t\tif (withoutComments[index] === \",\") {\n\t\t\tBEFORE_CLOSING_BRACKET.lastIndex = index + 1;\n\t\t\tif (BEFORE_CLOSING_BRACKET.test(withoutComments)) {\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tjson += withoutComments[index];\n\t\tindex += 1;\n\t}\n\t// A UTF-8 byte order mark is not JSON either.\n\treturn JSON.parse(json.replace(/^/, \"\"));\n}\n\n/** The file an `extends` entry names, or null when it cannot be found. */\nfunction resolveExtends(entry: string, from: string): string | null {\n\tif (entry.startsWith(\"./\") || entry.startsWith(\"../\") || isAbsolute(entry)) {\n\t\tconst path = resolve(dirname(from), entry);\n\t\t// \"./tsconfig.base\" means tsconfig.base.json: a name's last dot is not\n\t\t// necessarily an extension, so both spellings are tried.\n\t\treturn [path, `${path}.json`].find(isFile) ?? null;\n\t}\n\t// A package, such as \"@tsconfig/node22/tsconfig.json\".\n\tconst require = createRequire(from);\n\tfor (const specifier of [entry, `${entry}.json`, `${entry}/tsconfig.json`]) {\n\t\ttry {\n\t\t\treturn require.resolve(specifier);\n\t\t} catch {\n\t\t\t// Try the next spelling.\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction toPatterns(paths: Record<string, unknown>): PathPattern[] {\n\tconst patterns: PathPattern[] = [];\n\tfor (const [key, value] of Object.entries(paths)) {\n\t\tif (!Array.isArray(value)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst targets = value.filter(\n\t\t\t(target): target is string => typeof target === \"string\",\n\t\t);\n\t\tconst star = key.indexOf(\"*\");\n\t\tpatterns.push(\n\t\t\tstar === -1\n\t\t\t\t? { prefix: key, suffix: null, targets }\n\t\t\t\t: { prefix: key.slice(0, star), suffix: key.slice(star + 1), targets },\n\t\t);\n\t}\n\treturn patterns;\n}\n\n/**\n * `baseUrl` and `paths` of a tsconfig, with what it `extends` underneath.\n * As in TypeScript, a config's own value replaces the inherited one whole.\n * A file that cannot be read or parsed contributes nothing: the CLI then\n * resolves no aliases, and Node reports the import it could not find.\n */\nfunction readOptions(file: string, seen: Set<string>): RawOptions {\n\tif (seen.has(file)) {\n\t\treturn {};\n\t}\n\tseen.add(file);\n\tlet config: unknown;\n\ttry {\n\t\tconfig = parseJsonc(readFileSync(file, \"utf8\"));\n\t} catch {\n\t\treturn {};\n\t}\n\tif (!isRecord(config)) {\n\t\treturn {};\n\t}\n\n\tlet options: RawOptions = {};\n\tconst parents =\n\t\ttypeof config.extends === \"string\"\n\t\t\t? [config.extends]\n\t\t\t: Array.isArray(config.extends)\n\t\t\t\t? config.extends.filter(\n\t\t\t\t\t\t(entry): entry is string => typeof entry === \"string\",\n\t\t\t\t\t)\n\t\t\t\t: [];\n\tfor (const entry of parents) {\n\t\tconst parent = resolveExtends(entry, file);\n\t\tif (parent !== null) {\n\t\t\toptions = { ...options, ...readOptions(parent, seen) };\n\t\t}\n\t}\n\n\tconst compilerOptions = config.compilerOptions;\n\tif (isRecord(compilerOptions)) {\n\t\tif (typeof compilerOptions.baseUrl === \"string\") {\n\t\t\toptions.baseUrl = resolve(dirname(file), compilerOptions.baseUrl);\n\t\t}\n\t\tif (isRecord(compilerOptions.paths)) {\n\t\t\toptions.paths = toPatterns(compilerOptions.paths);\n\t\t\toptions.pathsDirectory = dirname(file);\n\t\t}\n\t\tfor (const key of [\"module\", \"moduleResolution\"] as const) {\n\t\t\tconst value = compilerOptions[key];\n\t\t\tif (typeof value === \"string\") {\n\t\t\t\toptions[key] = value.toLowerCase();\n\t\t\t}\n\t\t}\n\t}\n\treturn options;\n}\n\n/**\n * The `paths` mapping of a tsconfig file, or null when it (and what it\n * extends) defines none. Targets are relative to `baseUrl` when one is set,\n * otherwise to the folder of the config that defines `paths`.\n */\nexport function loadPathMapping(tsconfigPath: string): PathMapping | null {\n\tconst options = readOptions(tsconfigPath, new Set());\n\tif (options.paths === undefined || options.pathsDirectory === undefined) {\n\t\treturn null;\n\t}\n\treturn {\n\t\tbase: options.baseUrl ?? options.pathsDirectory,\n\t\tpatterns: options.paths,\n\t};\n}\n\n/**\n * `module` and `moduleResolution` of a tsconfig file, with what it extends\n * underneath, as `mnemocyte init` needs them to spell an import. A file\n * that cannot be read contributes nothing.\n */\nexport function loadModuleOptions(tsconfigPath: string): ModuleOptions {\n\tconst options = readOptions(tsconfigPath, new Set());\n\treturn {\n\t\t...(options.module === undefined ? {} : { module: options.module }),\n\t\t...(options.moduleResolution === undefined\n\t\t\t? {}\n\t\t\t: { moduleResolution: options.moduleResolution }),\n\t};\n}\n\n/** The nearest `tsconfig.json` in `directory` or a folder above it. */\nexport function findTsconfig(directory: string): string | null {\n\tfor (let current = directory; ; ) {\n\t\tconst candidate = join(current, \"tsconfig.json\");\n\t\tif (isFile(candidate)) {\n\t\t\treturn candidate;\n\t\t}\n\t\tconst parent = dirname(current);\n\t\tif (parent === current) {\n\t\t\treturn null;\n\t\t}\n\t\tcurrent = parent;\n\t}\n}\n\n/**\n * The absolute paths `specifier` maps to, in order, or none when no pattern\n * matches. An exact pattern wins; among wildcard patterns the longest\n * prefix wins, as in TypeScript.\n */\nexport function mapSpecifier(\n\tspecifier: string,\n\tmapping: PathMapping,\n): string[] {\n\tlet best: PathPattern | undefined;\n\tlet matched = \"\";\n\tfor (const pattern of mapping.patterns) {\n\t\tif (pattern.suffix === null) {\n\t\t\tif (pattern.prefix === specifier) {\n\t\t\t\tbest = pattern;\n\t\t\t\tmatched = \"\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (\n\t\t\tspecifier.length >= pattern.prefix.length + pattern.suffix.length &&\n\t\t\tspecifier.startsWith(pattern.prefix) &&\n\t\t\tspecifier.endsWith(pattern.suffix) &&\n\t\t\t(best === undefined || pattern.prefix.length > best.prefix.length)\n\t\t) {\n\t\t\tbest = pattern;\n\t\t\tmatched = specifier.slice(\n\t\t\t\tpattern.prefix.length,\n\t\t\t\tspecifier.length - pattern.suffix.length,\n\t\t\t);\n\t\t}\n\t}\n\tif (best === undefined) {\n\t\treturn [];\n\t}\n\treturn best.targets.map((target) =>\n\t\tresolve(mapping.base, target.replace(\"*\", matched)),\n\t);\n}\n","import { statSync } from \"node:fs\";\nimport { type ResolveHookSync, registerHooks } from \"node:module\";\nimport { dirname, extname, join, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport {\n\tfindTsconfig,\n\tloadPathMapping,\n\tmapSpecifier,\n\ttype PathMapping,\n} from \"./tsconfig.js\";\n\n/** The TypeScript source a JavaScript extension in an import stands for. */\nconst SOURCE_EXTENSION: Readonly<Record<string, string>> = {\n\t\".js\": \".ts\",\n\t\".mjs\": \".mts\",\n\t\".cjs\": \".cts\",\n};\n\nconst APPENDED_EXTENSIONS = [\".ts\", \".mts\", \".cts\", \".js\", \".mjs\", \".cjs\"];\nconst INDEX_FILES = [\"index.ts\", \"index.mts\", \"index.js\", \"index.mjs\"];\n\nfunction isFile(path: string): boolean {\n\treturn statSync(path, { throwIfNoEntry: false })?.isFile() === true;\n}\n\n/**\n * The files an import of `path` can mean, in the order tried: the path\n * itself, the `.ts` behind a `.js` name (how TypeScript projects with\n * `module: nodenext` write imports), then an added extension and a folder's\n * index file for an extensionless import.\n */\nexport function importCandidates(path: string): string[] {\n\tconst extension = extname(path);\n\tconst source = SOURCE_EXTENSION[extension];\n\tif (source !== undefined) {\n\t\treturn [path, `${path.slice(0, -extension.length)}${source}`];\n\t}\n\treturn [\n\t\tpath,\n\t\t...APPENDED_EXTENSIONS.map((appended) => `${path}${appended}`),\n\t\t...INDEX_FILES.map((index) => join(path, index)),\n\t];\n}\n\n// Keyed by the importing file's folder. `null` is a folder without a\n// tsconfig, or with one that has no `paths`.\nconst mappings = new Map<string, PathMapping | null>();\n\nfunction pathMappingFor(directory: string): PathMapping | null {\n\tlet mapping = mappings.get(directory);\n\tif (mapping === undefined) {\n\t\tconst tsconfig = findTsconfig(directory);\n\t\tmapping = tsconfig === null ? null : loadPathMapping(tsconfig);\n\t\tmappings.set(directory, mapping);\n\t}\n\treturn mapping;\n}\n\n/**\n * The file an import in `importer` means when Node's own resolution found\n * nothing, or null. Relative imports get the candidates of\n * {@link importCandidates}; any other specifier goes through the `paths` of\n * the nearest `tsconfig.json`.\n */\nexport function resolveAppImport(\n\tspecifier: string,\n\timporter: string,\n): string | null {\n\tconst directory = dirname(importer);\n\tlet targets: string[];\n\tif (specifier.startsWith(\"./\") || specifier.startsWith(\"../\")) {\n\t\ttargets = [resolve(directory, specifier)];\n\t} else if (specifier.startsWith(\"node:\")) {\n\t\treturn null;\n\t} else {\n\t\tconst mapping = pathMappingFor(directory);\n\t\ttargets = mapping === null ? [] : mapSpecifier(specifier, mapping);\n\t}\n\tfor (const target of targets) {\n\t\tconst found = importCandidates(target).find(isFile);\n\t\tif (found !== undefined) {\n\t\t\treturn found;\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * The file `server-only` resolves to, next to the bundled loader: each\n * bin's build writes an empty `dist/server-only.cjs` (the\n * `server-only-stub` plugin in its `tsdown.config.ts`). React's marker\n * package throws at import outside the `react-server` condition, and an\n * app's memory file may import it (Next.js's convention for server code).\n * The bins are server code, so it loads as nothing instead (decisions 81\n * and 97). A real file, because Node 22.18 skips resolve hooks for\n * `require()` in CommonJS loaded by `import` once any load hook is\n * registered, and `require()` cannot load a `data:` URL.\n */\nexport const SERVER_ONLY_FILE = \"server-only.cjs\";\n\n/**\n * The resolve hook. `server-only`, the exact bare specifier, maps to\n * {@link SERVER_ONLY_FILE} before Node resolves it, from any importer, so\n * an installed copy is not loaded either. Everything else asks Node first\n * and looks further only when Node fails, for an importer that is a file\n * outside `node_modules`.\n */\nexport const resolveHook: ResolveHookSync = (\n\tspecifier,\n\tcontext,\n\tnextResolve,\n) => {\n\tif (specifier === \"server-only\") {\n\t\tconst url = new URL(SERVER_ONLY_FILE, import.meta.url).href;\n\t\treturn { url, shortCircuit: true };\n\t}\n\ttry {\n\t\treturn nextResolve(specifier, context);\n\t} catch (error) {\n\t\tconst parent = context.parentURL;\n\t\tif (parent === undefined || !parent.startsWith(\"file:\")) {\n\t\t\tthrow error;\n\t\t}\n\t\tconst importer = fileURLToPath(parent);\n\t\tif (importer.split(/[\\\\/]/).includes(\"node_modules\")) {\n\t\t\tthrow error;\n\t\t}\n\t\tconst found = resolveAppImport(specifier, importer);\n\t\tif (found === null) {\n\t\t\tthrow error;\n\t\t}\n\t\treturn nextResolve(pathToFileURL(found).href, context);\n\t}\n};\n\nlet registered = false;\n\n/**\n * Teach this process the imports a TypeScript app writes that Node's type\n * stripping does not resolve: extensionless and `.js`-for-`.ts` relative\n * imports, and tsconfig `paths`; and load `server-only` as an empty module.\n *\n * `module.registerHooks` installs a synchronous resolve hook on the current\n * thread, for `import` and `require` alike (`module.register`, the\n * asynchronous one, is deprecated from Node 26). Apart from `server-only`,\n * the resolve hook asks Node first and only looks further when Node fails,\n * so anything Node resolves, every other package included, is untouched.\n * Registering twice does nothing.\n */\nexport function registerAppResolver(): void {\n\tif (registered) {\n\t\treturn;\n\t}\n\tregistered = true;\n\tregisterHooks({ resolve: resolveHook });\n}\n","import { parseArgs } from \"node:util\";\n\n/** What the bin was asked to do. */\nexport type CliArgs =\n\t| { readonly command: \"help\" }\n\t| { readonly command: \"version\" }\n\t| {\n\t\t\treadonly command: \"serve\";\n\t\t\treadonly scope: ServeScope;\n\t\t\treadonly project: string | undefined;\n\t\t\treadonly config: string | undefined;\n\t\t\treadonly envFile: string | undefined;\n\t\t\treadonly allowForget: boolean;\n\t\t\treadonly readOnly: boolean;\n\t };\n\n/** The scope from the flags. `namespace` may come from the memory file. */\nexport interface ServeScope {\n\treadonly namespace?: string;\n\treadonly entityId: string;\n\treadonly agentId?: string;\n\treadonly sessionId?: string;\n}\n\n/** A usage error: bad flags. The bin prints it with the usage and exits 2. */\nexport class UsageError extends Error {\n\toverride readonly name = \"UsageError\";\n}\n\nexport const USAGE: string = `Usage: mnemocyte-mcp --entity-id <id> [options]\n\nServes Mnemocyte memory over MCP on stdio, for one scope fixed here.\n\nScope:\n --entity-id <id> The user or entity whose memories the tools use. Required.\n --namespace <name> Defaults to the memory file's createMemory({ namespace }).\n --agent-id <id> Narrow the scope to one agent.\n --session-id <id> Narrow the scope to one session.\n\nMemory file:\n --project <dir> The app's folder. --config, --env-file and the lookup\n are relative to it. Default: the working directory.\n --config <file> The app's memory file. Default: the first of memory.ts,\n memory.mts, memory.js, memory.mjs in ., lib, src, src/lib.\n --env-file <file> Load this file into the environment first. Default:\n .env.local, then .env, in the app's folder, each when\n it exists (no .env.local when NODE_ENV is test).\n\nTools:\n --allow-forget Also list forgetMemory, which deletes for good.\n --read-only List searchMemories only.\n\n -h, --help Show this help.\n -v, --version Show the version.\n`;\n\nconst SCOPE_FLAGS = [\n\t[\"namespace\", \"namespace\"],\n\t[\"entity-id\", \"entityId\"],\n\t[\"agent-id\", \"agentId\"],\n\t[\"session-id\", \"sessionId\"],\n] as const;\n\nfunction nonEmpty(flag: string, value: string | undefined): string | undefined {\n\tif (value !== undefined && value.trim() === \"\") {\n\t\tthrow new UsageError(`--${flag} cannot be empty.`);\n\t}\n\treturn value;\n}\n\n/**\n * Parse the bin's arguments.\n *\n * @throws {UsageError} For an unknown flag, a positional argument, a missing\n * or empty `--entity-id`, an empty value, or `--read-only` with\n * `--allow-forget`.\n */\nexport function parseCliArgs(argv: readonly string[]): CliArgs {\n\tlet parsed: ReturnType<typeof parse>;\n\ttry {\n\t\tparsed = parse(argv);\n\t} catch (error) {\n\t\tthrow new UsageError(\n\t\t\terror instanceof Error ? error.message : String(error),\n\t\t);\n\t}\n\tconst { values, positionals } = parsed;\n\tif (values.help === true) {\n\t\treturn { command: \"help\" };\n\t}\n\tif (values.version === true) {\n\t\treturn { command: \"version\" };\n\t}\n\tif (positionals.length > 0) {\n\t\tthrow new UsageError(`Unexpected argument ${positionals[0]}.`);\n\t}\n\n\tconst scope: Record<string, string> = {};\n\tfor (const [flag, field] of SCOPE_FLAGS) {\n\t\tconst value = nonEmpty(flag, values[flag]);\n\t\tif (value !== undefined) {\n\t\t\tscope[field] = value;\n\t\t}\n\t}\n\tconst entityId = scope.entityId;\n\tif (entityId === undefined) {\n\t\tthrow new UsageError(\n\t\t\t\"--entity-id is required: the server serves one entity's memories.\",\n\t\t);\n\t}\n\tconst allowForget = values[\"allow-forget\"] === true;\n\tconst readOnly = values[\"read-only\"] === true;\n\tif (allowForget && readOnly) {\n\t\tthrow new UsageError(\"--read-only and --allow-forget cannot be combined.\");\n\t}\n\treturn {\n\t\tcommand: \"serve\",\n\t\tscope: { ...scope, entityId },\n\t\tproject: nonEmpty(\"project\", values.project),\n\t\tconfig: nonEmpty(\"config\", values.config),\n\t\tenvFile: nonEmpty(\"env-file\", values[\"env-file\"]),\n\t\tallowForget,\n\t\treadOnly,\n\t};\n}\n\nfunction parse(argv: readonly string[]) {\n\treturn parseArgs({\n\t\targs: [...argv],\n\t\tallowPositionals: true,\n\t\tstrict: true,\n\t\toptions: {\n\t\t\tnamespace: { type: \"string\" },\n\t\t\t\"entity-id\": { type: \"string\" },\n\t\t\t\"agent-id\": { type: \"string\" },\n\t\t\t\"session-id\": { type: \"string\" },\n\t\t\tproject: { type: \"string\" },\n\t\t\tconfig: { type: \"string\" },\n\t\t\t\"env-file\": { type: \"string\" },\n\t\t\t\"allow-forget\": { type: \"boolean\" },\n\t\t\t\"read-only\": { type: \"boolean\" },\n\t\t\thelp: { type: \"boolean\", short: \"h\" },\n\t\t\tversion: { type: \"boolean\", short: \"v\" },\n\t\t},\n\t});\n}\n","import { statSync } from \"node:fs\";\nimport { relative, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { findMemoryFile, registerAppResolver } from \"@mnemocyte/loader\";\nimport type { MemoryClient } from \"mnemocyte\";\nimport { UsageError } from \"./args.js\";\n\n// The lookup and the resolve hook come from @mnemocyte/loader, the private\n// package the `mnemocyte` CLI bundles too, so both bins find and load the\n// same file. Reading the client uses only the public API: the CLI's symbol\n// for the store and embedder is not needed to call `for`.\n\n/** An unbound client, as `createMemory` returns it. */\nexport type UnboundMemoryClient = MemoryClient<boolean>;\n\nfunction isFile(path: string): boolean {\n\treturn statSync(path, { throwIfNoEntry: false })?.isFile() === true;\n}\n\n/**\n * The memory file to load: `--config` when given, which must exist,\n * otherwise the first one found.\n *\n * @throws {UsageError} When `--config` names no file or no file is found.\n */\nexport function locateMemoryFile(\n\tcwd: string,\n\tconfig: string | undefined,\n): string {\n\tif (config !== undefined) {\n\t\tconst file = resolve(cwd, config);\n\t\tif (!isFile(file)) {\n\t\t\tthrow new UsageError(`--config: ${config} is not a file.`);\n\t\t}\n\t\treturn file;\n\t}\n\tconst found = findMemoryFile(cwd);\n\tif (found === null) {\n\t\tthrow new UsageError(\n\t\t\t`No memory file found in ${cwd}. Pass --config <file> with the file that exports createMemory()'s client.`,\n\t\t);\n\t}\n\treturn found;\n}\n\nfunction errorCode(error: unknown): string | undefined {\n\tif (typeof error !== \"object\" || error === null || !(\"code\" in error)) {\n\t\treturn undefined;\n\t}\n\treturn typeof error.code === \"string\" ? error.code : undefined;\n}\n\nfunction firstLine(error: unknown): string {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn message.split(\"\\n\")[0]?.trim() ?? \"\";\n}\n\nconst BUILD_HINT = \"Build the file and pass --config <built .js>.\";\n\nfunction loadError(name: string, error: unknown): UsageError {\n\tconst detail = firstLine(error);\n\tswitch (errorCode(error)) {\n\t\tcase \"ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX\":\n\t\t\treturn new UsageError(\n\t\t\t\t`${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}`,\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\tcase \"ERR_UNKNOWN_FILE_EXTENSION\":\n\t\t\treturn new UsageError(\n\t\t\t\t`Node cannot load ${name} (${detail}). .tsx files are not supported, and neither is a Node started with type stripping turned off. ${BUILD_HINT}`,\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\tcase \"ERR_MODULE_NOT_FOUND\":\n\t\t\treturn new UsageError(\n\t\t\t\t`${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>.`,\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\tdefault:\n\t\t\treturn new UsageError(`Loading ${name} failed: ${detail}`, {\n\t\t\t\tcause: error,\n\t\t\t});\n\t}\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction isUnboundClient(value: unknown): value is UnboundMemoryClient {\n\treturn (\n\t\tisRecord(value) &&\n\t\ttypeof value.for === \"function\" &&\n\t\ttypeof value.search === \"function\" &&\n\t\ttypeof value.add === \"function\" &&\n\t\ttypeof value.delete === \"function\"\n\t);\n}\n\nfunction isBoundClient(value: unknown): boolean {\n\treturn (\n\t\tisRecord(value) &&\n\t\tisRecord(value.scope) &&\n\t\ttypeof value.search === \"function\" &&\n\t\t!(\"for\" in value)\n\t);\n}\n\n/**\n * Import the app's memory file and return its client: the `memory` export,\n * else the default export's `memory`, else the default export, as the\n * `mnemocyte` CLI reads it. A `.ts` file loads through Node's type stripping\n * with the shared resolve hook (`@mnemocyte/loader`) for extensionless,\n * `.js`-for-`.ts` and tsconfig `paths` imports.\n *\n * @throws {UsageError} When the file does not load, or exports a bound\n * client or no client.\n */\nexport async function loadMemoryClient(\n\tfile: string,\n\tcwd: string,\n): Promise<UnboundMemoryClient> {\n\tconst name = relative(cwd, file).replaceAll(\"\\\\\", \"/\") || file;\n\tregisterAppResolver();\n\tlet exports: Record<string, unknown>;\n\ttry {\n\t\texports = (await import(pathToFileURL(file).href)) as Record<\n\t\t\tstring,\n\t\t\tunknown\n\t\t>;\n\t} catch (error) {\n\t\tthrow loadError(name, error);\n\t}\n\n\tconst fallback = exports.default;\n\tconst candidates = [\n\t\texports.memory,\n\t\tisRecord(fallback) && \"memory\" in fallback ? fallback.memory : undefined,\n\t\tfallback,\n\t].filter((candidate) => candidate !== undefined);\n\tconst client = candidates.find(isUnboundClient);\n\tif (client !== undefined) {\n\t\treturn client;\n\t}\n\tif (candidates.some(isBoundClient)) {\n\t\tthrow new UsageError(\n\t\t\t`${name} exports a bound client from memory.for(...). Export the client from createMemory() itself; mnemocyte-mcp binds it to the scope in its flags.`,\n\t\t);\n\t}\n\tthrow new UsageError(\n\t\t`${name} does not export a memory client. Export the result of createMemory() as \"memory\": export const memory = createMemory({ ... });`,\n\t);\n}\n","import { statSync } from \"node:fs\";\nimport { relative, resolve } from \"node:path\";\nimport { loadEnvFiles } from \"@mnemocyte/loader\";\nimport type { McpServer } from \"@modelcontextprotocol/server\";\nimport type { BoundMemoryClient } from \"mnemocyte\";\nimport { isMnemocyteError } from \"mnemocyte\";\nimport { createMemoryMcpServer, toolNames } from \"../server.js\";\nimport { parseCliArgs, type ServeScope, USAGE, UsageError } from \"./args.js\";\nimport { loadMemoryClient, locateMemoryFile } from \"./memory-file.js\";\n\n/** Where the bin reads and writes. Tests pass a recording one. */\nexport interface CliIo {\n\treadonly cwd: string;\n\t/** Standard output: help and version only. */\n\twrite(text: string): void;\n\t/** Standard error: errors and the startup line. */\n\terror(text: string): void;\n}\n\n/** What the bin does after {@link prepare}. */\nexport type Prepared =\n\t| { readonly kind: \"exit\"; readonly code: number }\n\t| {\n\t\t\treadonly kind: \"serve\";\n\t\t\t/** A new server for each connection. */\n\t\t\treadonly createServer: () => McpServer;\n\t };\n\n/** Exit code for bad flags or a memory file that cannot be used. */\nexport const EXIT_USAGE = 2;\n\n/**\n * `--env-file` when given, else `.env.local` and then `.env` in the app's\n * folder, each when it exists (`.env.local` not when `NODE_ENV` is `test`),\n * as the `mnemocyte` CLI does. A variable that is already set is kept.\n *\n * @returns The files that were read, for the startup line.\n */\nexport function loadEnvironment(\n\tcwd: string,\n\tenvFile: string | undefined,\n): string[] {\n\tif (envFile === undefined) {\n\t\treturn loadEnvFiles({ directory: cwd });\n\t}\n\ttry {\n\t\tprocess.loadEnvFile(resolve(cwd, envFile));\n\t} catch (error) {\n\t\tthrow new UsageError(`--env-file: could not read ${envFile}.`, {\n\t\t\tcause: error,\n\t\t});\n\t}\n\treturn [envFile];\n}\n\n/**\n * The app's folder: `--project` resolved against the working directory, or\n * the working directory itself. MCP clients do not all say which folder\n * they start a server in.\n *\n * @throws {UsageError} When `--project` is not a folder.\n */\nexport function projectFolder(\n\tcwd: string,\n\tproject: string | undefined,\n): string {\n\tif (project === undefined) {\n\t\treturn cwd;\n\t}\n\tconst folder = resolve(cwd, project);\n\tif (statSync(folder, { throwIfNoEntry: false })?.isDirectory() !== true) {\n\t\tthrow new UsageError(`--project: ${project} is not a folder.`);\n\t}\n\treturn folder;\n}\n\nfunction describeError(error: unknown): string {\n\treturn `mnemocyte-mcp: ${error instanceof Error ? error.message : String(error)}\\n`;\n}\n\nfunction describeScope(scope: Readonly<Record<string, unknown>>): string {\n\treturn Object.entries(scope)\n\t\t.filter(([, value]) => value !== undefined)\n\t\t.map(([field, value]) => `${field}=${String(value)}`)\n\t\t.join(\" \");\n}\n\n/**\n * Parse the arguments, load the memory file and bind its client to the\n * scope in the flags. Resolves with what to do next; never rejects. Errors\n * are written to `io.error`: bad flags and an unusable memory file exit 2,\n * anything else 1.\n */\nexport async function prepare(\n\targv: readonly string[],\n\tio: CliIo,\n\tversion: string,\n): Promise<Prepared> {\n\tlet args: ReturnType<typeof parseCliArgs>;\n\ttry {\n\t\targs = parseCliArgs(argv);\n\t} catch (error) {\n\t\tio.error(`${describeError(error)}\\n${USAGE}`);\n\t\treturn { kind: \"exit\", code: EXIT_USAGE };\n\t}\n\tif (args.command === \"help\") {\n\t\tio.write(USAGE);\n\t\treturn { kind: \"exit\", code: 0 };\n\t}\n\tif (args.command === \"version\") {\n\t\tio.write(`${version}\\n`);\n\t\treturn { kind: \"exit\", code: 0 };\n\t}\n\n\ttry {\n\t\tconst project = projectFolder(io.cwd, args.project);\n\t\tconst envFiles = loadEnvironment(project, args.envFile);\n\t\tconst file = locateMemoryFile(project, args.config);\n\t\tconst client = await loadMemoryClient(file, project);\n\t\tconst memory = bind(client, args.scope);\n\t\tconst { allowForget, readOnly } = args;\n\t\t// Built once here so a bad option fails at startup, not on connect.\n\t\tcreateMemoryMcpServer({ memory, allowForget, readOnly });\n\t\tconst label = relative(project, file).replaceAll(\"\\\\\", \"/\") || file;\n\t\tio.error(\n\t\t\t`mnemocyte-mcp ${version}: ${label}, scope ${describeScope(memory.scope)}, tools ${toolNames({ allowForget, readOnly }).join(\", \")}, env ${envFiles.length === 0 ? \"none\" : envFiles.join(\", \")}\\n`,\n\t\t);\n\t\treturn {\n\t\t\tkind: \"serve\",\n\t\t\tcreateServer: () =>\n\t\t\t\tcreateMemoryMcpServer({ memory, allowForget, readOnly }),\n\t\t};\n\t} catch (error) {\n\t\tio.error(describeError(error));\n\t\treturn {\n\t\t\tkind: \"exit\",\n\t\t\tcode:\n\t\t\t\terror instanceof UsageError ||\n\t\t\t\t(isMnemocyteError(error) &&\n\t\t\t\t\t(error.code === \"VALIDATION\" || error.code === \"CONFIG\"))\n\t\t\t\t\t? EXIT_USAGE\n\t\t\t\t\t: 1,\n\t\t};\n\t}\n}\n\nfunction bind(\n\tclient: { for(scope: ServeScope): BoundMemoryClient },\n\tscope: ServeScope,\n): BoundMemoryClient {\n\ttry {\n\t\treturn client.for(scope);\n\t} catch (error) {\n\t\tif (isMnemocyteError(error) && error.code === \"VALIDATION\") {\n\t\t\tconst hint =\n\t\t\t\tscope.namespace === undefined\n\t\t\t\t\t? \" Pass --namespace, or set namespace in the memory file's createMemory().\"\n\t\t\t\t\t: \"\";\n\t\t\tthrow new UsageError(\n\t\t\t\t`The scope in the flags is not valid: ${error.message}${hint}`,\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n}\n","#!/usr/bin/env node\n// The `mnemocyte-mcp` bin. Not an export of the package: `package.json`\n// lists it under `bin` only.\nimport { serveStdio } from \"@modelcontextprotocol/server/stdio\";\nimport { redirectConsoleToStderr } from \"./cli/console.js\";\nimport { type CliIo, prepare } from \"./cli/main.js\";\nimport { SERVER_INFO } from \"./server.js\";\n\nconst io: CliIo = {\n\tcwd: process.cwd(),\n\twrite: (text) => process.stdout.write(text),\n\terror: (text) => process.stderr.write(text),\n};\n\n// Each stream's empty write is queued behind the output, so its callback\n// runs once that is flushed (pipes are asynchronous on Windows).\nfunction exit(code: number): void {\n\tprocess.stdout.write(\"\", () => {\n\t\tprocess.stderr.write(\"\", () => process.exit(code));\n\t});\n}\n\n// Before the memory file is imported, so nothing it logs reaches stdout.\nredirectConsoleToStderr();\n\n// No top-level await, like the rest of dist/.\nvoid prepare(process.argv.slice(2), io, SERVER_INFO.version).then(\n\t(prepared) => {\n\t\tif (prepared.kind === \"exit\") {\n\t\t\texit(prepared.code);\n\t\t\treturn;\n\t\t}\n\t\tserveStdio(prepared.createServer, {\n\t\t\tonerror: (error) => io.error(`mnemocyte-mcp: ${error.message}\\n`),\n\t\t});\n\t\t// The client ends the session by closing stdin. The app's database\n\t\t// client, which the bin does not own and cannot close, would keep the\n\t\t// process alive, so it exits here.\n\t\tlet ended = false;\n\t\tconst end = () => {\n\t\t\tif (!ended) {\n\t\t\t\tended = true;\n\t\t\t\texit(0);\n\t\t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, MemoryKind } from "mnemocyte";
3
+ /** Input of the `searchMemories` tool. */
4
+ interface SearchMemoriesInput {
5
+ query: string;
6
+ limit?: number;
7
+ kinds?: MemoryKind[];
8
+ }
9
+ /** A memory as the `searchMemories` tool returns it. */
10
+ interface FoundMemory {
11
+ id: string;
12
+ content: string;
13
+ kind: MemoryKind;
14
+ importance: ImportanceLevel;
15
+ tags: string[];
16
+ /** ISO 8601 creation time. */
17
+ createdAt: string;
18
+ /** Relevance in `[0, 1]`, rounded to three decimals. */
19
+ score: number;
20
+ }
21
+ /** Input of the `saveMemory` tool. */
22
+ interface SaveMemoryInput {
23
+ content: string;
24
+ kind?: MemoryKind;
25
+ importance?: ImportanceLevel;
26
+ }
27
+ /** Input of the `forgetMemory` tool. */
28
+ interface ForgetMemoryInput {
29
+ id: string;
30
+ }
31
+ /** The names of the tools the server can list. */
32
+ type MemoryToolName = "searchMemories" | "saveMemory" | "forgetMemory";
33
+ /** Options for {@link createMemoryMcpServer}. */
34
+ interface MemoryMcpServerOptions {
35
+ /**
36
+ * A client bound to one scope, from `memory.for(scope)`. Every tool reads
37
+ * and writes that scope only; no tool input can name another.
38
+ */
39
+ readonly memory: BoundMemoryClient;
40
+ /**
41
+ * List `forgetMemory`, which deletes a memory for good.
42
+ * @defaultValue `false`
43
+ */
44
+ readonly allowForget?: boolean;
45
+ /**
46
+ * List `searchMemories` only. Cannot be combined with `allowForget`.
47
+ * @defaultValue `false`
48
+ */
49
+ readonly readOnly?: boolean;
50
+ }
51
+ /**
52
+ * An MCP server with Mnemocyte's memory tools over one bound client:
53
+ * `searchMemories` and `saveMemory`, plus `forgetMemory` with
54
+ * `allowForget`. The scope comes from `memory.for(scope)` on your side; no
55
+ * tool takes a scope field, so a client or a prompt injection cannot reach
56
+ * another scope's memories.
57
+ *
58
+ * Connect it to a transport yourself, or use the `mnemocyte-mcp` bin for
59
+ * stdio. Create one per connection: an `McpServer` serves one transport.
60
+ *
61
+ * @throws {TypeError} When `memory` is not a bound client, an option is
62
+ * unknown or not a boolean, or `readOnly` and `allowForget` are both set.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * import { createMemoryMcpServer } from "@mnemocyte/mcp";
67
+ * import { memory } from "./memory.ts";
68
+ *
69
+ * const server = createMemoryMcpServer({
70
+ * memory: memory.for({ entityId: user.id }),
71
+ * });
72
+ * ```
73
+ */
74
+ export declare function createMemoryMcpServer(options: MemoryMcpServerOptions): McpServer;
75
+ export type { ForgetMemoryInput, FoundMemory, MemoryMcpServerOptions, MemoryToolName, SaveMemoryInput, SearchMemoriesInput };
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ export { n as createMemoryMcpServer } from "./server-Bwa4mQjX.mjs";
@@ -0,0 +1,424 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { McpServer } from "@modelcontextprotocol/server";
3
+ import { isMnemocyteError } from "mnemocyte";
4
+ // src/tools.ts
5
+ /** The value that tells the app's memories from the ones a model saved. */
6
+ const SAVE_SOURCE = "saveMemory";
7
+ const DEFAULT_SEARCH_LIMIT = 5;
8
+ const MAX_SEARCH_LIMIT = 20;
9
+ const MEMORY_KINDS = [
10
+ "fact",
11
+ "preference",
12
+ "instruction",
13
+ "backstory",
14
+ "episode",
15
+ "session"
16
+ ];
17
+ const IMPORTANCE_LEVELS = [
18
+ "low",
19
+ "normal",
20
+ "high",
21
+ "critical"
22
+ ];
23
+ const SCOPE_FIELDS = /* @__PURE__ */ new Set([
24
+ "scope",
25
+ "namespace",
26
+ "entityId",
27
+ "agentId",
28
+ "sessionId",
29
+ "allNamespaces"
30
+ ]);
31
+ const KIND_DESCRIPTION = "fact: a stable statement about the user; preference: how they like things done; instruction: a standing request for how to respond; backstory: long-lived background; episode: something that happened; session: context for this conversation only.";
32
+ function isRecord$1(value) {
33
+ return typeof value === "object" && value !== null && !Array.isArray(value);
34
+ }
35
+ function invalid(message) {
36
+ return { issues: [{ message }] };
37
+ }
38
+ function checkFields(value, allowed) {
39
+ if (!isRecord$1(value)) return "Input must be an object.";
40
+ for (const field of Object.keys(value)) {
41
+ if (allowed.includes(field)) continue;
42
+ return SCOPE_FIELDS.has(field) ? `${field} is not accepted: the memory scope is fixed by the server.` : `Unknown field ${field}.`;
43
+ }
44
+ return value;
45
+ }
46
+ function isNonEmptyString(value) {
47
+ return typeof value === "string" && value.trim().length > 0;
48
+ }
49
+ function isOneOf(value, options) {
50
+ return typeof value === "string" && options.includes(value);
51
+ }
52
+ /** @internal Exported for tests. */
53
+ function validateSearchInput(value) {
54
+ const input = checkFields(value, [
55
+ "query",
56
+ "limit",
57
+ "kinds"
58
+ ]);
59
+ if (typeof input === "string") return invalid(input);
60
+ const { query, limit, kinds } = input;
61
+ if (!isNonEmptyString(query)) return invalid("query must be a non-empty string.");
62
+ if (limit !== void 0 && (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > MAX_SEARCH_LIMIT)) return invalid(`limit must be an integer from 1 to ${MAX_SEARCH_LIMIT}.`);
63
+ if (kinds !== void 0 && (!Array.isArray(kinds) || !kinds.every((kind) => isOneOf(kind, MEMORY_KINDS)))) return invalid(`kinds must be an array of ${MEMORY_KINDS.join(", ")}.`);
64
+ return { value: {
65
+ query,
66
+ ...limit === void 0 ? {} : { limit },
67
+ ...kinds === void 0 ? {} : { kinds: [...kinds] }
68
+ } };
69
+ }
70
+ /** @internal Exported for tests. */
71
+ function validateSaveInput(value) {
72
+ const input = checkFields(value, [
73
+ "content",
74
+ "kind",
75
+ "importance"
76
+ ]);
77
+ if (typeof input === "string") return invalid(input);
78
+ const { content, kind, importance } = input;
79
+ if (!isNonEmptyString(content)) return invalid("content must be a non-empty string.");
80
+ if (kind !== void 0 && !isOneOf(kind, MEMORY_KINDS)) return invalid(`kind must be one of ${MEMORY_KINDS.join(", ")}.`);
81
+ if (importance !== void 0 && !isOneOf(importance, IMPORTANCE_LEVELS)) return invalid(`importance must be one of ${IMPORTANCE_LEVELS.join(", ")}.`);
82
+ return { value: {
83
+ content,
84
+ ...kind === void 0 ? {} : { kind },
85
+ ...importance === void 0 ? {} : { importance }
86
+ } };
87
+ }
88
+ /** @internal Exported for tests. */
89
+ function validateForgetInput(value) {
90
+ const input = checkFields(value, ["id"]);
91
+ if (typeof input === "string") return invalid(input);
92
+ if (!isNonEmptyString(input.id)) return invalid("id must be a non-empty string.");
93
+ return { value: { id: input.id } };
94
+ }
95
+ /**
96
+ * A Standard Schema over a fixed JSON Schema and a validator of our own, so
97
+ * the error messages match `memoryTools` and no schema library is needed.
98
+ */
99
+ function schema(json, validate) {
100
+ return { "~standard": {
101
+ version: 1,
102
+ vendor: "mnemocyte",
103
+ validate,
104
+ jsonSchema: {
105
+ input: () => structuredClone(json),
106
+ output: () => structuredClone(json)
107
+ }
108
+ } };
109
+ }
110
+ /** An output schema: the server builds the value, so it is not checked again. */
111
+ function outputSchema(json) {
112
+ return schema(json, (value) => ({ value }));
113
+ }
114
+ const SEARCH_INPUT = {
115
+ type: "object",
116
+ properties: {
117
+ query: {
118
+ type: "string",
119
+ description: "What to look for, in natural language."
120
+ },
121
+ limit: {
122
+ type: "integer",
123
+ minimum: 1,
124
+ maximum: MAX_SEARCH_LIMIT,
125
+ description: `Most memories to return. Defaults to ${DEFAULT_SEARCH_LIMIT}.`
126
+ },
127
+ kinds: {
128
+ type: "array",
129
+ items: {
130
+ type: "string",
131
+ enum: [...MEMORY_KINDS]
132
+ },
133
+ description: `Only memories of these kinds. ${KIND_DESCRIPTION}`
134
+ }
135
+ },
136
+ required: ["query"],
137
+ additionalProperties: false
138
+ };
139
+ const SEARCH_OUTPUT = {
140
+ type: "object",
141
+ properties: { memories: {
142
+ type: "array",
143
+ description: "Best match first.",
144
+ items: {
145
+ type: "object",
146
+ properties: {
147
+ id: { type: "string" },
148
+ content: { type: "string" },
149
+ kind: {
150
+ type: "string",
151
+ enum: [...MEMORY_KINDS]
152
+ },
153
+ importance: {
154
+ type: "string",
155
+ enum: [...IMPORTANCE_LEVELS]
156
+ },
157
+ tags: {
158
+ type: "array",
159
+ items: { type: "string" }
160
+ },
161
+ createdAt: {
162
+ type: "string",
163
+ format: "date-time"
164
+ },
165
+ score: {
166
+ type: "number",
167
+ minimum: 0,
168
+ maximum: 1
169
+ }
170
+ },
171
+ required: [
172
+ "id",
173
+ "content",
174
+ "kind",
175
+ "importance",
176
+ "tags",
177
+ "createdAt",
178
+ "score"
179
+ ],
180
+ additionalProperties: false
181
+ }
182
+ } },
183
+ required: ["memories"],
184
+ additionalProperties: false
185
+ };
186
+ const SAVE_INPUT = {
187
+ type: "object",
188
+ properties: {
189
+ content: {
190
+ type: "string",
191
+ description: "The memory as a short standalone sentence, for example: Prefers metric units."
192
+ },
193
+ kind: {
194
+ type: "string",
195
+ enum: [...MEMORY_KINDS],
196
+ description: `Defaults to fact. ${KIND_DESCRIPTION}`
197
+ },
198
+ importance: {
199
+ type: "string",
200
+ enum: [...IMPORTANCE_LEVELS],
201
+ description: "Defaults to normal."
202
+ }
203
+ },
204
+ required: ["content"],
205
+ additionalProperties: false
206
+ };
207
+ const SAVE_OUTPUT = {
208
+ type: "object",
209
+ properties: { id: {
210
+ type: "string",
211
+ description: "Id of the new memory."
212
+ } },
213
+ required: ["id"],
214
+ additionalProperties: false
215
+ };
216
+ const FORGET_INPUT = {
217
+ type: "object",
218
+ properties: { id: {
219
+ type: "string",
220
+ description: "Id of the memory, from searchMemories."
221
+ } },
222
+ required: ["id"],
223
+ additionalProperties: false
224
+ };
225
+ const FORGET_OUTPUT = {
226
+ type: "object",
227
+ properties: { forgotten: {
228
+ type: "boolean",
229
+ description: "false when no memory with that id is visible."
230
+ } },
231
+ required: ["forgotten"],
232
+ additionalProperties: false
233
+ };
234
+ function result(value) {
235
+ return {
236
+ content: [{
237
+ type: "text",
238
+ text: JSON.stringify(value)
239
+ }],
240
+ structuredContent: value
241
+ };
242
+ }
243
+ function toFoundMemory(memory) {
244
+ return {
245
+ id: memory.id,
246
+ content: memory.content,
247
+ kind: memory.kind,
248
+ importance: memory.importance,
249
+ tags: [...memory.tags],
250
+ createdAt: memory.createdAt.toISOString(),
251
+ score: Math.round(memory.score * 1e3) / 1e3
252
+ };
253
+ }
254
+ /** The search tool over a bound client. */
255
+ function searchTool(memory) {
256
+ return {
257
+ name: "searchMemories",
258
+ title: "Search memories",
259
+ description: "Search long-term memory about the user for facts, preferences and past events relevant to the conversation. Use it before answering anything that depends on what you know about them. Returns the best matches first, each with an id.",
260
+ inputSchema: schema(SEARCH_INPUT, validateSearchInput),
261
+ outputSchema: outputSchema(SEARCH_OUTPUT),
262
+ annotations: {
263
+ readOnlyHint: true,
264
+ openWorldHint: false
265
+ },
266
+ async run(input, signal) {
267
+ return result({ memories: (await memory.search({
268
+ query: input.query,
269
+ limit: input.limit ?? DEFAULT_SEARCH_LIMIT,
270
+ ...input.kinds === void 0 || input.kinds.length === 0 ? {} : { kinds: input.kinds },
271
+ signal
272
+ })).map(toFoundMemory) });
273
+ }
274
+ };
275
+ }
276
+ /** The save tool over a bound client. */
277
+ function saveTool(memory) {
278
+ return {
279
+ name: "saveMemory",
280
+ title: "Save a memory",
281
+ description: "Save one durable fact about the user, such as a preference, a goal or a personal detail they shared, so later conversations can recall it. Save each fact once, as a short standalone sentence. Never save passwords, keys, payment details or other secrets.",
282
+ inputSchema: schema(SAVE_INPUT, validateSaveInput),
283
+ outputSchema: outputSchema(SAVE_OUTPUT),
284
+ annotations: {
285
+ readOnlyHint: false,
286
+ destructiveHint: false,
287
+ idempotentHint: false,
288
+ openWorldHint: false
289
+ },
290
+ async run(input, signal) {
291
+ return result({ id: (await memory.add({
292
+ content: input.content,
293
+ ...input.kind === void 0 ? {} : { kind: input.kind },
294
+ ...input.importance === void 0 ? {} : { importance: input.importance },
295
+ source: SAVE_SOURCE,
296
+ signal
297
+ })).id });
298
+ }
299
+ };
300
+ }
301
+ /** The forget tool over a bound client. */
302
+ function forgetTool(memory) {
303
+ return {
304
+ name: "forgetMemory",
305
+ title: "Forget a memory",
306
+ description: "Delete one memory about the user by its id from searchMemories, for example when they ask you to forget something or a memory is wrong. Duplicates that were merged into it are deleted too. Returns forgotten: false when no memory has that id.",
307
+ inputSchema: schema(FORGET_INPUT, validateForgetInput),
308
+ outputSchema: outputSchema(FORGET_OUTPUT),
309
+ annotations: {
310
+ readOnlyHint: false,
311
+ destructiveHint: true,
312
+ idempotentHint: true,
313
+ openWorldHint: false
314
+ },
315
+ async run(input, signal) {
316
+ try {
317
+ await memory.delete({
318
+ id: input.id,
319
+ dependents: "delete",
320
+ signal
321
+ });
322
+ return result({ forgotten: true });
323
+ } catch (error) {
324
+ if (isMnemocyteError(error) && error.code === "NOT_FOUND") return result({ forgotten: false });
325
+ throw error;
326
+ }
327
+ }
328
+ };
329
+ }
330
+ // src/server.ts
331
+ const OPTION_KEYS = [
332
+ "memory",
333
+ "allowForget",
334
+ "readOnly"
335
+ ];
336
+ /** The package name and version, read from `package.json` once. */
337
+ const SERVER_INFO = readServerInfo();
338
+ function readServerInfo() {
339
+ let manifest;
340
+ try {
341
+ manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
342
+ } catch {
343
+ manifest = void 0;
344
+ }
345
+ return {
346
+ name: "mnemocyte-mcp",
347
+ version: typeof manifest === "object" && manifest !== null && "version" in manifest && typeof manifest.version === "string" ? manifest.version : "unknown"
348
+ };
349
+ }
350
+ function isRecord(value) {
351
+ return typeof value === "object" && value !== null && !Array.isArray(value);
352
+ }
353
+ function isBoundClient(value) {
354
+ return isRecord(value) && isRecord(value.scope) && typeof value.search === "function" && typeof value.add === "function" && typeof value.delete === "function";
355
+ }
356
+ function isOptionalBoolean(value) {
357
+ return value === void 0 || typeof value === "boolean";
358
+ }
359
+ /** The tools a server with these options lists, in order. */
360
+ function toolNames(options) {
361
+ if (options.readOnly === true) return ["searchMemories"];
362
+ return options.allowForget === true ? [
363
+ "searchMemories",
364
+ "saveMemory",
365
+ "forgetMemory"
366
+ ] : ["searchMemories", "saveMemory"];
367
+ }
368
+ function register(server, tool) {
369
+ server.registerTool(tool.name, {
370
+ title: tool.title,
371
+ description: tool.description,
372
+ inputSchema: tool.inputSchema,
373
+ outputSchema: tool.outputSchema,
374
+ annotations: tool.annotations
375
+ }, (input, context) => tool.run(input, context.mcpReq.signal));
376
+ }
377
+ /**
378
+ * An MCP server with Mnemocyte's memory tools over one bound client:
379
+ * `searchMemories` and `saveMemory`, plus `forgetMemory` with
380
+ * `allowForget`. The scope comes from `memory.for(scope)` on your side; no
381
+ * tool takes a scope field, so a client or a prompt injection cannot reach
382
+ * another scope's memories.
383
+ *
384
+ * Connect it to a transport yourself, or use the `mnemocyte-mcp` bin for
385
+ * stdio. Create one per connection: an `McpServer` serves one transport.
386
+ *
387
+ * @throws {TypeError} When `memory` is not a bound client, an option is
388
+ * unknown or not a boolean, or `readOnly` and `allowForget` are both set.
389
+ *
390
+ * @example
391
+ * ```ts
392
+ * import { createMemoryMcpServer } from "@mnemocyte/mcp";
393
+ * import { memory } from "./memory.ts";
394
+ *
395
+ * const server = createMemoryMcpServer({
396
+ * memory: memory.for({ entityId: user.id }),
397
+ * });
398
+ * ```
399
+ */
400
+ function createMemoryMcpServer(options) {
401
+ if (!isRecord(options)) throw new TypeError("createMemoryMcpServer requires an options object.");
402
+ for (const key of Object.keys(options)) if (!OPTION_KEYS.includes(key)) throw new TypeError(`createMemoryMcpServer: unknown option ${key}.`);
403
+ const { memory, allowForget, readOnly } = options;
404
+ if (!isBoundClient(memory)) throw new TypeError("createMemoryMcpServer requires a bound client: pass memory.for(scope), not the client itself.");
405
+ if (!isOptionalBoolean(allowForget) || !isOptionalBoolean(readOnly)) throw new TypeError("createMemoryMcpServer: allowForget and readOnly must be booleans.");
406
+ if (allowForget === true && readOnly === true) throw new TypeError("createMemoryMcpServer: readOnly and allowForget cannot both be set.");
407
+ const server = new McpServer(SERVER_INFO, { capabilities: { tools: {} } });
408
+ for (const name of toolNames({
409
+ allowForget,
410
+ readOnly
411
+ })) switch (name) {
412
+ case "searchMemories":
413
+ register(server, searchTool(memory));
414
+ break;
415
+ case "saveMemory":
416
+ register(server, saveTool(memory));
417
+ break;
418
+ case "forgetMemory": register(server, forgetTool(memory));
419
+ }
420
+ return server;
421
+ }
422
+ export { createMemoryMcpServer as n, toolNames as r, SERVER_INFO as t };
423
+
424
+ //# sourceMappingURL=server-Bwa4mQjX.mjs.map