@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 CHANGED
@@ -187,21 +187,117 @@ async function runKeygen(flags) {
187
187
  console.error('(主私钥是信任根,请妥善保管;权限 0600)');
188
188
  }
189
189
 
190
+ function initError(message, code) {
191
+ const error = new Error(message);
192
+ error.code = code;
193
+ return error;
194
+ }
195
+
196
+ async function readInitJson(file, { label, code }) {
197
+ try {
198
+ const parsed = JSON.parse(await readFile(file, 'utf-8'));
199
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
200
+ throw new Error('顶层必须是对象');
201
+ }
202
+ return parsed;
203
+ } catch (error) {
204
+ throw initError(`${label}损坏:${file}(${error?.message ?? error})`, code);
205
+ }
206
+ }
207
+
190
208
  async function runInit(flags) {
191
209
  const home = homeDir();
192
210
  const configFile = join(home, 'config.json');
193
211
  const keyFile = join(home, 'user-master-key.json');
194
212
  await mkdir(home, { recursive: true });
195
213
 
196
- if (!existsSync(keyFile)) await runKeygen({ out: keyFile });
214
+ const config = existsSync(configFile)
215
+ ? await readInitJson(configFile, { label: 'config.json', code: 'CONFIG_INVALID' })
216
+ : null;
217
+ const storagePath = typeof config?.storagePath === 'string'
218
+ ? config.storagePath
219
+ : (typeof flags['storage'] === 'string' ? flags['storage'] : join(home, 'store.jsonl'));
220
+ const explicit = {
221
+ ...(typeof flags['device-id'] === 'string' && flags['device-id'].trim().length > 0
222
+ ? { deviceId: flags['device-id'].trim() }
223
+ : {}),
224
+ ...(typeof flags['device-name'] === 'string' && flags['device-name'].trim().length > 0
225
+ ? { deviceName: flags['device-name'].trim() }
226
+ : {}),
227
+ };
197
228
 
198
- if (existsSync(configFile)) {
229
+ const {
230
+ assertFreshStore,
231
+ cleanLegacyConfig,
232
+ createIdentity,
233
+ prepareIdentity,
234
+ } = await import('../src/home-identity.mjs');
235
+ const prepared = prepareIdentity({ config: config ?? {}, storagePath, explicit });
236
+ if (!prepared.ok) throw initError(prepared.message, prepared.code);
237
+ for (const warning of prepared.warnings) console.error(`warning: ${warning}`);
238
+
239
+ let identity = prepared.identity;
240
+ const { identityMode, readMasterKeyRecord } = await import('../src/config.mjs');
241
+ if (prepared.status === 'missing') {
242
+ // 缺身份但 store 已有数据 = 自动换钥风险:先拒绝,绝不写任何文件。
243
+ assertFreshStore(storagePath);
244
+ if (!existsSync(keyFile)) await runKeygen({ out: keyFile });
245
+ let master;
246
+ try {
247
+ master = await readMasterKeyRecord(keyFile);
248
+ } catch (error) {
249
+ throw initError(`主密钥文件损坏:${keyFile}(${error?.message ?? error})`, 'MASTER_KEY_INVALID');
250
+ }
251
+ if (!master.userMasterPrivateKey) {
252
+ throw initError(`主密钥文件缺少私钥:${keyFile}`, 'MASTER_KEY_INVALID');
253
+ }
254
+ const created = await createIdentity({
255
+ storagePath,
256
+ deviceId: identity.deviceId,
257
+ deviceName: identity.deviceName,
258
+ userMasterPrivateKey: master.userMasterPrivateKey,
259
+ userMasterPublicKey: master.userMasterKey,
260
+ });
261
+ identity = { deviceId: created.deviceId, deviceName: created.deviceName };
262
+ } else if (identityMode(home, config ?? {}, storagePath) === 'root') {
263
+ // 已有 root 身份但信任根缺失/损坏:init 不能假装成功,更不能生成新主密钥。
264
+ // 委派身份没有 root 主私钥是正常的,因此只对 root 校验。
265
+ const envInline = process.env.MEBULAR_USER_MASTER_KEY;
266
+ const keySource = envInline
267
+ ? envInline
268
+ : (process.env.MEBULAR_USER_MASTER_KEY_FILE
269
+ || (typeof config?.encryption?.keyFile === 'string' && config.encryption.keyFile.length > 0
270
+ ? config.encryption.keyFile
271
+ : keyFile));
272
+ if (!envInline && !existsSync(keySource)) {
273
+ throw initError(
274
+ `已有 root 身份,但缺少用户主密钥:${keySource}`
275
+ + '(不会自动生成新的信任根;请恢复原主密钥或从备份恢复)',
276
+ 'IDENTITY_TRUST_ROOT_MISSING',
277
+ );
278
+ }
279
+ let master;
280
+ try {
281
+ master = await readMasterKeyRecord(keySource);
282
+ } catch (error) {
283
+ throw initError(`主密钥文件损坏:${keySource}(${error?.message ?? error})`, 'MASTER_KEY_INVALID');
284
+ }
285
+ if (!master.userMasterPrivateKey) {
286
+ throw initError(`主密钥文件缺少私钥:${keySource}`, 'MASTER_KEY_INVALID');
287
+ }
288
+ }
289
+
290
+ if (config !== null) {
291
+ const migrated = await cleanLegacyConfig({ configPath: configFile, identity });
199
292
  console.log(`配置已存在,未覆盖:${configFile}`);
293
+ if (migrated.migrated) {
294
+ console.log(`已备份旧 config 身份字段:${migrated.backupPath},并以身份 ${identity.deviceId} 为准`);
295
+ }
200
296
  } else {
201
- const config = {
202
- storagePath: typeof flags['storage'] === 'string' ? flags['storage'] : join(home, 'store.jsonl'),
297
+ // F-IDENT-1:新 config 不写 deviceId/deviceName;身份文件是唯一权威。
298
+ const nextConfig = {
299
+ storagePath,
203
300
  storageAdapter: 'json',
204
- deviceId: typeof flags['device-id'] === 'string' ? flags['device-id'] : `device-${process.env.HOSTNAME ?? 'local'}`,
205
301
  encryption: { level: 'none', keyFile },
206
302
  network: { enabled: false, libp2p: { listen: [], relayServers: [], relayUnlimited: false } },
207
303
  // 常驻入口默认实时(写入即推 + 周期 anti-entropy);可显式关闭
@@ -209,8 +305,18 @@ async function runInit(flags) {
209
305
  semantic: { enabled: false, minScore: 0.2 },
210
306
  mcp: { http: { host: '127.0.0.1', port: 7331, auth: 'none', tls: false, tokensFile: join(home, 'auth', 'tokens.json') } },
211
307
  };
212
- await writeFile(configFile, JSON.stringify(config, null, 2), 'utf-8');
213
- console.log(`已写入配置:${configFile}`);
308
+ await writeFile(configFile, JSON.stringify(nextConfig, null, 2), 'utf-8');
309
+ console.log(`已写入配置:${configFile}(deviceId=${identity.deviceId},由身份文件提供)`);
310
+ }
311
+ // Skill 是部署产物:初始化成功后对已检测到的助手自动 ensure;失败只告警,不阻断 init。
312
+ try {
313
+ const { autoEnsureSkills, assistantUserHome } = await import('../src/clients.mjs');
314
+ const skills = await autoEnsureSkills({ home, userHome: assistantUserHome(), cwd: process.cwd() });
315
+ if (!skills.skipped && skills.summary?.total > 0) {
316
+ console.log(`Skill:安装 ${skills.summary.installed} · 更新 ${skills.summary.updated} · 保留 ${skills.summary.kept} · 失败 ${skills.summary.failed}`);
317
+ }
318
+ } catch (error) {
319
+ console.error(`warning: Skill 自动安装失败(不阻断初始化):${error?.message ?? error}`);
214
320
  }
215
321
  console.log(
216
322
  [
@@ -494,11 +600,13 @@ async function runNetDoctor() {
494
600
 
495
601
  async function runStatus() {
496
602
  const { loadConfigFile, homeDir: resolveHome, identityMode: resolveIdentityMode } = await import('../src/config.mjs');
603
+ const { readIdentityFile, storagePathForHome } = await import('../src/home-identity.mjs');
497
604
  const home = resolveHome();
498
605
  const configFile = await loadConfigFile(home).catch(() => ({}));
499
- const storagePath = process.env.MEBULAR_STORAGE_PATH
500
- ?? configFile.storagePath
501
- ?? join(home, (configFile.storageAdapter ?? 'json') === 'sqlite' ? 'store.sqlite' : 'store.jsonl');
606
+ const storagePath = storagePathForHome(home, configFile, process.env);
607
+ // F-IDENT-1:status 的 deviceId 只认身份文件;env/config 仅旧布局兜底(且仅用于展示)。
608
+ const identityRead = readIdentityFile(storagePath);
609
+ const identityDeviceId = identityRead.status === 'valid' ? identityRead.deviceId : null;
502
610
  // store 锁持有者(单写者证据)
503
611
  let storeLock = null;
504
612
  const lockPath = join(home, 'lock');
@@ -520,12 +628,19 @@ async function runStatus() {
520
628
  ok: true,
521
629
  running: true,
522
630
  reused: true,
523
- deviceId: process.env.MEBULAR_DEVICE_ID ?? configFile.deviceId ?? `device-${process.env.HOSTNAME ?? 'local'}`,
631
+ deviceId: identityDeviceId,
524
632
  peerId: null,
525
633
  nodeCount: null,
526
634
  stateHash: null,
527
635
  home,
528
636
  storagePath,
637
+ ...(identityDeviceId === null
638
+ ? {
639
+ identityError: identityRead.status === 'invalid'
640
+ ? { status: 'invalid', code: 'IDENTITY_INVALID', problems: identityRead.problems ?? [] }
641
+ : { status: identityRead.status, code: identityRead.status === 'missing' ? 'IDENTITY_MISSING' : null },
642
+ }
643
+ : {}),
529
644
  identityMode: resolveIdentityMode(home, configFile, storagePath),
530
645
  network: { enabled: configFile.network?.enabled ?? false, listen: configFile.network?.libp2p?.listen ?? [], reused: true },
531
646
  storeLock,
@@ -1586,7 +1701,7 @@ async function main() {
1586
1701
  ' token grant|list|revoke [--scope a,b] [--id x] [--tokens-file p] bearer 令牌管理',
1587
1702
  ' token client add|list|remove [--redirect uri] [--scope a,b] [--id x] OAuth 客户端预注册',
1588
1703
  ' token consent [--scope a,b] [--ttl sec] 生成一次性本地同意码(/authorize 用)',
1589
- ' init / keygen / print-config / status|doctor 初始化、状态与自检(身份模式/网络/锁/域/join)',
1704
+ ' init / keygen / print-config / status|doctor 初始化(已有身份时沿用其 deviceId)、状态与自检',
1590
1705
  ' doctor --net 网络排障:地址簿/路径状态 + relay 可达性 + 下一步建议',
1591
1706
  ' tools 打印 MCP 工具 ↔ CLI 对照表',
1592
1707
  ' memory_write|memory_write_batch|memory_query|memory_search|memory_profile|memory_skills|',
@@ -1596,7 +1711,12 @@ async function main() {
1596
1711
  process.exit(0);
1597
1712
  return;
1598
1713
  case 'init':
1599
- await runInit(flags);
1714
+ try {
1715
+ await runInit(flags);
1716
+ } catch (error) {
1717
+ console.error(`✗ init 失败(${error?.code ?? 'ERROR'}):${error?.message ?? error}`);
1718
+ process.exit(2);
1719
+ }
1600
1720
  return;
1601
1721
  case 'keygen':
1602
1722
  await runKeygen(flags);
@@ -1610,14 +1730,24 @@ async function main() {
1610
1730
  return;
1611
1731
  }
1612
1732
  case 'status':
1613
- await runStatus();
1733
+ try {
1734
+ await runStatus();
1735
+ } catch (error) {
1736
+ console.error(`✗ status 失败(${error?.code ?? 'ERROR'}):${error?.message ?? error}`);
1737
+ process.exit(2);
1738
+ }
1614
1739
  return;
1615
1740
  case 'doctor':
1616
1741
  if (flags.net === true || flags.net === 'true') {
1617
1742
  await runNetDoctor();
1618
1743
  return;
1619
1744
  }
1620
- await runStatus();
1745
+ try {
1746
+ await runStatus();
1747
+ } catch (error) {
1748
+ console.error(`✗ doctor 失败(${error?.code ?? 'ERROR'}):${error?.message ?? error}`);
1749
+ process.exit(2);
1750
+ }
1621
1751
  return;
1622
1752
  default: {
1623
1753
  const { toolByName } = await import('../src/tools.mjs');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mebular/mcp",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "Mebular MCP server(stdio + Streamable HTTP):把 Mebular 记忆能力暴露给任意 MCP client",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -29,9 +29,9 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@mebular/core": "^0.2.2",
32
+ "@mebular/core": "^0.2.4",
33
33
  "@modelcontextprotocol/server": "^2.3.1",
34
34
  "zod": "^4.6.7",
35
- "@mebular/fleet": "^0.2.2"
35
+ "@mebular/fleet": "^0.2.4"
36
36
  }
37
37
  }
package/src/admin.mjs CHANGED
@@ -408,7 +408,7 @@ export function collectOnlinePeers(app) {
408
408
  }
409
409
 
410
410
  /** GET /admin/api/overview */
411
- export async function buildOverview({ app, service, cloud, config, runtime }) {
411
+ export async function buildOverview({ app, service, cloud, runtime }) {
412
412
  const status = await service.status();
413
413
  const { peers } = collectOnlinePeers(app);
414
414
  let blockedCount = 0;
@@ -434,7 +434,6 @@ export async function buildOverview({ app, service, cloud, config, runtime }) {
434
434
  }
435
435
  const selfDeviceName = deviceNames[app.deviceId]?.name
436
436
  ?? runtime?.deviceName
437
- ?? config?.deviceName
438
437
  ?? null;
439
438
  // 忆云身份:旧守护无此字段 → 前端自行隐藏;注册表不可读时同样省略(不阻塞总览)。
440
439
  let cloudView = null;
@@ -608,19 +607,19 @@ export async function collectKnownDevices(app, policy, online) {
608
607
  }
609
608
 
610
609
  /** GET /admin/api/devices */
611
- export async function buildDevices({ app, config, runtime }) {
610
+ export async function buildDevices({ app, runtime }) {
612
611
  const self = app.deviceId;
613
612
  const online = collectOnlinePeers(app);
614
613
  const policy = await collectPolicy(app);
615
614
  const known = await collectKnownDevices(app, policy, online);
616
- // 设备名来自网络派生(本人可改);无事件时本机用 config/runtime 回退,其他设备只显示 deviceId。
615
+ // 设备名来自网络派生(本人可改);无事件时本机用 runtime(身份文件派生)回退,其他设备只显示 deviceId。
617
616
  let deviceNames = {};
618
617
  try {
619
618
  deviceNames = (await app.getDeviceNames?.()) ?? {};
620
619
  } catch {
621
620
  deviceNames = {};
622
621
  }
623
- const selfNameFallback = runtime?.deviceName ?? config?.deviceName ?? null;
622
+ const selfNameFallback = runtime?.deviceName ?? null;
624
623
 
625
624
  let syncStatus = null;
626
625
  try {
@@ -891,7 +890,7 @@ export async function buildSettings({ app, service, config, runtime, home }) {
891
890
  } catch {
892
891
  // 忽略:门面未就绪
893
892
  }
894
- // 设备名:网络派生优先;无共享事件时回退 config/runtime(旧安装迁移)。
893
+ // 设备名:网络派生优先;无共享事件时回退 runtime(身份文件派生)。
895
894
  let selfDeviceName = null;
896
895
  try {
897
896
  const names = (await app.getDeviceNames?.()) ?? {};
@@ -904,8 +903,8 @@ export async function buildSettings({ app, service, config, runtime, home }) {
904
903
  const payload = {
905
904
  identity: {
906
905
  deviceId: app.deviceId,
907
- name: selfDeviceName ?? runtime?.deviceName ?? config?.deviceName ?? null,
908
- nameSource: selfDeviceName ? 'network' : (runtime?.deviceName ?? config?.deviceName ? 'local' : null),
906
+ name: selfDeviceName ?? runtime?.deviceName ?? null,
907
+ nameSource: selfDeviceName ? 'network' : (runtime?.deviceName ? 'local' : null),
909
908
  // W2:root(持主私钥)/ delegated(仅委派链)
910
909
  mode: runtime?.identityMode ?? config?.identity?.mode ?? null,
911
910
  peerId: status.peerId,