@spike1292/claude-memory 0.0.0-stage → 0.14.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.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +412 -2
  3. package/hooks/distill-session.mjs +74 -0
  4. package/hooks/graph-staleness-check.mjs +25 -0
  5. package/hooks/hooks.json +94 -0
  6. package/hooks/insights-surface.mjs +48 -0
  7. package/hooks/lib/distill-session.mjs +1560 -0
  8. package/hooks/lib/dupe-report.mjs +61 -0
  9. package/hooks/lib/env-shell.mjs +92 -0
  10. package/hooks/lib/graph-staleness-check.mjs +394 -0
  11. package/hooks/lib/hook-io.mjs +715 -0
  12. package/hooks/lib/insights-surface.mjs +165 -0
  13. package/hooks/lib/memory-link-lint.mjs +499 -0
  14. package/hooks/lib/memory-recall.mjs +219 -0
  15. package/hooks/lib/omp.mjs +103 -0
  16. package/hooks/lib/opencode.mjs +231 -0
  17. package/hooks/lib/paths.mjs +452 -0
  18. package/hooks/lib/semantic-index-refresh.mjs +155 -0
  19. package/hooks/lib/validate-note.mjs +218 -0
  20. package/hooks/lib/vault-env.sh +110 -0
  21. package/hooks/memory-link-lint.mjs +65 -0
  22. package/hooks/memory-recall.mjs +251 -0
  23. package/hooks/semantic-index-refresh.mjs +23 -0
  24. package/hooks/session-context.mjs +9 -0
  25. package/hooks/validate-note.mjs +52 -0
  26. package/hooks/vault-memory-sync.sh +154 -0
  27. package/omp/index.js +1 -0
  28. package/opencode/index.js +1 -0
  29. package/package.json +51 -4
  30. package/scripts/claude-memory.mjs +31 -0
  31. package/scripts/doctor-perf.mjs +121 -0
  32. package/scripts/doctor.sh +558 -0
  33. package/scripts/env.mjs +6 -0
  34. package/scripts/lib/claude-memory.mjs +168 -0
  35. package/scripts/lib/doctor-perf.mjs +434 -0
  36. package/scripts/lib/hook-stats.mjs +864 -0
  37. package/scripts/lib/lexical.mjs +85 -0
  38. package/scripts/lib/memory-adopt.mjs +69 -0
  39. package/scripts/lib/memory-audit-checks.mjs +344 -0
  40. package/scripts/lib/memory-eval.mjs +381 -0
  41. package/scripts/lib/memory-mark.mjs +135 -0
  42. package/scripts/lib/memory-mcp.mjs +142 -0
  43. package/scripts/lib/memory-merge.mjs +316 -0
  44. package/scripts/lib/memory-mine.mjs +108 -0
  45. package/scripts/lib/memory-promote.mjs +207 -0
  46. package/scripts/lib/memory-prune.mjs +84 -0
  47. package/scripts/lib/memory-semantic.mjs +999 -0
  48. package/scripts/lib/memory-setup.mjs +170 -0
  49. package/scripts/lib/memory-synth-vault.mjs +538 -0
  50. package/scripts/lib/model-default.mjs +7 -0
  51. package/scripts/lib/models.mjs +58 -0
  52. package/scripts/lib/prune-logs.mjs +130 -0
  53. package/scripts/lib/recall-stats.mjs +354 -0
  54. package/scripts/lib/share-modules.mjs +70 -0
  55. package/scripts/lib/slim-install.mjs +162 -0
  56. package/scripts/lib/vault-mcp.mjs +405 -0
  57. package/scripts/memory-adopt.mjs +160 -0
  58. package/scripts/memory-audit-checks.mjs +375 -0
  59. package/scripts/memory-eval.mjs +753 -0
  60. package/scripts/memory-mark.mjs +39 -0
  61. package/scripts/memory-mcp.mjs +35 -0
  62. package/scripts/memory-merge.mjs +55 -0
  63. package/scripts/memory-prune.mjs +44 -0
  64. package/scripts/memory-semantic.mjs +1192 -0
  65. package/scripts/memory-setup.mjs +33 -0
  66. package/scripts/memory-synth-vault.mjs +251 -0
  67. package/scripts/prune-logs.mjs +42 -0
  68. package/scripts/share-modules.mjs +79 -0
  69. package/scripts/slim-install.mjs +55 -0
  70. package/scripts/vault-mcp.mjs +50 -0
  71. package/stubs/onnxruntime-web/index.mjs +11 -0
  72. package/stubs/onnxruntime-web/package.json +12 -0
  73. package/stubs/sharp/index.mjs +11 -0
  74. package/stubs/sharp/package.json +12 -0
