mixgram 1.3.7 → 2.0.1

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.
Files changed (39) hide show
  1. package/README.md +68 -345
  2. package/bin/mixgram.js +51 -160
  3. package/examples/embedding-demo.js +22 -142
  4. package/package.json +2 -3
  5. package/pnpm-workspace.yaml +2 -2
  6. package/spec/bench-indexing.js +23 -211
  7. package/spec/bench-search.js +26 -212
  8. package/spec/run-tests.js +1 -214
  9. package/spec/scenarios/scenarios.js +277 -607
  10. package/spec/sdd.md +14 -988
  11. package/spec/tdd.md +15 -1232
  12. package/spec/test-large-document.js +20 -91
  13. package/src/config.js +57 -48
  14. package/src/core/documents/documents.js +62 -224
  15. package/src/core/embeddings/embedder.js +14 -54
  16. package/src/core/embeddings/queue.js +33 -106
  17. package/src/core/embeddings/vectorStore.js +30 -111
  18. package/src/core/embeddings/worker-process.js +23 -74
  19. package/src/core/indexing/indexer.js +51 -237
  20. package/src/core/indexing/parser.js +13 -114
  21. package/src/core/indexing/reindex.js +28 -137
  22. package/src/core/search/search.js +64 -158
  23. package/src/db/migrations/001_initial.sql +14 -63
  24. package/src/db/sqlite.js +19 -29
  25. package/src/fs/paths.js +11 -101
  26. package/src/fs/watcher.js +15 -48
  27. package/src/mcp/cli-adapter.js +32 -110
  28. package/src/mcp/server.js +64 -141
  29. package/src/mcp/tool-registry.js +21 -132
  30. package/src/mcp/tools.js +27 -199
  31. package/src/utils/markdown.js +15 -82
  32. package/patches/sharp@0.34.5.patch +0 -13
  33. package/spec/fixtures/realistic-content.js +0 -106
  34. package/spec/reporter.js +0 -127
  35. package/spec/run-tests-runner.js +0 -40
  36. package/src/core/embeddings/worker.js +0 -27
  37. package/src/core/prompts/prompts.js +0 -15
  38. package/src/core/sessions/sessions.js +0 -27
  39. package/src/utils/ids.js +0 -27
