@mebular/mcp 0.2.2 → 0.2.4
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/bin/mebular.mjs +145 -15
- package/package.json +3 -3
- package/src/admin.mjs +7 -8
- package/src/clients.mjs +472 -34
- package/src/config-schema.mjs +0 -2
- package/src/config.mjs +110 -23
- package/src/home-identity.mjs +389 -0
- package/src/profiles.mjs +18 -1
- package/src/provision.mjs +80 -19
- package/src/runtime-supervisor.mjs +24 -0
- package/src/serve.mjs +34 -1
- package/src/server.mjs +20 -5
- package/src/tools.mjs +20 -17
- package/src/version.mjs +1 -1
package/src/provision.mjs
CHANGED
|
@@ -12,7 +12,13 @@ import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
|
12
12
|
import { createServer } from 'node:net';
|
|
13
13
|
import { hostname } from 'node:os';
|
|
14
14
|
import { dirname, join, resolve } from 'node:path';
|
|
15
|
-
import { configPath, resolveMasterKeys } from './config.mjs';
|
|
15
|
+
import { configPath, readMasterKeyRecord, resolveMasterKeys } from './config.mjs';
|
|
16
|
+
import {
|
|
17
|
+
assertFreshStore,
|
|
18
|
+
createIdentityForStorage,
|
|
19
|
+
identityPathFor,
|
|
20
|
+
readIdentityFile,
|
|
21
|
+
} from './home-identity.mjs';
|
|
16
22
|
import {
|
|
17
23
|
DEFAULT_PROFILE_NAME,
|
|
18
24
|
masterFingerprintForHome,
|
|
@@ -123,8 +129,13 @@ const PROVISION_STATE_PATHS = [
|
|
|
123
129
|
* P1:create/join 的落盘事务快照。热初始化失败时只删除**本次新建**的文件,
|
|
124
130
|
* 不触碰调用前已存在的任何内容(home 锁始终由当前进程持有)。
|
|
125
131
|
*/
|
|
126
|
-
export async function snapshotProvisionState(home) {
|
|
132
|
+
export async function snapshotProvisionState(home, { storagePath } = {}) {
|
|
127
133
|
const paths = new Set(PROVISION_STATE_PATHS.map((rel) => join(home, rel)));
|
|
134
|
+
const effectiveStorage = typeof storagePath === 'string' && storagePath.length > 0
|
|
135
|
+
? storagePath
|
|
136
|
+
: join(home, 'store.jsonl');
|
|
137
|
+
paths.add(identityPathFor(effectiveStorage));
|
|
138
|
+
paths.add(`${configPath(home)}.identity-legacy.bak`);
|
|
128
139
|
paths.add(configPath(home));
|
|
129
140
|
const cloud = resolveCloudRoot({ home, env: process.env });
|
|
130
141
|
if (cloud.available) {
|
|
@@ -235,16 +246,21 @@ async function writeConfigFile(home, config) {
|
|
|
235
246
|
* 写引导态 config.json(create/restore 共用)。调用方必须已确保 `<home>/user-master-key.json` 存在
|
|
236
247
|
* (create 由 resolveMasterKeys 生成;restore 由备份解密落盘)。
|
|
237
248
|
*/
|
|
238
|
-
async function writeInitialProvisionConfig({ home, deviceName, deviceId, mcpPort, joinPort, listenPort, action = 'create', notes = [] }) {
|
|
249
|
+
async function writeInitialProvisionConfig({ home, storagePath, deviceName, deviceId, mcpPort, joinPort, listenPort, action = 'create', notes = [] }) {
|
|
239
250
|
const name = String(deviceName ?? '').trim() || defaultDeviceName();
|
|
240
|
-
|
|
251
|
+
// 调用方传入的身份值即权威;仅在缺省时按名字派生(保持旧内部契约)。
|
|
252
|
+
const id = String(deviceId ?? '').trim() || deriveDeviceId(name);
|
|
253
|
+
// 与 isProvisionHome/createMebular 同序:env 覆盖 > <home>/store.jsonl。
|
|
254
|
+
const effectiveStorage = typeof storagePath === 'string' && storagePath.length > 0
|
|
255
|
+
? storagePath
|
|
256
|
+
: (process.env.MEBULAR_STORAGE_PATH ?? join(home, 'store.jsonl'));
|
|
241
257
|
// 端口预检(避免重启即失败):mcp 端口 = 当前引导服务端口(我们自己持有,无需探测)
|
|
242
258
|
const joinChoice = await findFreePort(Number(joinPort) > 0 ? Number(joinPort) : 4002);
|
|
243
259
|
const listenChoice = await findFreePort(Number(listenPort) > 0 ? Number(listenPort) : 4001);
|
|
244
260
|
|
|
261
|
+
// F-IDENT-1:config 不写身份字段;deviceId/deviceName 由 <storagePath>.identity.json 提供。
|
|
245
262
|
const config = {
|
|
246
|
-
|
|
247
|
-
deviceName: name,
|
|
263
|
+
storagePath: effectiveStorage,
|
|
248
264
|
encryption: { level: 'none' },
|
|
249
265
|
network: {
|
|
250
266
|
enabled: true,
|
|
@@ -298,17 +314,30 @@ export async function provisionCreate({ home, cloudName, deviceName, deviceId, m
|
|
|
298
314
|
const registryBackupPath = cloud.available ? join(cloud.root, 'profiles.json.bak') : null;
|
|
299
315
|
const registryExisted = registryPath !== null && existsSync(registryPath);
|
|
300
316
|
const registryBackupExisted = registryBackupPath !== null && existsSync(registryBackupPath);
|
|
317
|
+
const storagePath = process.env.MEBULAR_STORAGE_PATH ?? join(home, 'store.jsonl');
|
|
318
|
+
const identityFile = identityPathFor(storagePath);
|
|
319
|
+
const identityExisted = existsSync(identityFile);
|
|
301
320
|
try {
|
|
321
|
+
// 缺身份但 store 已有数据 = 自动换钥风险:先拒绝,绝不写主密钥/配置。
|
|
322
|
+
assertFreshStore(storagePath);
|
|
302
323
|
const master = await resolveMasterKeys(home, {});
|
|
303
324
|
if (master.userMasterPrivateKey === undefined) {
|
|
304
325
|
const error = new Error('建新需要 root 主密钥(生成失败:未获得私钥)');
|
|
305
326
|
error.code = 'MASTER_KEY_FAILED';
|
|
306
327
|
throw error;
|
|
307
328
|
}
|
|
329
|
+
const identity = await createIdentityForStorage({
|
|
330
|
+
storagePath,
|
|
331
|
+
deviceId: normalizeExplicitDeviceId(deviceId) ?? deriveDeviceId(name),
|
|
332
|
+
deviceName: name,
|
|
333
|
+
userMasterPrivateKey: master.userMasterPrivateKey,
|
|
334
|
+
userMasterPublicKey: master.userMasterKey,
|
|
335
|
+
});
|
|
308
336
|
const result = await writeInitialProvisionConfig({
|
|
309
337
|
home,
|
|
310
|
-
|
|
311
|
-
|
|
338
|
+
storagePath,
|
|
339
|
+
deviceName: identity.deviceName,
|
|
340
|
+
deviceId: identity.deviceId,
|
|
312
341
|
mcpPort,
|
|
313
342
|
joinPort,
|
|
314
343
|
listenPort,
|
|
@@ -340,6 +369,7 @@ export async function provisionCreate({ home, cloudName, deviceName, deviceId, m
|
|
|
340
369
|
} catch (error) {
|
|
341
370
|
if (!keyExisted) await rm(keyPath, { force: true }).catch(() => undefined);
|
|
342
371
|
if (!configExisted) await rm(cfgPath, { force: true }).catch(() => undefined);
|
|
372
|
+
if (!identityExisted) await rm(identityFile, { force: true }).catch(() => undefined);
|
|
343
373
|
if (registryPath !== null && !registryExisted) await rm(registryPath, { force: true }).catch(() => undefined);
|
|
344
374
|
if (registryBackupPath !== null && !registryBackupExisted) await rm(registryBackupPath, { force: true }).catch(() => undefined);
|
|
345
375
|
throw error;
|
|
@@ -370,6 +400,10 @@ export async function provisionRestore({ home, file, code, cloudName, deviceName
|
|
|
370
400
|
}
|
|
371
401
|
const fleet = await import('../../fleet/dist/index.js');
|
|
372
402
|
const keyPath = join(home, 'user-master-key.json');
|
|
403
|
+
const storagePath = process.env.MEBULAR_STORAGE_PATH ?? join(home, 'store.jsonl');
|
|
404
|
+
// 缺身份但 store 已有数据 = 自动换钥风险:写主密钥前先拒绝。
|
|
405
|
+
assertFreshStore(storagePath);
|
|
406
|
+
const transaction = await snapshotProvisionState(home, { storagePath });
|
|
373
407
|
let restored;
|
|
374
408
|
try {
|
|
375
409
|
restored = await fleet.restoreMasterKeyBackup({
|
|
@@ -384,12 +418,25 @@ export async function provisionRestore({ home, file, code, cloudName, deviceName
|
|
|
384
418
|
wrapped.code = 'RESTORE_FAILED';
|
|
385
419
|
throw wrapped;
|
|
386
420
|
}
|
|
387
|
-
const transaction = await snapshotProvisionState(home);
|
|
388
421
|
try {
|
|
422
|
+
const master = await readMasterKeyRecord(keyPath);
|
|
423
|
+
if (master.userMasterPrivateKey === undefined) {
|
|
424
|
+
const error = new Error('恢复失败:主密钥文件缺少私钥(无法签发设备身份)');
|
|
425
|
+
error.code = 'RESTORE_FAILED';
|
|
426
|
+
throw error;
|
|
427
|
+
}
|
|
428
|
+
const identity = await createIdentityForStorage({
|
|
429
|
+
storagePath,
|
|
430
|
+
deviceId: normalizeExplicitDeviceId(deviceId) ?? deriveDeviceId(name),
|
|
431
|
+
deviceName: name,
|
|
432
|
+
userMasterPrivateKey: master.userMasterPrivateKey,
|
|
433
|
+
userMasterPublicKey: master.userMasterKey,
|
|
434
|
+
});
|
|
389
435
|
const result = await writeInitialProvisionConfig({
|
|
390
436
|
home,
|
|
391
|
-
|
|
392
|
-
|
|
437
|
+
storagePath,
|
|
438
|
+
deviceName: identity.deviceName,
|
|
439
|
+
deviceId: identity.deviceId,
|
|
393
440
|
mcpPort,
|
|
394
441
|
joinPort,
|
|
395
442
|
listenPort,
|
|
@@ -456,11 +503,10 @@ async function resolveJoinPorts({ ports = {}, mcpPort, joinPort, listenPort }) {
|
|
|
456
503
|
return { mcp, join, listen };
|
|
457
504
|
}
|
|
458
505
|
|
|
459
|
-
function delegatedConfig({ home,
|
|
506
|
+
function delegatedConfig({ home, namespace, ports, peers = [] }) {
|
|
460
507
|
return {
|
|
461
508
|
storagePath: join(home, 'store.jsonl'),
|
|
462
|
-
deviceId
|
|
463
|
-
deviceName: name,
|
|
509
|
+
// F-IDENT-1:不写身份字段;deviceId/deviceName 由身份文件提供。
|
|
464
510
|
identity: { mode: 'delegated' },
|
|
465
511
|
encryption: { level: 'none', userMasterPublicKeyFile: join(home, 'master-key.json') },
|
|
466
512
|
network: {
|
|
@@ -508,6 +554,8 @@ export async function provisionJoinInto({
|
|
|
508
554
|
error.code = 'ALREADY_PROVISIONED';
|
|
509
555
|
throw error;
|
|
510
556
|
}
|
|
557
|
+
// 身份缺失但 store 已有数据 = 自动换钥风险:在写 config / 请求加入前拒绝。
|
|
558
|
+
assertFreshStore(join(home, 'store.jsonl'));
|
|
511
559
|
if (typeof token !== 'string' || token.trim().length === 0) {
|
|
512
560
|
const error = new Error('需要令牌文本(邀请面板生成的 base64 令牌)');
|
|
513
561
|
error.code = 'TOKEN_REQUIRED';
|
|
@@ -540,7 +588,7 @@ export async function provisionJoinInto({
|
|
|
540
588
|
};
|
|
541
589
|
|
|
542
590
|
// 预写 config:兑换前完成本机落盘(端口复用当前忆云;准备阶段不 bind)。
|
|
543
|
-
await writeConfigFile(home, delegatedConfig({ home,
|
|
591
|
+
await writeConfigFile(home, delegatedConfig({ home, namespace, ports: resolvedPorts }));
|
|
544
592
|
|
|
545
593
|
let joined;
|
|
546
594
|
try {
|
|
@@ -548,6 +596,7 @@ export async function provisionJoinInto({
|
|
|
548
596
|
dir: home,
|
|
549
597
|
token: token.trim(),
|
|
550
598
|
device: id,
|
|
599
|
+
deviceName: name,
|
|
551
600
|
namespace,
|
|
552
601
|
listen: `/ip4/0.0.0.0/tcp/${resolvedPorts.listen}`,
|
|
553
602
|
agents: [{ name: 'echo', kind: 'echo' }],
|
|
@@ -579,21 +628,33 @@ export async function provisionJoinInto({
|
|
|
579
628
|
const masterKeyPublic = join(home, 'master-key.json');
|
|
580
629
|
const fingerprint = typeof joined.fingerprint === 'string' ? joined.fingerprint : null;
|
|
581
630
|
try {
|
|
582
|
-
|
|
631
|
+
// 加入后身份文件必须可用且与请求一致——config 与档案都只引用身份提供的 deviceId。
|
|
632
|
+
const identity = readIdentityFile(join(home, 'store.jsonl'));
|
|
633
|
+
if (identity.status !== 'valid') {
|
|
634
|
+
const error = new Error(`加入后身份文件不可用:${identity.path}`);
|
|
635
|
+
error.code = 'IDENTITY_INVALID';
|
|
636
|
+
throw error;
|
|
637
|
+
}
|
|
638
|
+
if (identity.deviceId !== id) {
|
|
639
|
+
const error = new Error(`加入后身份 ${identity.deviceId} 与请求 ${id} 不一致`);
|
|
640
|
+
error.code = 'IDENTITY_MISMATCH';
|
|
641
|
+
throw error;
|
|
642
|
+
}
|
|
643
|
+
const path = await writeConfigFile(home, delegatedConfig({ home, namespace, ports: resolvedPorts, peers }));
|
|
583
644
|
const profile = registerCurrentProfile
|
|
584
645
|
? await writeInitialProfile({
|
|
585
646
|
home,
|
|
586
647
|
name: profileName,
|
|
587
648
|
kind: 'delegated',
|
|
588
|
-
deviceId:
|
|
649
|
+
deviceId: identity.deviceId,
|
|
589
650
|
masterFingerprint: fingerprint,
|
|
590
651
|
})
|
|
591
652
|
: { written: false, reason: 'not_current_profile' };
|
|
592
653
|
return {
|
|
593
654
|
ok: true,
|
|
594
655
|
action: 'join',
|
|
595
|
-
deviceId:
|
|
596
|
-
deviceName:
|
|
656
|
+
deviceId: identity.deviceId,
|
|
657
|
+
deviceName: identity.deviceName,
|
|
597
658
|
inviterDeviceId: parsed.inviterDeviceId,
|
|
598
659
|
namespace,
|
|
599
660
|
hinted: joined.hinted,
|
|
@@ -29,6 +29,7 @@ import {
|
|
|
29
29
|
readRegistry,
|
|
30
30
|
resolveCloudRoot,
|
|
31
31
|
} from './profiles.mjs';
|
|
32
|
+
import { prepareHomeIdentity } from './home-identity.mjs';
|
|
32
33
|
import { readRuntimeFile, runtimePath } from './runtime-file.mjs';
|
|
33
34
|
import {
|
|
34
35
|
readRuntimeProviders,
|
|
@@ -1146,6 +1147,29 @@ async function inspectRuntime(options = {}) {
|
|
|
1146
1147
|
}
|
|
1147
1148
|
}
|
|
1148
1149
|
|
|
1150
|
+
// F-IDENT-1:spawn/service 之前完成身份 preflight——无效身份或「身份缺失 + 非空 store」
|
|
1151
|
+
// 以明确 reason fail closed,而不是 child 退出后只剩 unreachable。
|
|
1152
|
+
const homeConfig = await readHomeConfig(context.home);
|
|
1153
|
+
const identity = prepareHomeIdentity({ home: context.home, config: homeConfig, env });
|
|
1154
|
+
if (!identity.ok) {
|
|
1155
|
+
const result = baseResult(context, { http, checkedAt });
|
|
1156
|
+
result.ok = false;
|
|
1157
|
+
result.mode = 'error';
|
|
1158
|
+
result.reason = identity.status === 'invalid'
|
|
1159
|
+
? 'identity_invalid'
|
|
1160
|
+
: identity.status === 'occupied'
|
|
1161
|
+
? 'identity_store_occupied'
|
|
1162
|
+
: 'identity_mismatch';
|
|
1163
|
+
result.code = identity.code ?? null;
|
|
1164
|
+
result.message = identity.message;
|
|
1165
|
+
result.identity = {
|
|
1166
|
+
status: identity.status,
|
|
1167
|
+
path: identity.identityPath ?? null,
|
|
1168
|
+
...(identity.problems ? { problems: identity.problems } : {}),
|
|
1169
|
+
};
|
|
1170
|
+
return result;
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1149
1173
|
const probeHealth = probeHealthFn
|
|
1150
1174
|
?? ((target, probeOptions) => probeRuntimeHealth(fetchImpl, target, probeOptions));
|
|
1151
1175
|
let health;
|
package/src/serve.mjs
CHANGED
|
@@ -1341,6 +1341,7 @@ export async function startHttpServer({
|
|
|
1341
1341
|
/^\/admin\/api\/security\/recovery\/(generate|rotate)$/,
|
|
1342
1342
|
/^\/admin\/api\/namespaces\/([^/]+)\/(rejoin|leave)$/,
|
|
1343
1343
|
/^\/admin\/api\/service\/(install|uninstall)$/,
|
|
1344
|
+
/^\/admin\/api\/repair$/,
|
|
1344
1345
|
/^\/admin\/api\/clients\/([^/]+)\/(connect|rollback|skills|preview|verify|recheck)$/,
|
|
1345
1346
|
/^\/admin\/api\/assistants$/,
|
|
1346
1347
|
/^\/admin\/api\/assistants\/([^/]+)$/,
|
|
@@ -1859,6 +1860,24 @@ export async function startHttpServer({
|
|
|
1859
1860
|
}
|
|
1860
1861
|
}
|
|
1861
1862
|
|
|
1863
|
+
// 设置 · 常用「自动修复」:只重跑客户端接入(MCP 条目 + Skill),不碰 memory/identity/cloud/task/audit。
|
|
1864
|
+
async function handleRepair(req, res) {
|
|
1865
|
+
const { repairClients, assistantUserHome, daemonMcpUrl } = await import('./clients.mjs');
|
|
1866
|
+
const mcpUrl = daemonMcpUrl({ host: req.headers?.host, encrypted: Boolean(req.socket?.encrypted) });
|
|
1867
|
+
try {
|
|
1868
|
+
const result = await repairClients({ home, cwd: process.cwd(), mcpUrl, userHome: assistantUserHome() });
|
|
1869
|
+
// 逐项失败也是有效结果:200 + per-client report,由 UI 展示摘要。
|
|
1870
|
+
return sendJson(res, 200, result);
|
|
1871
|
+
} catch (error) {
|
|
1872
|
+
return sendJson(res, 500, {
|
|
1873
|
+
ok: false,
|
|
1874
|
+
scope: 'client-integration',
|
|
1875
|
+
error: 'repair_failed',
|
|
1876
|
+
message: `自动修复失败:${String(error?.message ?? error)}`,
|
|
1877
|
+
});
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1862
1881
|
// D2 写端点实现(memory.admin scope + CSRF 已在 handleAdminWrite 校验)
|
|
1863
1882
|
async function applyAdminWrite(req, res, path, body) {
|
|
1864
1883
|
if (!app || !service) {
|
|
@@ -1874,6 +1893,9 @@ export async function startHttpServer({
|
|
|
1874
1893
|
if (path === '/admin/api/clouds/join') return handleCloudJoin(req, res, body);
|
|
1875
1894
|
if (path === '/admin/api/clouds/rename') return handleCloudRename(req, res, body);
|
|
1876
1895
|
|
|
1896
|
+
// 自动修复:客户端接入修复,**不**经 securityWriteGate(不写记忆/安全状态)。
|
|
1897
|
+
if (path === '/admin/api/repair') return handleRepair(req, res);
|
|
1898
|
+
|
|
1877
1899
|
// S2:安全三档写端点门禁(medium 动态码 / high 会签或恢复码;low 放行)。
|
|
1878
1900
|
const gateInput = parseJsonBody(body) ?? {};
|
|
1879
1901
|
const gate = await securityWriteGate({ app, home, path, input: gateInput, namespace });
|
|
@@ -3204,7 +3226,9 @@ export async function startHttpServer({
|
|
|
3204
3226
|
phase = 'INITIALIZING';
|
|
3205
3227
|
let transaction = null;
|
|
3206
3228
|
try {
|
|
3207
|
-
transaction = await snapshotProvisionState(home
|
|
3229
|
+
transaction = await snapshotProvisionState(home, {
|
|
3230
|
+
storagePath: process.env.MEBULAR_STORAGE_PATH ?? join(home, 'store.jsonl'),
|
|
3231
|
+
});
|
|
3208
3232
|
const result = action === 'create'
|
|
3209
3233
|
? await provisionCreate({
|
|
3210
3234
|
home,
|
|
@@ -3252,6 +3276,15 @@ export async function startHttpServer({
|
|
|
3252
3276
|
},
|
|
3253
3277
|
});
|
|
3254
3278
|
await activateRuntime(next, { viaHotInit: true });
|
|
3279
|
+
// 首次初始化成功:对已检测到的客户端 ensure Skill(后台执行;失败不阻断初始化响应)。
|
|
3280
|
+
void import('./clients.mjs')
|
|
3281
|
+
.then(({ autoEnsureSkills, assistantUserHome }) => autoEnsureSkills({ home, userHome: assistantUserHome(), cwd: process.cwd() }))
|
|
3282
|
+
.then((result) => {
|
|
3283
|
+
if (result?.summary?.failed > 0 || (result?.ok === false && result?.skipped !== true)) {
|
|
3284
|
+
console.error(`SKILL_ENSURE_PENDING_REPAIR ${result?.reason ?? `${result?.summary?.failed ?? 1} client(s)`}`);
|
|
3285
|
+
}
|
|
3286
|
+
})
|
|
3287
|
+
.catch((error) => console.error(`SKILL_ENSURE_FAILED ${error?.code ?? 'ERROR'}`));
|
|
3255
3288
|
return sendJson(res, 200, {
|
|
3256
3289
|
ok: true,
|
|
3257
3290
|
...result,
|
package/src/server.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// MCP server 装配(G6.2 + R1):stdio 传输 + **
|
|
1
|
+
// MCP server 装配(G6.2 + R1):stdio 传输 + **29 工具**(记忆 13 + 任务 16)+ memory_policy prompt。
|
|
2
2
|
// 全部委托 MemoryService(D33 单一实现)。
|
|
3
3
|
|
|
4
4
|
import { McpServer } from '@modelcontextprotocol/server';
|
|
@@ -26,8 +26,15 @@ const MEMORY_POLICY = `# Mebular 记忆使用规约(memory_policy)
|
|
|
26
26
|
5. 隐私:不要写入密钥、口令、完整身份证件等高敏感信息。
|
|
27
27
|
6. 无结果别编:召回为空就如实说明,不要臆造记忆。`;
|
|
28
28
|
|
|
29
|
+
/** MCP initialize 返回的全局行为说明(不替代 memory_policy prompt)。 */
|
|
30
|
+
export const MCP_INSTRUCTIONS = `Mebular 是本地优先的图式记忆与任务协作层。
|
|
31
|
+
1. 先查后写:写入记忆前先用 memory_query/memory_search 查重;只写可复用的稳定事实/偏好,不要把一次会话的过程产物当跨设备记忆。
|
|
32
|
+
2. 任务派发前先 task_targets 确认可派对象,再 task_submit;非幂等/失败重试的语义以工具描述为准。
|
|
33
|
+
3. 工具描述首行的「何时用」是首选路由信号;优先按它选择工具。`;
|
|
34
|
+
|
|
29
35
|
export function buildServer(service, options = {}) {
|
|
30
|
-
|
|
36
|
+
// McpServer(serverInfo, options):instructions 必须放在第二参数,initialize/discover 才会下发。
|
|
37
|
+
const server = new McpServer({ name: 'mebular', version: APP_VERSION }, { instructions: MCP_INSTRUCTIONS });
|
|
31
38
|
registerTools(server, service, options);
|
|
32
39
|
server.registerPrompt(
|
|
33
40
|
'memory_policy',
|
|
@@ -140,9 +147,8 @@ export async function startServeServer(options = {}) {
|
|
|
140
147
|
// F-NET-1(C):**先取单实例锁,再初始化网络**——第二写者应在绑定监听端口前就得到
|
|
141
148
|
// 可读的 MCP_STORAGE_LOCKED(此前 createMebular 先启网络 → 抢 4001 → 裸 EADDRINUSE)。
|
|
142
149
|
const preConfig = provisionStart ? {} : await loadConfigFile(home).catch(() => ({}));
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
?? join(home, (preConfig.storageAdapter ?? 'json') === 'sqlite' ? 'store.sqlite' : 'store.jsonl');
|
|
150
|
+
const { storagePathForHome } = await import('./home-identity.mjs');
|
|
151
|
+
const preStoragePath = storagePathForHome(home, preConfig, process.env);
|
|
146
152
|
const lock = await acquireLock(home, preStoragePath);
|
|
147
153
|
|
|
148
154
|
// 热初始化 / 正常启动共用:app、join 服务、运行时快照与生命周期资源。
|
|
@@ -389,6 +395,15 @@ export async function startServeServer(options = {}) {
|
|
|
389
395
|
current.runtime.mcp.auth = httpServer.auth;
|
|
390
396
|
// G:装配完成后写「已监听」标记——supervisor 用它判定新实例健康(join 失败则不写)
|
|
391
397
|
await finalizeRuntime(current);
|
|
398
|
+
// Skill 收敛(启动/升级):受管旧版更新、用户修改保留;失败只记录,绝不阻断 serve。
|
|
399
|
+
void import('./clients.mjs')
|
|
400
|
+
.then(({ autoEnsureSkills, assistantUserHome }) => autoEnsureSkills({ home, userHome: assistantUserHome(), cwd: process.cwd() }))
|
|
401
|
+
.then((result) => {
|
|
402
|
+
if (result?.summary?.failed > 0 || (result?.ok === false && result?.skipped !== true)) {
|
|
403
|
+
console.error(`SKILL_ENSURE_PENDING_REPAIR ${result?.reason ?? `${result?.summary?.failed ?? 1} client(s)`}`);
|
|
404
|
+
}
|
|
405
|
+
})
|
|
406
|
+
.catch((error) => console.error(`SKILL_ENSURE_FAILED ${error?.code ?? 'ERROR'}`));
|
|
392
407
|
}
|
|
393
408
|
|
|
394
409
|
const shutdown = async () => {
|
package/src/tools.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// MCP 工具面(G6.2 / D35 + R1 统一入口):**
|
|
1
|
+
// MCP 工具面(G6.2 / D35 + R1 统一入口):**29 个** agent 中立工具 = 记忆 13(薄壳委托 MemoryService)
|
|
2
2
|
// + 任务 16(复用 @mebular/fleet 的 TASK_TOOLS handler;同 handler 不复制)。
|
|
3
3
|
//
|
|
4
4
|
// 钳制:limit ≤ 50(默认 10)、depth ≤ 5、batch ≤ 100。
|
|
@@ -90,12 +90,15 @@ const namespaceFilter = z.union([z.string(), z.array(z.string())]).optional();
|
|
|
90
90
|
|
|
91
91
|
const internalTypes = z.array(z.enum(['fact', 'episode', 'skill', 'preference', 'observation']));
|
|
92
92
|
|
|
93
|
+
/** 工具描述首行 = 首要路由信号「何时用」;原始语义/约束保留在第二行。 */
|
|
94
|
+
const when = (whenToUse, description) => `何时用:${whenToUse}\n${description}`;
|
|
95
|
+
|
|
93
96
|
/** 工具注册表:handler(service, args) → MCP 结果对象(CLI 直接取 `structuredContent`)。 */
|
|
94
97
|
export const TOOL_SPECS = [
|
|
95
98
|
{
|
|
96
99
|
name: 'memory_write',
|
|
97
100
|
title: '写入记忆',
|
|
98
|
-
description: '写入单条记忆(fact/episode/skill/preference/observation)',
|
|
101
|
+
description: when('需要把用户明确、可复用的稳定事实/偏好写入长期记忆时;先查后写,用 memory_query/memory_search 查重。', '写入单条记忆(fact/episode/skill/preference/observation)'),
|
|
99
102
|
inputSchema: z.object({ items: z.array(memoryInputSchema).min(1) }),
|
|
100
103
|
handler: async (service, { items }) => {
|
|
101
104
|
try {
|
|
@@ -108,7 +111,7 @@ export const TOOL_SPECS = [
|
|
|
108
111
|
{
|
|
109
112
|
name: 'memory_write_batch',
|
|
110
113
|
title: '批量写入记忆',
|
|
111
|
-
description: `批量写入记忆(最多 ${MAX_BATCH}
|
|
114
|
+
description: when('一次会话结束有 2 条以上稳定事实/偏好要落库,且已查重时。', `批量写入记忆(最多 ${MAX_BATCH} 条)`),
|
|
112
115
|
inputSchema: z.object({ items: z.array(memoryInputSchema).min(1) }),
|
|
113
116
|
handler: async (service, { items }) => {
|
|
114
117
|
if (items.length > MAX_BATCH) return fail(`批量写入超过上限:${items.length} > ${MAX_BATCH}`);
|
|
@@ -122,7 +125,7 @@ export const TOOL_SPECS = [
|
|
|
122
125
|
{
|
|
123
126
|
name: 'memory_query',
|
|
124
127
|
title: '查询记忆',
|
|
125
|
-
description: '语义/关键词召回(配置向量索引时走语义)',
|
|
128
|
+
description: when('回答前需要按语义召回已有记忆,或不确定某事实是否已记录时。', '语义/关键词召回(配置向量索引时走语义)'),
|
|
126
129
|
inputSchema: z.object({
|
|
127
130
|
query: z.string().optional(),
|
|
128
131
|
types: internalTypes.optional(),
|
|
@@ -161,7 +164,7 @@ export const TOOL_SPECS = [
|
|
|
161
164
|
{
|
|
162
165
|
name: 'memory_search',
|
|
163
166
|
title: '关键词搜索',
|
|
164
|
-
description: '关键词检索基线,可选一跳关系',
|
|
167
|
+
description: when('已知关键词/专有名词,需要精确检索或查重时(比 memory_query 更可控)。', '关键词检索基线,可选一跳关系'),
|
|
165
168
|
inputSchema: z.object({
|
|
166
169
|
query: z.string(),
|
|
167
170
|
types: z.array(z.string()).optional(),
|
|
@@ -196,7 +199,7 @@ export const TOOL_SPECS = [
|
|
|
196
199
|
{
|
|
197
200
|
name: 'memory_profile',
|
|
198
201
|
title: '用户画像',
|
|
199
|
-
description: '返回用户偏好与属性(默认不含已归档)',
|
|
202
|
+
description: when('需要用户偏好/属性做个性化回答,或判断写入是否符合用户约束时。', '返回用户偏好与属性(默认不含已归档)'),
|
|
200
203
|
inputSchema: z.object({ includeArchived: z.boolean().optional() }),
|
|
201
204
|
handler: async (service, args) => {
|
|
202
205
|
try {
|
|
@@ -209,7 +212,7 @@ export const TOOL_SPECS = [
|
|
|
209
212
|
{
|
|
210
213
|
name: 'memory_skills',
|
|
211
214
|
title: '技能列表',
|
|
212
|
-
description: '按分类/关键词/标签筛选技能',
|
|
215
|
+
description: when('需要复用已有技能步骤,或查找某类可复用流程时。', '按分类/关键词/标签筛选技能'),
|
|
213
216
|
inputSchema: z.object({
|
|
214
217
|
category: z.string().optional(),
|
|
215
218
|
search: z.string().optional(),
|
|
@@ -233,7 +236,7 @@ export const TOOL_SPECS = [
|
|
|
233
236
|
{
|
|
234
237
|
name: 'memory_history',
|
|
235
238
|
title: '会话历史',
|
|
236
|
-
description: '按会话/时间/主题筛选会话情节',
|
|
239
|
+
description: when('需要回看某次会话/任务过程,而不是稳定事实时。', '按会话/时间/主题筛选会话情节'),
|
|
237
240
|
inputSchema: z.object({
|
|
238
241
|
sessionIds: z.array(z.string()).optional(),
|
|
239
242
|
startTime: z.number().optional(),
|
|
@@ -262,7 +265,7 @@ export const TOOL_SPECS = [
|
|
|
262
265
|
{
|
|
263
266
|
name: 'memory_graph',
|
|
264
267
|
title: '图遍历',
|
|
265
|
-
description: `从起点遍历(深度 ≤ ${MAX_DEPTH}
|
|
268
|
+
description: when('需要沿关系边查上下文(相关实体/事实/技能)时。', `从起点遍历(深度 ≤ ${MAX_DEPTH})`),
|
|
266
269
|
inputSchema: z.object({
|
|
267
270
|
startId: z.string(),
|
|
268
271
|
direction: z.enum(['outgoing', 'incoming', 'both']).optional(),
|
|
@@ -288,7 +291,7 @@ export const TOOL_SPECS = [
|
|
|
288
291
|
{
|
|
289
292
|
name: 'memory_import',
|
|
290
293
|
title: '导入记忆',
|
|
291
|
-
description: '经适配器导入异构来源(kv/markdown/…)',
|
|
294
|
+
description: when('从外部 kv/markdown 等来源一次性导入历史记忆时。', '经适配器导入异构来源(kv/markdown/…)'),
|
|
292
295
|
inputSchema: z.object({ kind: z.string().optional(), data: z.unknown(), origin: z.string().optional() }),
|
|
293
296
|
handler: async (service, args) => {
|
|
294
297
|
try {
|
|
@@ -305,7 +308,7 @@ export const TOOL_SPECS = [
|
|
|
305
308
|
{
|
|
306
309
|
name: 'memory_status',
|
|
307
310
|
title: '记忆状态',
|
|
308
|
-
description: '返回设备/网络/计数/状态哈希/开关',
|
|
311
|
+
description: when('接入、排障或需要确认设备/网络/计数/状态哈希/开关时。', '返回设备/网络/计数/状态哈希/开关'),
|
|
309
312
|
inputSchema: z.object({}),
|
|
310
313
|
handler: async (service) => {
|
|
311
314
|
try {
|
|
@@ -318,7 +321,7 @@ export const TOOL_SPECS = [
|
|
|
318
321
|
{
|
|
319
322
|
name: 'memory_sync',
|
|
320
323
|
title: '同步对端',
|
|
321
|
-
description: '连接对端并等待一次双向同步(network.enabled 需为 true)',
|
|
324
|
+
description: when('需要立即拉取/推送某个对端,而不是等待自动同步时(network.enabled 需为 true)。', '连接对端并等待一次双向同步(network.enabled 需为 true)'),
|
|
322
325
|
inputSchema: z.object({ peerId: z.string(), address: z.string().optional() }),
|
|
323
326
|
handler: async (service, args) => {
|
|
324
327
|
try {
|
|
@@ -332,7 +335,7 @@ export const TOOL_SPECS = [
|
|
|
332
335
|
{
|
|
333
336
|
name: 'memory_delete',
|
|
334
337
|
title: '删除记忆',
|
|
335
|
-
description: '删除记忆:写墓碑(deletedAt)并随图事件同步到各端;删除后默认不再出现在任何召回。不可逆动作(对端已拷贝的旧快照无法强制回收)。需 memory.admin。',
|
|
338
|
+
description: when('确认内容要永久墓碑删除、且接受不可逆时;不确定时先用 memory_archive。', '删除记忆:写墓碑(deletedAt)并随图事件同步到各端;删除后默认不再出现在任何召回。不可逆动作(对端已拷贝的旧快照无法强制回收)。需 memory.admin。'),
|
|
336
339
|
inputSchema: z.object({ ids: z.array(z.string()).min(1) }),
|
|
337
340
|
handler: async (service, args) => {
|
|
338
341
|
try {
|
|
@@ -345,7 +348,7 @@ export const TOOL_SPECS = [
|
|
|
345
348
|
{
|
|
346
349
|
name: 'memory_archive',
|
|
347
350
|
title: '归档 / 解除归档记忆',
|
|
348
|
-
description: '归档记忆:打 metadata.archivedAt 标记(随图同步、无损、可逆),归档后默认不进入召回;archived=false 解除归档。删除(墓碑)节点会被跳过。',
|
|
351
|
+
description: when('内容暂时不该参与召回但将来可能有用(可逆);要永久删除请用 memory_delete。', '归档记忆:打 metadata.archivedAt 标记(随图同步、无损、可逆),归档后默认不进入召回;archived=false 解除归档。删除(墓碑)节点会被跳过。'),
|
|
349
352
|
inputSchema: z.object({ ids: z.array(z.string()).min(1), archived: z.boolean().optional() }),
|
|
350
353
|
handler: async (service, args) => {
|
|
351
354
|
try {
|
|
@@ -357,13 +360,13 @@ export const TOOL_SPECS = [
|
|
|
357
360
|
},
|
|
358
361
|
];
|
|
359
362
|
|
|
360
|
-
/** 统一工具注册表(记忆
|
|
363
|
+
/** 统一工具注册表(记忆 13 + 任务 16 = 29):`mebular mcp`(stdio)与 HTTP `/mcp` 都注册这一份。 */
|
|
361
364
|
export const ALL_TOOL_SPECS = [...TOOL_SPECS, ...TASK_TOOL_SPECS];
|
|
362
365
|
|
|
363
|
-
/** 统一工具名(
|
|
366
|
+
/** 统一工具名(29)——控制台「能力清单」与 CLI `mebular tools` 同源。 */
|
|
364
367
|
export const TOOL_NAMES = ALL_TOOL_SPECS.map((spec) => spec.name);
|
|
365
368
|
|
|
366
|
-
/** 统一 scope 表(记忆 + 任务,
|
|
369
|
+
/** 统一 scope 表(记忆 + 任务,29)。 */
|
|
367
370
|
export const TOOL_ALL_SCOPES = { ...TOOL_SCOPES, ...TASK_TOOL_SCOPES };
|
|
368
371
|
|
|
369
372
|
/** 工具名 → spec(记忆 + 任务;CLI 与 MCP 同 handler)。 */
|
package/src/version.mjs
CHANGED