@@ -0,0 +1,162 @@
1
+ // onnxruntime-node ships every platform's native runtime in one tarball: 210 MB under
2
+ // bin/napi-v6/{darwin,linux,win32}/{arm64,x64}, of which exactly one directory can ever load.
3
+ // Measured 2026-08-18 — 176 MB is unloadable on any given machine. npm cannot skip it (the
4
+ // binaries are inside the package, not optionalDependencies), so it gets deleted after install.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+
8
+ // Directory names onnxruntime-node uses; they happen to match process.platform / process.arch.
9
+ const OSES = new Set(['darwin', 'linux', 'win32']);
10
+ const ARCHES = new Set(['arm64', 'x64', 'ia32']);
11
+
12
+ /** @type {(p: string) => string[]} */
13
+ const dirs = (p) => {
14
+ try {
15
+ return fs
16
+ .readdirSync(p, { withFileTypes: true })
17
+ .filter((e) => e.isDirectory())
18
+ .map((e) => e.name);
19
+ } catch {
20
+ return []; // missing bin/ — nothing to prune, not an error
21
+ }
22
+ };
23
+
24
+ /**
25
+ * Directories under binDir that cannot load on this platform.
26
+ * Anything whose name is not a known os/arch is left alone: an upstream layout change must
27
+ * make this prune nothing rather than guess. Never returns binDir or a napi-v* dir itself.
28
+ *
29
+ * @param {string} binDir
30
+ * @param {string} [platform]
31
+ * @param {string} [arch]
32
+ * @returns {string[]}
33
+ */
34
+ export function pruneTargets(binDir, platform = process.platform, arch = process.arch) {
35
+ /** @type {string[]} */
36
+ const out = [];
37
+ // Unknown host: every directory would look foreign and the whole runtime would go. Do nothing.
38
+ if (!OSES.has(platform)) return out;
39
+ for (const napi of dirs(binDir)) {
40
+ const napiDir = path.join(binDir, napi);
41
+ for (const os of dirs(napiDir)) {
42
+ if (!OSES.has(os)) continue;
43
+ const osDir = path.join(napiDir, os);
44
+ if (os !== platform) {
45
+ out.push(osDir);
46
+ continue;
47
+ }
48
+ for (const a of dirs(osDir)) {
49
+ if (ARCHES.has(a) && a !== arch) out.push(path.join(osDir, a));
50
+ }
51
+ }
52
+ }
53
+ return out;
54
+ }
55
+
56
+ /**
57
+ * GPU execution-provider blobs. On linux, onnxruntime-node's own install script downloads a
58
+ * CUDA/TensorRT build on top of the bundled binaries — CI measured node_modules still at 363 MB
59
+ * after every other prune (2026-08-18). Nothing here asks for a GPU provider: the pipeline runs the
60
+ * default CPU EP at batch size 1, and macOS has never had these files at all, so the CPU path is
61
+ * the only one this plugin has ever exercised. They are dlopen'd lazily by name, so deleting them
62
+ * is inert unless someone adds `executionProviders: ['cuda']`.
63
+ * `libonnxruntime_providers_shared` stays — it is the small loader shim, not a provider.
64
+ */
65
+ const GPU_BLOB = /_providers_(cuda|tensorrt|rocm|migraphx)/;
66
+
67
+ /**
68
+ * @param {string} binDir
69
+ * @returns {string[]}
70
+ */
71
+ export function providerBlobs(binDir) {
72
+ /** @type {string[]} */
73
+ const out = [];
74
+ /** @type {(dir: string) => void} */
75
+ const walk = (dir) => {
76
+ /** @type {import('node:fs').Dirent[]} */
77
+ let entries = [];
78
+ try {
79
+ entries = fs.readdirSync(dir, { withFileTypes: true });
80
+ } catch {
81
+ return;
82
+ }
83
+ for (const e of entries) {
84
+ const p = path.join(dir, e.name);
85
+ if (e.isDirectory()) walk(p);
86
+ else if (GPU_BLOB.test(e.name)) out.push(p);
87
+ }
88
+ };
89
+ walk(binDir);
90
+ return out;
91
+ }
92
+
93
+ // --- unused packages ------------------------------------------------------------------------
94
+ // sharp + onnxruntime-web (147 MB) are stubbed, never deleted — both are static imports in
95
+ // transformers.node.mjs, so removing them fails resolution before any code runs; full rationale
96
+ // in CLAUDE.md's "node_modules is slimmed after install" section.
97
+ export const STUBBED = ['sharp', 'onnxruntime-web'];
98
+
99
+ // sharp's libvips binaries; nothing else depends on them once sharp itself is a stub.
100
+ export const DELETED = ['@img'];
101
+
102
+ const STUB_VERSION = '0.0.0-stub';
103
+
104
+ /**
105
+ * Every directory named `name` that sits directly inside some node_modules/, at any depth.
106
+ *
107
+ * @param {string} root
108
+ * @param {string[]} names
109
+ * @returns {string[]}
110
+ */
111
+ export function findPackages(root, names) {
112
+ /** @type {string[]} */
113
+ const found = [];
114
+ /** @type {(dir: string) => void} */
115
+ const walk = (dir) => {
116
+ for (const e of dirs(dir)) {
117
+ const p = path.join(dir, e);
118
+ if (names.includes(e) || (e.startsWith('@') && names.includes(`${e}/${path.basename(p)}`))) {
119
+ found.push(p);
120
+ continue; // do not descend into something we are about to replace
121
+ }
122
+ if (e.startsWith('@')) {
123
+ for (const scoped of dirs(p)) {
124
+ if (names.includes(`${e}/${scoped}`)) found.push(path.join(p, scoped));
125
+ else walk(path.join(p, scoped, 'node_modules'));
126
+ }
127
+ continue;
128
+ }
129
+ walk(path.join(p, 'node_modules'));
130
+ }
131
+ };
132
+ walk(root);
133
+ return found;
134
+ }
135
+
136
+ /**
137
+ * True once the stub is in place — keeps a repeated postinstall from re-copying.
138
+ *
139
+ * @param {string} dir
140
+ * @returns {boolean}
141
+ */
142
+ export function isStub(dir) {
143
+ try {
144
+ return (
145
+ JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).version === STUB_VERSION
146
+ );
147
+ } catch {
148
+ return false;
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Recursive byte count — only used to report what was freed.
154
+ *
155
+ * @param {string} p
156
+ * @returns {number}
157
+ */
158
+ export function bytes(p) {
159
+ const st = fs.statSync(p);
160
+ if (!st.isDirectory()) return st.size;
161
+ return fs.readdirSync(p).reduce((n, e) => n + bytes(path.join(p, e)), 0);
162
+ }
@@ -0,0 +1,405 @@
1
+ // Read-only MCP server over the vault, for a claude.ai custom connector. MCP 2026-07-28 only,
2
+ // Streamable HTTP with JSON responses, hand-rolled JSON-RPC: no SDK, no new dependency.
3
+ // Why bearer-only, Origin refused, one protocol version and an ungated keyword fallback:
4
+ // docs/decisions/2026-10-13-vault-mcp.md.
5
+ import crypto from 'node:crypto';
6
+ import fs from 'node:fs';
7
+ import http from 'node:http';
8
+ import net from 'node:net';
9
+ import path from 'node:path';
10
+ import * as paths from '../../hooks/lib/paths.mjs';
11
+ import { detach } from '../../hooks/lib/hook-io.mjs';
12
+ import { bm25, lexTokens } from './lexical.mjs';
13
+ import {
14
+ MODEL_KEY,
15
+ SAFE_NAME,
16
+ indexedSlugs,
17
+ isIndexedSlug,
18
+ vaultSources,
19
+ } from './memory-semantic.mjs';
20
+
21
+ export const PROTOCOL = '2026-07-28';
22
+ export const BODY_CAP = 64 * 1024;
23
+ const PV = 'io.modelcontextprotocol/protocolVersion';
24
+ const SERVER_INFO = 'io.modelcontextprotocol/serverInfo';
25
+ const PAGE = { ttlMs: 300000, cacheScope: 'public' };
26
+
27
+ const TOOLS = [
28
+ {
29
+ name: 'list_projects',
30
+ description: 'List the vault projects that have a search index. Call this first.',
31
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
32
+ },
33
+ {
34
+ name: 'search',
35
+ description: 'Search one project of the memory vault. Returns the best-matching notes.',
36
+ inputSchema: {
37
+ type: 'object',
38
+ properties: {
39
+ query: { type: 'string' },
40
+ project: { type: 'string', description: 'A slug from list_projects' },
41
+ k: { type: 'integer', minimum: 1, maximum: 10, default: 5 },
42
+ },
43
+ required: ['query', 'project'],
44
+ additionalProperties: false,
45
+ },
46
+ },
47
+ {
48
+ name: 'get_note',
49
+ description: 'Read one note of a project by its name, as returned by search.',
50
+ inputSchema: {
51
+ type: 'object',
52
+ properties: { project: { type: 'string' }, note: { type: 'string' } },
53
+ required: ['project', 'note'],
54
+ additionalProperties: false,
55
+ },
56
+ },
57
+ ];
58
+
59
+ class RpcError extends Error {
60
+ /**
61
+ * @param {number} code
62
+ * @param {string} message
63
+ * @param {number} [status]
64
+ * @param {unknown} [data]
65
+ */
66
+ constructor(code, message, status = 200, data) {
67
+ super(message);
68
+ this.code = code;
69
+ this.status = status;
70
+ this.data = data;
71
+ }
72
+ }
73
+ /** @param {string} msg */
74
+ const badArgs = (msg) => new RpcError(-32602, msg);
75
+
76
+ /**
77
+ * @param {{ tokenFile?: string, credentialsDir?: string }} o
78
+ * @returns {string}
79
+ */
80
+ export function readToken({ tokenFile, credentialsDir }) {
81
+ const file = tokenFile || (credentialsDir ? path.join(credentialsDir, 'vault-mcp-token') : '');
82
+ if (!file) throw new Error('no token: pass --token-file or set $CREDENTIALS_DIRECTORY');
83
+ const token = fs.readFileSync(file, 'utf8').trim();
84
+ if (Buffer.byteLength(token) < 32) throw new Error('token shorter than 32 bytes');
85
+ return token;
86
+ }
87
+
88
+ /**
89
+ * @param {string | undefined} header
90
+ * @param {string} token
91
+ */
92
+ function authorized(header, token) {
93
+ const got = Buffer.from(String(header ?? ''));
94
+ const want = Buffer.from(`Bearer ${token}`);
95
+ return got.length === want.length && crypto.timingSafeEqual(got, want);
96
+ }
97
+
98
+ /**
99
+ * @param {import('node:http').IncomingMessage} req
100
+ * @returns {Promise<string | null>} null when over BODY_CAP
101
+ */
102
+ function readCapped(req) {
103
+ if (Number(req.headers['content-length']) > BODY_CAP) return Promise.resolve(null);
104
+ return new Promise((resolve, reject) => {
105
+ /** @type {Buffer[]} */
106
+ const chunks = [];
107
+ let size = 0;
108
+ req.on('data', (/** @type {Buffer} */ c) => {
109
+ size += c.length;
110
+ if (size > BODY_CAP) {
111
+ req.removeAllListeners('data');
112
+ req.pause();
113
+ resolve(null);
114
+ } else chunks.push(c);
115
+ });
116
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
117
+ req.on('error', reject);
118
+ });
119
+ }
120
+
121
+ /**
122
+ * @param {string} sockPath
123
+ * @param {object} msg
124
+ * @param {number} timeoutMs
125
+ * @returns {Promise<any>}
126
+ */
127
+ export function askServe(sockPath, msg, timeoutMs) {
128
+ return new Promise((resolve) => {
129
+ const c = net.createConnection(sockPath);
130
+ c.setEncoding('utf8');
131
+ let buf = '';
132
+ const done = (/** @type {any} */ v) => {
133
+ clearTimeout(timer);
134
+ c.destroy();
135
+ resolve(v);
136
+ };
137
+ const timer = setTimeout(() => done(null), timeoutMs);
138
+ c.on('connect', () => c.write(JSON.stringify(msg) + '\n'));
139
+ c.on('data', (d) => (buf += d));
140
+ c.on('end', () => {
141
+ try {
142
+ done(JSON.parse(buf));
143
+ } catch {
144
+ done(null);
145
+ }
146
+ });
147
+ c.on('error', () => done(null));
148
+ });
149
+ }
150
+
151
+ /** @typedef {{ note: string, layer: string, text: string | null }} Card */
152
+
153
+ // Same BM25 over the same CARD rows as recall's keywordArm(), without its prompt-injection gates:
154
+ // a search tool returns a ranking and lets the caller judge it.
155
+ /**
156
+ * @param {readonly Card[]} cards
157
+ * @param {string} query
158
+ * @param {number} k
159
+ */
160
+ export function keywordSearch(cards, query, k) {
161
+ const qt = [...new Set(lexTokens(query))];
162
+ if (!qt.length) return [];
163
+ const docs = cards.map((c) => ({ ...c, toks: lexTokens(c.text ?? '') }));
164
+ const scores = bm25(docs, qt, 1.2, 0.75);
165
+ return docs
166
+ .map((d, i) => ({ note: d.note, layer: d.layer, text: d.text, score: +scores[i].toFixed(4) }))
167
+ .filter((r) => r.score > 0)
168
+ .sort((a, b) => b.score - a.score)
169
+ .slice(0, k);
170
+ }
171
+
172
+ /**
173
+ * Resolves only to a file directly inside one of the project's vaultSources() folders, by real
174
+ * path, so a symlink out of them is refused like a missing note.
175
+ * @param {string} vault
176
+ * @param {string} project
177
+ * @param {unknown} note
178
+ * @returns {string | null}
179
+ */
180
+ function readNote(vault, project, note) {
181
+ if (typeof note !== 'string' || !SAFE_NAME.test(note)) return null;
182
+ const file = note.endsWith('.md') ? note : `${note}.md`;
183
+ const real = (/** @type {string} */ p) => {
184
+ try {
185
+ return fs.realpathSync(p);
186
+ } catch {
187
+ return null;
188
+ }
189
+ };
190
+ const roots = vaultSources(vault, project)
191
+ .map((s) => real(s.dir))
192
+ .filter((d) => d !== null);
193
+ for (const root of roots) {
194
+ const p = real(path.join(root, file));
195
+ if (p && roots.includes(path.dirname(p)) && fs.statSync(p).isFile())
196
+ return fs.readFileSync(p, 'utf8');
197
+ }
198
+ return null;
199
+ }
200
+
201
+ /**
202
+ * @typedef {{
203
+ * token: string,
204
+ * readCards: (dbFile: string) => Card[],
205
+ * vault?: string,
206
+ * dbDir?: string,
207
+ * sockPath?: string,
208
+ * spawn?: () => void,
209
+ * timeoutMs?: number,
210
+ * log?: (line: string) => void,
211
+ * }} HandlerOptions
212
+ */
213
+
214
+ /**
215
+ * @param {HandlerOptions} o
216
+ * @returns {(req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => Promise<void>}
217
+ */
218
+ export function createHandler({
219
+ token,
220
+ readCards,
221
+ vault = paths.vault(),
222
+ dbDir = paths.stateDir('db'),
223
+ sockPath = path.join(paths.stateDir('run'), `search-${MODEL_KEY}.sock`),
224
+ spawn = () =>
225
+ detach(process.execPath, [path.join(paths.scriptsDir, 'memory-semantic.mjs'), '--serve']),
226
+ timeoutMs = 1500,
227
+ log = (line) => console.error(line),
228
+ }) {
229
+ const version = JSON.parse(
230
+ fs.readFileSync(path.join(paths.pluginRoot, 'package.json'), 'utf8'),
231
+ ).version;
232
+ const meta = { [SERVER_INFO]: { name: 'vault-mcp', version } };
233
+
234
+ /** @param {unknown} project */
235
+ const project = (project) => {
236
+ if (!isIndexedSlug(dbDir, project)) throw badArgs('unknown project; call list_projects');
237
+ return project;
238
+ };
239
+
240
+ /**
241
+ * @param {string} name
242
+ * @param {Record<string, unknown>} args
243
+ */
244
+ async function callTool(name, args) {
245
+ if (name === 'list_projects') return { projects: indexedSlugs(dbDir) };
246
+ if (name === 'search') {
247
+ const slug = project(args.project);
248
+ const { query, k = 5 } = args;
249
+ if (typeof query !== 'string' || !query.trim()) throw badArgs('query must be a string');
250
+ if (!Number.isInteger(k) || /** @type {number} */ (k) < 1 || /** @type {number} */ (k) > 10)
251
+ throw badArgs('k must be an integer from 1 to 10');
252
+ const n = /** @type {number} */ (k);
253
+ const sem = await askServe(sockPath, { q: query, k: n, slug }, timeoutMs);
254
+ if (Array.isArray(sem?.results)) {
255
+ const results = sem.results.map((/** @type {any} */ r) => ({
256
+ note: r.note,
257
+ layer: r.layer,
258
+ text: r.text,
259
+ score: r.score,
260
+ }));
261
+ return { arm: 'semantic', results };
262
+ }
263
+ spawn();
264
+ const dbFile = path.join(dbDir, `semantic-${slug}-${MODEL_KEY}.db`);
265
+ return { arm: 'keyword', results: keywordSearch(readCards(dbFile), query, n) };
266
+ }
267
+ if (name === 'get_note') {
268
+ const text = readNote(vault, project(args.project), args.note);
269
+ if (text === null) throw badArgs('no such note in this project');
270
+ return text;
271
+ }
272
+ throw badArgs('unknown tool');
273
+ }
274
+
275
+ /**
276
+ * @param {string} raw
277
+ * @param {import('node:http').IncomingHttpHeaders} headers
278
+ * @returns {Promise<{ status: number, body: object, msg?: any }>}
279
+ */
280
+ async function rpc(raw, headers) {
281
+ /** @type {any} */
282
+ let msg;
283
+ try {
284
+ msg = JSON.parse(raw);
285
+ } catch {
286
+ return reply(null, new RpcError(-32700, 'parse error', 400));
287
+ }
288
+ const valid =
289
+ msg &&
290
+ typeof msg === 'object' &&
291
+ !Array.isArray(msg) &&
292
+ msg.jsonrpc === '2.0' &&
293
+ typeof msg.method === 'string' &&
294
+ (typeof msg.id === 'string' || Number.isInteger(msg.id)) &&
295
+ (msg.params === undefined || (msg.params && typeof msg.params === 'object'));
296
+ if (!valid) return reply(null, new RpcError(-32600, 'invalid request', 400));
297
+ const id = msg.id;
298
+ const params = msg.params ?? {};
299
+ try {
300
+ const requested = msg.method === 'initialize' ? params.protocolVersion : params._meta?.[PV];
301
+ if (requested === undefined && msg.method !== 'initialize')
302
+ throw new RpcError(-32602, 'missing _meta protocolVersion', 400);
303
+ if (requested !== PROTOCOL)
304
+ throw new RpcError(-32022, 'unsupported protocol version', 400, {
305
+ supported: [PROTOCOL],
306
+ requested: requested ?? null,
307
+ });
308
+ const mismatch =
309
+ headers['mcp-protocol-version'] !== PROTOCOL ||
310
+ headers['mcp-method'] !== msg.method ||
311
+ (msg.method === 'tools/call' && headers['mcp-name'] !== params.name);
312
+ if (mismatch) throw new RpcError(-32020, 'header mismatch', 400);
313
+
314
+ /** @type {object} */
315
+ let result;
316
+ if (msg.method === 'server/discover')
317
+ result = {
318
+ supportedVersions: [PROTOCOL],
319
+ capabilities: { tools: {} },
320
+ ttlMs: 3600000,
321
+ cacheScope: 'public',
322
+ };
323
+ else if (msg.method === 'tools/list') result = { tools: TOOLS, ...PAGE };
324
+ else if (msg.method === 'tools/call') {
325
+ const args = params.arguments ?? {};
326
+ if (typeof params.name !== 'string' || typeof args !== 'object' || Array.isArray(args))
327
+ throw badArgs('tools/call needs a name and an arguments object');
328
+ const out = await callTool(params.name, args);
329
+ result =
330
+ typeof out === 'string'
331
+ ? { content: [{ type: 'text', text: out }], isError: false }
332
+ : {
333
+ content: [{ type: 'text', text: JSON.stringify(out) }],
334
+ structuredContent: out,
335
+ isError: false,
336
+ };
337
+ } else throw new RpcError(-32601, 'method not found');
338
+ return {
339
+ status: 200,
340
+ body: { jsonrpc: '2.0', id, result: { resultType: 'complete', ...result, _meta: meta } },
341
+ msg,
342
+ };
343
+ } catch (e) {
344
+ return { ...reply(id, e), msg };
345
+ }
346
+ }
347
+
348
+ /**
349
+ * @param {unknown} id
350
+ * @param {unknown} e
351
+ */
352
+ function reply(id, e) {
353
+ const err = e instanceof RpcError ? e : new RpcError(-32603, 'internal error', 500);
354
+ /** @type {{ code: number, message: string, data?: unknown }} */
355
+ const error = { code: err.code, message: err.message };
356
+ if (err.data !== undefined) error.data = err.data;
357
+ return { status: err.status, body: { jsonrpc: '2.0', id, error } };
358
+ }
359
+
360
+ return async (req, res) => {
361
+ /**
362
+ * @param {number} status
363
+ * @param {object} [body]
364
+ * @param {Record<string, string>} [extra]
365
+ */
366
+ const send = (status, body, extra = {}) => {
367
+ const h = body ? { 'content-type': 'application/json', ...extra } : extra;
368
+ res.writeHead(status, h);
369
+ res.end(body ? JSON.stringify(body) : undefined);
370
+ };
371
+ if (!authorized(req.headers.authorization, token)) return send(401);
372
+ if (req.headers.origin !== undefined) return send(403);
373
+ if (new URL(req.url ?? '/', 'http://x').pathname !== '/mcp') return send(404);
374
+ if (req.method !== 'POST') return send(405, undefined, { allow: 'POST' });
375
+ const raw = await readCapped(req).catch(() => null);
376
+ if (raw === null) return send(413, undefined, { connection: 'close' });
377
+ const { status, body, msg } = await rpc(raw, req.headers);
378
+ log(
379
+ JSON.stringify({
380
+ t: new Date().toISOString(),
381
+ status,
382
+ method: msg?.method,
383
+ protocolVersion: req.headers['mcp-protocol-version'],
384
+ clientInfo: msg?.params?._meta?.['io.modelcontextprotocol/clientInfo'],
385
+ }),
386
+ );
387
+ send(status, body);
388
+ };
389
+ }
390
+
391
+ /**
392
+ * @param {HandlerOptions & { host?: string, port: number }} o
393
+ * @returns {import('node:http').Server}
394
+ */
395
+ export function startServer({ host = '127.0.0.1', port, ...opts }) {
396
+ const handle = createHandler(opts);
397
+ return http
398
+ .createServer((req, res) => {
399
+ handle(req, res).catch(() => {
400
+ if (!res.headersSent) res.writeHead(500);
401
+ res.end();
402
+ });
403
+ })
404
+ .listen(port, host);
405
+ }