/** * wechat-tools.js — 微信数据导入 MCP 工具 * * 提供两个 Master Agent 工具: * import_wechat_contacts — 批量导入微信联系人到图谱 * import_wechat_chat — 导入指定联系人聊天记录 */ const { WechatImporter } = require('../../../services/wechat/wechat-importer'); const { WechatReader } = require('../../../services/wechat/wechat-reader'); const { getGraphStore } = require('../../../db/GraphStore'); // 懒加载单例 let _importer = null; function importer() { if (!_importer) _importer = new WechatImporter(); return _importer; } function createWechatTools() { return [ { name: 'import_wechat_contacts', description: '从本地微信数据库导入联系人到知识图谱。limit 参数控制导入数量,默认 200。', parameters: { type: 'object', required: [], properties: { limit: { type: 'number', description: '导入数量上限,默认 200,最大 5000', }, }, }, async execute(params) { const limit = Math.min(params.limit || 200, 5000); try { const result = importer().importContacts(limit); return `✅ 微信联系人导入完成\n总计:${result.total} 条\n成功导入:${result.imported} 人\n跳过(无效数据):${result.skipped} 条`; } catch (e) { return `❌ 导入联系人失败:${e.message}`; } }, }, { name: 'import_wechat_chat', description: '导入指定微信联系人的聊天记录(最近 N 条),创建 Event 节点关联到该联系人。', parameters: { type: 'object', required: ['username_or_name'], properties: { username_or_name: { type: 'string', description: '微信 ID (wxid_xxx) 或联系人姓名', }, limit: { type: 'number', description: '导入消息条数上限,默认 50', }, }, }, async execute(params) { const limit = params.limit || 50; let username = params.username_or_name; // 如果不是 wxid_ 格式,尝试从图谱查找对应 wechatId if (!username.startsWith('wxid_') && !username.match(/^\d+@chatroom$/)) { const g = getGraphStore(); const results = g.findByName(username, 'Person'); const person = results.find(n => n.wechatId); if (person?.wechatId) { username = person.wechatId; } else { // 尝试直接用输入值作为 username(可能是非标准微信 ID) const reader = new WechatReader(); const contacts = reader.getContacts(5000); const found = contacts.find( c => c.remark === params.username_or_name || c.nickName === params.username_or_name || c.alias === params.username_or_name ); if (found) { username = found.username; } else { return `❌ 未找到联系人:${params.username_or_name},请使用微信 ID(wxid_xxx)或已导入联系人的姓名。`; } } } try { const result = importer().importChatHistory(username, limit); if (!result.eventId) { return `⚠️ 未找到 ${username} 的聊天记录(可能消息为空或无文本消息)。`; } return `✅ 聊天记录导入完成\n联系人:${username}\n消息条数:${result.messages}\nEvent ID:${result.eventId}`; } catch (e) { return `❌ 导入聊天记录失败:${e.message}`; } }, }, ]; } module.exports = { createWechatTools };