nebula-memory-mcp 1.0.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/mcp-server.mjs +80 -7
- package/memory/store.cjs +66 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -49,6 +49,23 @@
|
|
|
49
49
|
| `stats` | 记忆库统计 | 无 |
|
|
50
50
|
| `forget` | 按 id 删除 | `id`(必填) |
|
|
51
51
|
|
|
52
|
+
四个工具都接受一个**可选** `namespace` 参数(见下节)。
|
|
53
|
+
|
|
54
|
+
## 多库(namespace)
|
|
55
|
+
|
|
56
|
+
想让同一个 MCP Server 管多套互不干扰的记忆(比如工作 / 个人分开)?在任意工具调用里加 `namespace` 即可:
|
|
57
|
+
|
|
58
|
+
```json
|
|
59
|
+
{"text":"记在工作库","namespace":"work"}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
- **不填** `namespace` → 用默认单库(路径即 `NEBULA_DATA_DIR`,老用户无需改任何配置);
|
|
63
|
+
- **填了** → 用独立子库 `NEBULA_DATA_DIR/__ns__/<namespace>/`,各库完全隔离,召回也只在指定库内;
|
|
64
|
+
- `namespace` 只允许字母、数字、`_`、`-`,长度 ≤ 64(防目录穿越,非法值会报错);
|
|
65
|
+
- `recall` / `stats` / `forget` 同样支持 `namespace`,传了就只操作对应库。
|
|
66
|
+
|
|
67
|
+
典型用法:给不同项目或不同 Agent 各起一个 namespace,一句话切换记忆库,无需启动多个 MCP 进程。
|
|
68
|
+
|
|
52
69
|
## 环境变量
|
|
53
70
|
|
|
54
71
|
| 变量 | 说明 | 默认 |
|
package/mcp-server.mjs
CHANGED
|
@@ -42,12 +42,38 @@ const DATA_DIR = path.resolve(
|
|
|
42
42
|
|
|
43
43
|
const SERVER_INFO = {
|
|
44
44
|
name: 'agent-memory',
|
|
45
|
-
version: '1.
|
|
45
|
+
version: '1.2.0',
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
// MCP 协议版本(当前规范)
|
|
49
49
|
const PROTOCOL_VERSION = '2024-11-05'
|
|
50
50
|
|
|
51
|
+
// ── 多库(namespace)支持 ────────────────────────────────────────────────
|
|
52
|
+
// 可选参数:不传 namespace 时走原来的 DATA_DIR 单库(完全向后兼容);
|
|
53
|
+
// 传了则用 DATA_DIR/__ns__/<name> 子目录,各库互不干扰。
|
|
54
|
+
const NS_ROOT = path.join(DATA_DIR, '__ns__')
|
|
55
|
+
const memCache = new Map() // namespace -> NebulaMemory 实例
|
|
56
|
+
|
|
57
|
+
function normalizeNamespace(ns) {
|
|
58
|
+
if (ns == null) return null
|
|
59
|
+
const s = String(ns).trim()
|
|
60
|
+
if (!s) return null
|
|
61
|
+
// 白名单:只允许字母数字、下划线、连字符;防止目录穿越。
|
|
62
|
+
if (!/^[A-Za-z0-9_-]{1,64}$/.test(s)) throw new Error(`invalid namespace: ${s}`)
|
|
63
|
+
return s
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function getMemory(ns) {
|
|
67
|
+
if (ns == null) return null // 调用方改用默认单库实例
|
|
68
|
+
if (!memCache.has(ns)) {
|
|
69
|
+
const dir = path.join(NS_ROOT, ns)
|
|
70
|
+
const m = new NebulaMemory({ dir, log: () => {} })
|
|
71
|
+
await m.init()
|
|
72
|
+
memCache.set(ns, m)
|
|
73
|
+
}
|
|
74
|
+
return memCache.get(ns)
|
|
75
|
+
}
|
|
76
|
+
|
|
51
77
|
// ── stdio 行缓冲读写 ─────────────────────────────────────────────────────
|
|
52
78
|
// MCP stdio transport:每行一个 JSON-RPC 消息(LF 分隔),无 Content-Length 头
|
|
53
79
|
// (那是 LSP 的做法;MCP stdio 用换行分隔的 JSON)。
|
|
@@ -87,6 +113,7 @@ const TOOLS = [
|
|
|
87
113
|
kind: { type: 'string', enum: ['episode', 'fact', 'note', 'profile'], description: '记忆类型,默认 episode' },
|
|
88
114
|
importance: { type: 'number', description: '重要性 0~1,1.0 = 永久置顶', minimum: 0, maximum: 1 },
|
|
89
115
|
tags: { type: 'array', items: { type: 'string' }, description: '标签' },
|
|
116
|
+
namespace: { type: 'string', description: '目标记忆库(可选)。不填=默认单库;填了写入独立子库,如 work/personal。仅字母数字、_、-,≤64字符。' },
|
|
90
117
|
},
|
|
91
118
|
required: ['text'],
|
|
92
119
|
},
|
|
@@ -99,6 +126,7 @@ const TOOLS = [
|
|
|
99
126
|
properties: {
|
|
100
127
|
query: { type: 'string', description: '要检索的内容' },
|
|
101
128
|
limit: { type: 'number', description: '最多返回条数,默认 6' },
|
|
129
|
+
namespace: { type: 'string', description: '目标记忆库(可选)。不填=默认单库;填了只在该子库内检索。' },
|
|
102
130
|
},
|
|
103
131
|
required: ['query'],
|
|
104
132
|
},
|
|
@@ -106,21 +134,38 @@ const TOOLS = [
|
|
|
106
134
|
{
|
|
107
135
|
name: 'stats',
|
|
108
136
|
description: '返回当前记忆库的统计信息(节点数、边数等)。',
|
|
109
|
-
inputSchema: {
|
|
137
|
+
inputSchema: {
|
|
138
|
+
type: 'object',
|
|
139
|
+
properties: { namespace: { type: 'string', description: '目标记忆库(可选)。不填=默认单库。' } },
|
|
140
|
+
},
|
|
110
141
|
},
|
|
111
142
|
{
|
|
112
143
|
name: 'forget',
|
|
113
144
|
description: '按 id 删除一条记忆。',
|
|
114
145
|
inputSchema: {
|
|
115
146
|
type: 'object',
|
|
116
|
-
properties: {
|
|
147
|
+
properties: {
|
|
148
|
+
id: { type: 'string', description: '记忆 id' },
|
|
149
|
+
namespace: { type: 'string', description: '目标记忆库(可选)。不填=默认单库。' },
|
|
150
|
+
},
|
|
117
151
|
required: ['id'],
|
|
118
152
|
},
|
|
119
153
|
},
|
|
154
|
+
{
|
|
155
|
+
name: 'compact',
|
|
156
|
+
description: '手动压缩记忆库文件:清理追加历史,磁盘显著变小、下次启动明显变快。实例保持可用,不影响读写。可选 namespace。',
|
|
157
|
+
inputSchema: {
|
|
158
|
+
type: 'object',
|
|
159
|
+
properties: { namespace: { type: 'string', description: '目标记忆库(可选)。不填=默认单库。' } },
|
|
160
|
+
},
|
|
161
|
+
},
|
|
120
162
|
]
|
|
121
163
|
|
|
122
164
|
// ── 工具执行 ─────────────────────────────────────────────────────────────
|
|
123
|
-
|
|
165
|
+
// defaultMem:默认单库实例;args.namespace 传了就切到对应子库。
|
|
166
|
+
async function callTool(name, args, defaultMem) {
|
|
167
|
+
const ns = normalizeNamespace(args.namespace)
|
|
168
|
+
const mem = ns == null ? defaultMem : await getMemory(ns)
|
|
124
169
|
switch (name) {
|
|
125
170
|
case 'remember': {
|
|
126
171
|
const input = { text: String(args.text || '') }
|
|
@@ -149,6 +194,16 @@ async function callTool(name, args, mem) {
|
|
|
149
194
|
const r = await mem.forget(String(args.id || ''))
|
|
150
195
|
return { content: [{ type: 'text', text: JSON.stringify(r) }] }
|
|
151
196
|
}
|
|
197
|
+
case 'compact': {
|
|
198
|
+
const r = await mem.compact()
|
|
199
|
+
const summary = {
|
|
200
|
+
ok: r.ok,
|
|
201
|
+
durationMs: r.durationMs,
|
|
202
|
+
nodeLines: `${r.before.nodeLines} -> ${r.after.nodeLines}`,
|
|
203
|
+
nodesFileMB: `${r.before.nodesMB} -> ${r.after.nodesMB}`,
|
|
204
|
+
}
|
|
205
|
+
return { content: [{ type: 'text', text: JSON.stringify(summary) }] }
|
|
206
|
+
}
|
|
152
207
|
default:
|
|
153
208
|
throw new Error(`unknown tool: ${name}`)
|
|
154
209
|
}
|
|
@@ -156,8 +211,26 @@ async function callTool(name, args, mem) {
|
|
|
156
211
|
|
|
157
212
|
// ── 主流程 ───────────────────────────────────────────────────────────────
|
|
158
213
|
async function main() {
|
|
159
|
-
|
|
160
|
-
|
|
214
|
+
// CLI 子命令:node mcp-server.mjs compact [数据目录]
|
|
215
|
+
// ⚠️ 必须在插件服务停止后使用(压缩重写 JSONL,与服务双写会冲突)。
|
|
216
|
+
if (process.argv[2] === 'compact') {
|
|
217
|
+
const dir = path.resolve(
|
|
218
|
+
process.argv[3] ||
|
|
219
|
+
process.env.NEBULA_DATA_DIR ||
|
|
220
|
+
process.env.MEMORY_NEBULA_DATA_DIR ||
|
|
221
|
+
path.join(os.homedir(), '.agent-memory')
|
|
222
|
+
)
|
|
223
|
+
const mem = new NebulaMemory({ dir, log: () => {} })
|
|
224
|
+
await mem.init()
|
|
225
|
+
const r = await mem.compact()
|
|
226
|
+
await mem.close()
|
|
227
|
+
console.log(JSON.stringify(r, null, 2))
|
|
228
|
+
return
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// 默认单库实例(不传 namespace 时用),保持与旧版完全一致的行为。
|
|
232
|
+
const defaultMem = new NebulaMemory({ dir: DATA_DIR, log: () => {} })
|
|
233
|
+
await defaultMem.init()
|
|
161
234
|
|
|
162
235
|
readStdinLines(async (line) => {
|
|
163
236
|
let msg
|
|
@@ -181,7 +254,7 @@ async function main() {
|
|
|
181
254
|
break
|
|
182
255
|
case 'tools/call': {
|
|
183
256
|
const { name, arguments: args } = params || {}
|
|
184
|
-
const result = await callTool(name, args || {},
|
|
257
|
+
const result = await callTool(name, args || {}, defaultMem)
|
|
185
258
|
ok(id, result)
|
|
186
259
|
break
|
|
187
260
|
}
|
package/memory/store.cjs
CHANGED
|
@@ -87,6 +87,8 @@ const DEFAULTS = {
|
|
|
87
87
|
observeConsolidateEvery: 20, // observe() 每 N 轮触发一次巩固
|
|
88
88
|
observeConsolidateDays: 1, // 或距上次巩固超过 A 天
|
|
89
89
|
tickConsolidateDays: 1, // tick() 里距上次巩固超过 A 天才真正巩固
|
|
90
|
+
autoCompactRatio: 2.5, // 追加行数 > 存活×该比例 → 自动调度压缩(0 = 关闭自动压缩)
|
|
91
|
+
autoCompactDelayMs: 5000, // 跨过阈值后延迟这么多毫秒再压(防抖:写突发结束才动手)
|
|
90
92
|
};
|
|
91
93
|
|
|
92
94
|
/** 打分权重(1 = 原位;调大可放大该因子对排序的影响) */
|
|
@@ -446,6 +448,7 @@ class NebulaMemory {
|
|
|
446
448
|
}
|
|
447
449
|
this._ready = true;
|
|
448
450
|
if (this._indexDirty) this._writeIndexSnapshot();
|
|
451
|
+
this._scheduleAutoCompact(); // 重启加载后若追加历史已膨胀,排一次自动压缩
|
|
449
452
|
this._log(
|
|
450
453
|
'info',
|
|
451
454
|
`ready dir=${this.dir} nodes=${this.nodes.size} edges=${this.edgeMap.size} badLines=${this._badLines}`
|
|
@@ -467,6 +470,7 @@ class NebulaMemory {
|
|
|
467
470
|
/** 关闭:落 pending 更新 → 必要时压缩 → 落索引快照。可重复调用。 */
|
|
468
471
|
async close() {
|
|
469
472
|
if (!this._ready) return;
|
|
473
|
+
if (this._autoCompactTimer) { clearTimeout(this._autoCompactTimer); this._autoCompactTimer = null; }
|
|
470
474
|
this._flushPending();
|
|
471
475
|
this._maybeCompact();
|
|
472
476
|
if (this._traceLines > num(this.opts.traceMax, 200)) this._compactTrace();
|
|
@@ -476,6 +480,67 @@ class NebulaMemory {
|
|
|
476
480
|
this._closed = true;
|
|
477
481
|
}
|
|
478
482
|
|
|
483
|
+
/**
|
|
484
|
+
* 手动压缩(实例保持可用):落 pending → 强制重写 nodes/edges jsonl → 落索引快照。
|
|
485
|
+
* 只序列化内存里的存活集,规模再大也是亚秒级;收益是磁盘文件和下一次冷启动。
|
|
486
|
+
* @returns {Promise<{ok:boolean, durationMs:number, before:Object, after:Object, dir:string}>}
|
|
487
|
+
*/
|
|
488
|
+
async compact() {
|
|
489
|
+
this._assertReady();
|
|
490
|
+
const t = Date.now();
|
|
491
|
+
const sizeOf = (f) => { try { return fs.statSync(f).size; } catch { return 0; } };
|
|
492
|
+
const before = {
|
|
493
|
+
nodeLines: this._nodeLines,
|
|
494
|
+
edgeLines: this._edgeLines,
|
|
495
|
+
nodesMB: +(sizeOf(this.fileNodes) / 1048576).toFixed(1),
|
|
496
|
+
edgesMB: +(sizeOf(this.fileEdges) / 1048576).toFixed(1),
|
|
497
|
+
alive: { nodes: this.nodes.size, edges: this.edgeMap.size },
|
|
498
|
+
};
|
|
499
|
+
this._flushPending();
|
|
500
|
+
this._compactNodesNow = true;
|
|
501
|
+
this._maybeCompact();
|
|
502
|
+
this._compactNodesNow = false;
|
|
503
|
+
if (this._traceLines > num(this.opts.traceMax, 200)) this._compactTrace();
|
|
504
|
+
this._writeIndexSnapshot();
|
|
505
|
+
const after = {
|
|
506
|
+
nodeLines: this._nodeLines,
|
|
507
|
+
edgeLines: this._edgeLines,
|
|
508
|
+
nodesMB: +(sizeOf(this.fileNodes) / 1048576).toFixed(1),
|
|
509
|
+
edgesMB: +(sizeOf(this.fileEdges) / 1048576).toFixed(1),
|
|
510
|
+
alive: { nodes: this.nodes.size, edges: this.edgeMap.size },
|
|
511
|
+
};
|
|
512
|
+
const out = { ok: true, durationMs: Date.now() - t, before, after, dir: this.dir };
|
|
513
|
+
this._log('info', `compact: nodeLines ${before.nodeLines} -> ${after.nodeLines}, ${before.nodesMB}MB -> ${after.nodesMB}MB in ${out.durationMs}ms`);
|
|
514
|
+
return out;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* 自动压缩调度:追加行数超过 存活×autoCompactRatio 时,延迟 autoCompactDelayMs 执行。
|
|
519
|
+
* 压缩只重写存活集(亚秒级),不阻塞当前请求;阈值防抖保证一次写突发只压一次。
|
|
520
|
+
*/
|
|
521
|
+
_scheduleAutoCompact() {
|
|
522
|
+
if (this._autoCompactTimer || this._closed) return;
|
|
523
|
+
const ratio = num(this.opts.autoCompactRatio, 2.5);
|
|
524
|
+
if (ratio <= 0) return; // 0 = 关闭
|
|
525
|
+
if (this._nodeLines <= Math.max(200, this.nodes.size * ratio)) return;
|
|
526
|
+
this._autoCompactTimer = setTimeout(() => {
|
|
527
|
+
this._autoCompactTimer = null;
|
|
528
|
+
if (this._closed || !this._ready) return;
|
|
529
|
+
try {
|
|
530
|
+
this._flushPending();
|
|
531
|
+
this._compactNodesNow = true;
|
|
532
|
+
this._maybeCompact();
|
|
533
|
+
this._compactNodesNow = false;
|
|
534
|
+
if (this._traceLines > num(this.opts.traceMax, 200)) this._compactTrace();
|
|
535
|
+
this._writeIndexSnapshot();
|
|
536
|
+
this._log('info', `auto-compact done: nodeLines=${this._nodeLines} nodes=${this.nodes.size}`);
|
|
537
|
+
} catch (e) {
|
|
538
|
+
this._log('warn', `auto-compact failed: ${e.message}`);
|
|
539
|
+
}
|
|
540
|
+
}, Math.max(0, num(this.opts.autoCompactDelayMs, 5000)));
|
|
541
|
+
this._autoCompactTimer.unref?.();
|
|
542
|
+
}
|
|
543
|
+
|
|
479
544
|
// -- 写入 -----------------------------------------------------------------
|
|
480
545
|
|
|
481
546
|
/**
|
|
@@ -1530,6 +1595,7 @@ class NebulaMemory {
|
|
|
1530
1595
|
this._raw.set(n.id, rec);
|
|
1531
1596
|
this._nodeLines++;
|
|
1532
1597
|
this._writesSinceIndex++;
|
|
1598
|
+
this._scheduleAutoCompact();
|
|
1533
1599
|
}
|
|
1534
1600
|
|
|
1535
1601
|
_addEdge(a, b, weight, meta = {}) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nebula-memory-mcp",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"mcpName": "io.github.yb-zhai/nebula-memory",
|
|
5
5
|
"description": "Zero-dependency local Agent memory MCP Server (stdio JSON-RPC). Works offline, no API keys, no database. Exposes remember/recall/stats/forget to Claude Desktop, Cursor, ChatGPT and any MCP client.",
|
|
6
6
|
"type": "module",
|