@@ -1,118 +1,40 @@
1
- /**
2
- * CLI adapter: parse argv into tool args using the tool registry's inputSchema,
3
- * and format help from descriptions/schemas. No duplicate tool definitions.
4
- */
5
- import { getToolDefinitions, getToolByName } from './tool-registry.js';
6
-
7
- /** Unwrap ZodOptional/ZodNullable to get inner type for CLI coercion and help. */
8
- function unwrapZod(schema) {
9
- if (!schema || typeof schema !== 'object') return null;
10
- let s = schema;
11
- const optional = (s) => s?.constructor?.name === 'ZodOptional' || s?.constructor?.name === 'ZodNullable';
12
- while (s && optional(s)) {
13
- s = s._def?.innerType ?? s.unwrap?.() ?? null;
14
- }
15
- return s;
1
+ import { getToolDefinitions, getToolByName, validateToolArgs } from './tool-registry.js';
2
+
3
+ function getParamMeta(shape) {
4
+ return Object.fromEntries(Object.entries(shape).map(([key, schema]) => {
5
+ let inner = schema;
6
+ while (inner._def.innerType) inner = inner._def.innerType;
7
+ const type = inner._def.typeName.replace('Zod', '').toLowerCase();
8
+ return [key, { type, optional: schema.isOptional(), nullable: schema.isNullable() }];
9
+ }));
16
10
  }
17
11
 
18
- /** Return per-param meta: type ('string'|'number'|'boolean'|'array'), optional (boolean). */
19
- function getParamMeta(inputSchema) {
20
- const meta = {};
21
- for (const key of Object.keys(inputSchema)) {
22
- const schema = inputSchema[key];
23
- const unwrapped = unwrapZod(schema);
24
- const optional = !unwrapped || (schema?.constructor?.name === 'ZodOptional' || schema?.constructor?.name === 'ZodNullable');
25
- let type = 'string';
26
- if (unwrapped) {
27
- const name = unwrapped.constructor?.name ?? '';
28
- if (name === 'ZodNumber') type = 'number';
29
- else if (name === 'ZodBoolean') type = 'boolean';
30
- else if (name === 'ZodArray') type = 'array';
31
- }
32
- meta[key] = { type, optional };
33
- }
34
- return meta;
35
- }
36
-
37
- /**
38
- * Parse argv (e.g. ['--query', 'foo', '--limit', '5', '--hardDelete']) into an object
39
- * matching the tool's inputSchema. Supports --key value, --flag (boolean true), --no-flag (boolean false),
40
- * and repeated --key v1 --key v2 for arrays.
41
- */
42
- function parseToolArgs(toolDef, argv) {
43
- const meta = getParamMeta(toolDef.inputSchema);
12
+ export function parseToolArgs(tool, argv) {
13
+ const meta = getParamMeta(tool.inputSchema);
44
14
  const result = {};
45
- const args = [...argv];
46
-
47
- for (const key of Object.keys(meta)) {
48
- if (meta[key].type === 'boolean') {
49
- result[key] = false;
50
- } else if (meta[key].type === 'array') {
51
- result[key] = [];
52
- }
53
- }
54
-
55
- for (let i = 0; i < args.length; i++) {
56
- const a = args[i];
57
- if (a === '--help' || a === '-h') continue;
58
- if (!a.startsWith('--')) continue;
59
- const isNegated = a.startsWith('--no-');
60
- const paramKey = isNegated ? a.slice(5) : a.slice(2);
61
- if (!Object.prototype.hasOwnProperty.call(meta, paramKey)) continue;
62
- const { type } = meta[paramKey];
63
- if (type === 'boolean') {
64
- result[paramKey] = !isNegated;
65
- } else if (type === 'array') {
66
- const val = args[i + 1];
67
- if (val !== undefined && !val.startsWith('--')) {
68
- result[paramKey].push(val);
69
- i++;
70
- }
71
- } else {
72
- const val = args[i + 1];
73
- if (val !== undefined && !val.startsWith('--')) {
74
- if (type === 'number') {
75
- const n = Number(val);
76
- result[paramKey] = Number.isNaN(n) ? val : n;
77
- } else {
78
- result[paramKey] = val;
79
- }
80
- i++;
81
- }
82
- }
83
- }
84
-
85
- for (const key of Object.keys(meta)) {
86
- if (result[key] === undefined && meta[key].optional) {
87
- if (meta[key].type === 'array') result[key] = [];
88
- else if (meta[key].type === 'boolean') result[key] = false;
89
- }
90
- }
91
-
92
- return result;
93
- }
94
-
95
- /** Format help text for a single tool (description + params). */
96
- function formatToolHelp(toolDef) {
97
- const meta = getParamMeta(toolDef.inputSchema);
98
- const lines = [toolDef.description, '', 'Options:'];
99
- for (const [key, { type, optional }] of Object.entries(meta)) {
100
- const opt = optional ? ' (optional)' : '';
101
- if (type === 'boolean') {
102
- lines.push(` --${key} boolean${opt}`);
103
- lines.push(` --no-${key}`);
104
- } else if (type === 'array') {
105
- lines.push(` --${key} <value> repeat for multiple${opt}`);
106
- } else {
107
- lines.push(` --${key} <${type}>${opt}`);
108
- }
15
+ for (let i = 0; i < argv.length; i++) {
16
+ const flag = argv[i];
17
+ if (!flag.startsWith('--')) throw new Error(`Expected option, received ${flag}`);
18
+ const negated = flag.startsWith('--no-');
19
+ const key = flag.slice(negated ? 5 : 2);
20
+ const field = meta[key];
21
+ if (!field) throw new Error(`Unknown option: ${flag}`);
22
+ if (field.type === 'boolean') { result[key] = !negated; continue; }
23
+ if (negated && field.type === 'array') { result[key] = []; continue; }
24
+ if (negated && field.nullable) { result[key] = null; continue; }
25
+ if (negated) throw new Error(`Cannot negate ${key}`);
26
+ const value = argv[++i];
27
+ if (value === undefined || value.startsWith('--')) throw new Error(`Missing value for ${flag}`);
28
+ if (field.type === 'array') (result[key] ??= []).push(value);
29
+ else result[key] = field.type === 'number' ? Number(value) : value;
109
30
  }
110
- return lines.join('\n');
31
+ return validateToolArgs(tool.name, result);
111
32
  }
112
33
 
113
- /** List tool names for main help. */
114
- function listToolNames() {
115
- return getToolDefinitions().map((t) => t.name);
34
+ export function formatToolHelp(tool) {
35
+ return [tool.description, '', ...Object.entries(getParamMeta(tool.inputSchema)).map(([key, field]) =>
36
+ ` --${key}${field.type === 'boolean' ? '' : ' <value>'}${field.optional ? ' (optional)' : ''}${field.type === 'array' ? '; repeat or --no-' + key + ' to clear' : field.nullable ? '; --no-' + key + ' to clear' : ''}`)].join('\n');
116
37
  }
117
38
 
118
- export { getToolDefinitions, getToolByName, getParamMeta, parseToolArgs, formatToolHelp, listToolNames };
39
+ export function listToolNames() { return getToolDefinitions().map(tool => tool.name); }
40
+ export { getToolByName };
package/src/mcp/server.js CHANGED
@@ -3,162 +3,85 @@ import fs from 'fs';
3
3
  import path from 'path';
4
4
  import os from 'os';
5
5
  import { randomUUID } from 'crypto';
6
- import { fileURLToPath } from 'url';
7
6
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
8
7
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
9
8
  import { loadConfig } from '../config.js';
9
+ import { closeDb } from '../db/sqlite.js';
10
+ import { reindex } from '../core/indexing/reindex.js';
11
+ import { startWatcher } from '../fs/watcher.js';
10
12
  import { createToolHandlers } from './tools.js';
11
13
  import { getToolDefinitions } from './tool-registry.js';
12
14
 
13
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
14
- let embeddingWorkerChild = null;
15
- let embeddingWorkerConfigPath = null;
15
+ const version = JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
16
+ const workers = new WeakMap();
16
17
 
17
- const EMBED_TIMEOUT_MS = 60000;
18
-
19
- function makeQueryEmbedder(child) {
20
- return function getQueryEmbedding(text) {
21
- if (!child?.connected) return Promise.resolve(null);
22
- const id = randomUUID();
23
- return new Promise((resolve, reject) => {
24
- const timeout = setTimeout(() => {
25
- cleanup();
26
- reject(new Error('embedding timeout'));
27
- }, EMBED_TIMEOUT_MS);
28
- const onMessage = (msg) => {
29
- if (msg?.type !== 'embedResult' || msg.id !== id) return;
30
- cleanup();
31
- if (msg.err) {
32
- reject(new Error(msg.err));
33
- return;
34
- }
35
- resolve(msg.vector ? new Float32Array(msg.vector) : null);
36
- };
37
- const cleanup = () => {
38
- clearTimeout(timeout);
39
- child.off('message', onMessage);
40
- };
41
- child.on('message', onMessage);
42
- child.send({ type: 'embed', id, text });
43
- });
18
+ export function startEmbeddingWorker(config) {
19
+ if (!config.embeddings.enabled) return () => {};
20
+ if (workers.has(config)) return workers.get(config);
21
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'mixgram-worker-'));
22
+ const configPath = path.join(directory, 'config.json');
23
+ fs.writeFileSync(configPath, JSON.stringify(config));
24
+ const child = fork(new URL('../core/embeddings/worker-process.js', import.meta.url), [], {
25
+ stdio: ['ignore', 'ignore', 'inherit', 'ipc'], env: { ...process.env, MIXGRAM_WORKER_CONFIG: configPath }
26
+ });
27
+ const pending = new Map();
28
+ let closed = false;
29
+ const settle = (id, error, vector) => {
30
+ const request = pending.get(id);
31
+ if (!request) return;
32
+ pending.delete(id);
33
+ clearTimeout(request.timer);
34
+ if (error) request.reject(error); else request.resolve(new Float32Array(vector));
44
35
  };
36
+ child.on('message', msg => {
37
+ if (msg?.type === 'embedResult') settle(msg.id, msg.err ? new Error(msg.err) : null, msg.vector);
38
+ });
39
+ const cleanup = () => {
40
+ if (closed) return;
41
+ closed = true;
42
+ for (const id of pending.keys()) settle(id, new Error('Embedding worker stopped'));
43
+ delete config.getQueryEmbedding;
44
+ child.kill();
45
+ fs.rmSync(directory, { recursive: true, force: true });
46
+ workers.delete(config);
47
+ };
48
+ child.once('exit', cleanup);
49
+ child.once('error', cleanup);
50
+ config.getQueryEmbedding = text => new Promise((resolve, reject) => {
51
+ if (!child.connected || closed) { reject(new Error('Embedding worker unavailable')); return; }
52
+ const id = randomUUID();
53
+ const timer = setTimeout(() => settle(id, new Error('Query embedding timed out')), config.embeddings.queryTimeoutMs);
54
+ pending.set(id, { resolve, reject, timer });
55
+ child.send({ type: 'embed', id, text }, error => { if (error) settle(id, error); });
56
+ });
57
+ workers.set(config, cleanup);
58
+ return cleanup;
45
59
  }
46
60
 
47
- /**
48
- * Start the embedding worker and set config.getQueryEmbedding for use by mem_search.
49
- * Used by the CLI when running tools with --embeddings so that semantic search works.
50
- * Returns a cleanup function to kill the worker and remove the temp config file.
51
- */
52
- function startEmbeddingWorker(config) {
53
- if (!config?.embeddings?.enabled || config.getQueryEmbedding) {
54
- return () => {};
55
- }
56
- try {
57
- embeddingWorkerConfigPath = path.join(
58
- os.tmpdir(),
59
- `mixgram-worker-config-${process.pid}-${Date.now()}.json`
60
- );
61
- fs.writeFileSync(embeddingWorkerConfigPath, JSON.stringify(config), 'utf8');
62
- const workerPath = path.join(__dirname, '..', 'core', 'embeddings', 'worker-process.js');
63
- embeddingWorkerChild = fork(workerPath, [], {
64
- stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
65
- env: { ...process.env, MIXGRAM_WORKER_CONFIG: embeddingWorkerConfigPath }
66
- });
67
- config.getQueryEmbedding = makeQueryEmbedder(embeddingWorkerChild);
68
- const cleanup = () => {
69
- if (embeddingWorkerChild) {
70
- try { embeddingWorkerChild.kill(); } catch (_) {}
71
- embeddingWorkerChild = null;
72
- }
73
- config.getQueryEmbedding = null;
74
- if (embeddingWorkerConfigPath && fs.existsSync(embeddingWorkerConfigPath)) {
75
- try { fs.unlinkSync(embeddingWorkerConfigPath); } catch (_) {}
76
- embeddingWorkerConfigPath = null;
77
- }
78
- };
79
- embeddingWorkerChild.on('exit', () => {
80
- config.getQueryEmbedding = null;
81
- if (embeddingWorkerConfigPath && fs.existsSync(embeddingWorkerConfigPath)) {
82
- try { fs.unlinkSync(embeddingWorkerConfigPath); } catch (_) {}
83
- embeddingWorkerConfigPath = null;
84
- }
85
- });
86
- return cleanup;
87
- } catch (err) {
88
- if (typeof process !== 'undefined' && process.stderr) {
89
- process.stderr.write(`[mixgram] embeddings worker start failed: ${err?.message ?? err}\n`);
90
- }
91
- return () => {};
92
- }
93
- }
94
-
95
- function createServer(configOverrides = {}, baseDir = null, projectBaseDir = null) {
96
- const config = loadConfig(configOverrides, baseDir, projectBaseDir);
97
- const mcpServer = new McpServer(
98
- { name: 'mixgram', version: '1.0.0' },
99
- { capabilities: { tools: { listChanged: true } } }
100
- );
101
-
61
+ export function createServer(overrides = {}, baseDir) {
62
+ const config = loadConfig(overrides, baseDir);
63
+ const mcpServer = new McpServer({ name: 'mixgram', version });
102
64
  const handlers = createToolHandlers(config);
103
- const definitions = getToolDefinitions();
104
-
105
- for (const def of definitions) {
106
- const handler = handlers[def.name];
107
- if (!handler) continue;
108
- mcpServer.registerTool(def.name, {
109
- description: def.description,
110
- inputSchema: def.inputSchema
111
- }, async (args) => handler(args));
65
+ for (const tool of getToolDefinitions()) {
66
+ mcpServer.registerTool(tool.name, { description: tool.description, inputSchema: tool.schema }, handlers[tool.name]);
112
67
  }
113
-
114
68
  return { mcpServer, config };
115
69
  }
116
70
 
117
- async function run(configOverrides = {}, baseDir = null, projectBaseDir = null) {
118
- if (typeof process !== 'undefined') {
119
- process.on('unhandledRejection', (reason, promise) => {
120
- if (process.stderr) {
121
- process.stderr.write(`[mixgram] unhandledRejection: ${reason}\n`);
122
- }
123
- });
124
- }
125
-
126
- const { mcpServer, config } = createServer(configOverrides, baseDir, projectBaseDir);
127
-
128
- if (config.indexing?.reindexOnStartup) {
129
- try {
130
- const { fullReindex } = await import('../core/indexing/reindex.js');
131
- fullReindex(config);
132
- } catch (err) {
133
- if (typeof process !== 'undefined' && process.stderr) {
134
- process.stderr.write(`[mixgram] reindex on startup failed: ${err?.message ?? err}\n`);
135
- }
136
- }
137
- }
138
- if (config.watch) {
139
- try {
140
- const { startWatcher } = await import('../fs/watcher.js');
141
- startWatcher(config);
142
- } catch (err) {
143
- if (typeof process !== 'undefined' && process.stderr) {
144
- process.stderr.write(`[mixgram] watcher start failed: ${err?.message ?? err}\n`);
145
- }
146
- }
147
- }
148
- if (config.embeddings?.enabled) {
149
- const cleanup = startEmbeddingWorker(config);
150
- if (cleanup) {
151
- embeddingWorkerChild?.on('exit', (code, signal) => {
152
- if (code !== 0 && code != null && process.stderr) {
153
- process.stderr.write(`[mixgram] embeddings worker exited: code=${code} signal=${signal}\n`);
154
- }
155
- cleanup();
156
- });
157
- process.on('exit', () => cleanup());
158
- }
71
+ export async function run(overrides = {}, baseDir) {
72
+ const { mcpServer, config } = createServer(overrides, baseDir);
73
+ if (config.indexing.reindexOnStartup) {
74
+ const result = reindex(config);
75
+ for (const error of result.errors) process.stderr.write(`[mixgram] ${error.path}: ${error.error}\n`);
159
76
  }
77
+ const watcher = config.watch ? startWatcher(config) : null;
78
+ const stopWorker = startEmbeddingWorker(config);
79
+ const cleanup = async () => { await watcher?.close(); stopWorker(); closeDb(config); };
160
80
  const transport = new StdioServerTransport();
161
- await mcpServer.connect(transport);
81
+ mcpServer.server.onclose = cleanup;
82
+ const exit = async () => { await mcpServer.close(); await cleanup(); };
83
+ process.once('SIGINT', exit);
84
+ process.once('SIGTERM', exit);
85
+ try { await mcpServer.connect(transport); }
86
+ catch (error) { await cleanup(); throw error; }
162
87
  }
163
-
164
- export { createServer, run, startEmbeddingWorker };
@@ -1,138 +1,27 @@
1
- /**
2
- * Shared MCP tool registry: single source of truth for name, description, and inputSchema.
3
- * Used by the MCP server (registration) and CLI (subcommands and help).
4
- */
5
1
  import { z } from 'zod';
6
2
 
7
- const optionalString = z.string().optional();
8
- const optionalNumber = z.number().optional();
9
- const optionalBoolean = z.boolean().optional();
10
- const optionalArray = z.array(z.string()).optional();
11
-
12
- /** Tool definitions: name, description, inputSchema (Zod shape). Handlers live in tools.js. */
13
- const TOOL_DEFINITIONS = [
14
- {
15
- name: 'mem_save',
16
- description: 'Save a memory document (create or update by topic_key)',
17
- inputSchema: {
18
- title: optionalString,
19
- type: optionalString,
20
- scope: optionalString,
21
- project: optionalString.nullable(),
22
- topic_key: optionalString.nullable(),
23
- content: optionalString,
24
- session_id: optionalString.nullable(),
25
- id: optionalString.nullable(),
26
- tags: optionalArray
27
- }
28
- },
29
- {
30
- name: 'mem_update',
31
- description: 'Update an existing document by id',
32
- inputSchema: {
33
- id: z.string(),
34
- title: optionalString,
35
- content: optionalString,
36
- tags: optionalArray
37
- }
38
- },
39
- {
40
- name: 'mem_delete',
41
- description: 'Soft or hard delete a document by id',
42
- inputSchema: {
43
- id: z.string(),
44
- hardDelete: optionalBoolean
45
- }
46
- },
47
- {
48
- name: 'mem_suggest_topic_key',
49
- description: 'Suggest a stable topic key from title/content/type',
50
- inputSchema: {
51
- title: optionalString,
52
- content: optionalString,
53
- type: optionalString
54
- }
55
- },
56
- {
57
- name: 'mem_search',
58
- description: 'Full-text search over memory (project-only, home-only, or merged)',
59
- inputSchema: {
60
- query: z.string(),
61
- scope_mode: optionalString,
62
- project: optionalString.nullable(),
63
- limit: optionalNumber
64
- }
65
- },
66
- {
67
- name: 'mem_context',
68
- description: 'Get contextual memory for a project (recent or search-based)',
69
- inputSchema: {
70
- query: optionalString,
71
- project: optionalString.nullable(),
72
- limit: optionalNumber
73
- }
74
- },
75
- {
76
- name: 'mem_get_observation',
77
- description: 'Get full document content by id',
78
- inputSchema: { id: z.string() }
79
- },
80
- {
81
- name: 'mem_stats',
82
- description: 'Get memory statistics (documents, sessions, prompts)',
83
- inputSchema: {}
84
- },
85
- {
86
- name: 'mem_timeline',
87
- description: 'Get before/focus/after observations for an observation in its session',
88
- inputSchema: { observation_id: z.string() }
89
- },
90
- {
91
- name: 'mem_session_start',
92
- description: 'Start a new session',
93
- inputSchema: {
94
- session_id: optionalString.nullable(),
95
- project: optionalString.nullable(),
96
- directory: optionalString.nullable()
97
- }
98
- },
99
- {
100
- name: 'mem_session_end',
101
- description: 'End a session',
102
- inputSchema: { session_id: z.string() }
103
- },
104
- {
105
- name: 'mem_session_summary',
106
- description: 'Persist a session summary as durable memory',
107
- inputSchema: {
108
- session_id: z.string(),
109
- content: optionalString,
110
- summary: optionalString,
111
- title: optionalString
112
- }
113
- },
114
- {
115
- name: 'mem_save_prompt',
116
- description: 'Store a prompt for a session (no Markdown file by default)',
117
- inputSchema: {
118
- session_id: z.string(),
119
- project: optionalString.nullable(),
120
- content: optionalString
121
- }
122
- },
123
- {
124
- name: 'mem_reindex',
125
- description: 'Run full or incremental reindex from Markdown files',
126
- inputSchema: { full: optionalBoolean }
127
- }
3
+ const text = z.string().optional();
4
+ const name = z.string().min(1);
5
+ const tags = z.array(name).optional();
6
+ const definitions = [
7
+ { name: 'mem_save', description: 'Create a document, update by id, or upsert by explicit key within a collection. Omitted fields are preserved.', inputSchema: {
8
+ id: name.optional(), collection: name.optional(), title: text, content: text, type: name.optional(), key: name.nullable().optional(), tags
9
+ } },
10
+ { name: 'mem_search', description: 'Search documents or list recent documents without query. All supplied tags must match.', inputSchema: {
11
+ query: text, collection: name.optional(), type: name.optional(), tags, limit: z.number().int().positive().optional(), offset: z.number().int().nonnegative().optional()
12
+ } },
13
+ { name: 'mem_get', description: 'Read a full document with metadata separate from content.', inputSchema: { id: name } },
14
+ { name: 'mem_delete', description: 'Soft delete a document; hardDelete permanently removes its file.', inputSchema: { id: name, hardDelete: z.boolean().optional() } },
15
+ { name: 'mem_stats', description: 'Report document counts, index location and embedding queue status.', inputSchema: {} },
16
+ { name: 'mem_reindex', description: 'Synchronize Markdown files; full rebuilds the derived text index. Reports errors per file.', inputSchema: { full: z.boolean().optional() } }
128
17
  ];
129
18
 
130
- function getToolDefinitions() {
131
- return TOOL_DEFINITIONS;
132
- }
19
+ for (const tool of definitions) tool.schema = z.object(tool.inputSchema).strict();
133
20
 
134
- function getToolByName(name) {
135
- return TOOL_DEFINITIONS.find((t) => t.name === name) ?? null;
21
+ export function getToolDefinitions() { return definitions; }
22
+ export function getToolByName(name) { return definitions.find(tool => tool.name === name); }
23
+ export function validateToolArgs(name, args) {
24
+ const tool = getToolByName(name);
25
+ if (!tool) throw new Error('Unknown tool');
26
+ return tool.schema.parse(args);
136
27
  }
137
-
138
- export { getToolDefinitions, getToolByName, TOOL_DEFINITIONS };