UNPKG

yijing-bazi-mcp

Version:

易经八字分析 MCP 服务器 - 提供传统命理分析和易经卦象解读的AI工具

504 lines (480 loc) 16.5 kB
#!/usr/bin/env node /** * 易经八字分析MCP服务器 * 主入口文件 */ const { Server } = require('@modelcontextprotocol/sdk/server/index.js'); const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js'); const { CallToolRequestSchema, ListToolsRequestSchema } = require('@modelcontextprotocol/sdk/types.js'); const YijingEngine = require('./engines/yijing-engine.js'); const BaziEngine = require('./engines/bazi-engine.js'); const CombinedAnalysisEngine = require('./engines/combined-analysis-engine.js'); const KnowledgeEngine = require('./engines/knowledge-engine.js'); const Logger = require('./utils/logger.js'); const { validateToolInput } = require('./utils/validator.js'); const { ErrorHandler } = require('./utils/error-handler.js'); /** * MCP服务器类 */ class YijingBaziMCPServer { constructor() { this.server = new Server( { name: 'yijing-bazi-mcp-server', version: '1.0.0', }, { capabilities: { tools: {}, }, } ); // 初始化引擎 this.yijingEngine = new YijingEngine(); this.baziEngine = new BaziEngine(); this.combinedEngine = new CombinedAnalysisEngine(); this.knowledgeEngine = new KnowledgeEngine(); // 初始化日志 this.logger = new Logger(); // 初始化错误处理 this.errorHandler = new ErrorHandler(); this.setupHandlers(); } /** * 将resolution映射为period_type * @param {string} resolution - 用户提供的resolution参数 * @returns {string} 对应的period_type */ mapResolutionToPeriodType(resolution) { const mapping = { 'day': 'custom', 'month': 'monthly', 'year': 'yearly' }; return mapping[resolution] || 'custom'; } /** * 设置请求处理器 */ setupHandlers() { // 工具列表处理器 this.server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [ // 易经分析工具 { name: 'yijing_generate_hexagram', description: '根据指定方法生成六爻卦象', inputSchema: { type: 'object', properties: { method: { type: 'string', enum: ['number', 'time', 'plum_blossom', 'random'], description: '起卦方式' }, question: { type: 'string', description: '用户问题或求卦意图' }, seed: { type: 'string', description: '起卦数字或其他种子信息(可选)' } }, required: ['method', 'question'] } }, { name: 'yijing_interpret', description: '对卦象进行多层次解读', inputSchema: { type: 'object', properties: { hexagram: { type: 'object', description: '卦象数据,包含本卦和变卦信息' }, focus: { type: 'string', enum: ['overall', 'specific_line', 'changing'], description: '解读焦点:总体/特定爻/变卦' }, line_number: { type: 'integer', description: '当focus为specific_line时,指定关注的爻位(1-6)' }, context: { type: 'string', enum: ['general', 'career', 'relationship', 'health', 'finance'], description: '应用场景' }, detail_level: { type: 'string', enum: ['brief', 'standard', 'detailed'], description: '解读详细程度' } }, required: ['hexagram', 'focus', 'context'] } }, { name: 'yijing_advise', description: '基于卦象提供决策建议', inputSchema: { type: 'object', properties: { hexagram: { type: 'object', description: '卦象数据' }, question: { type: 'string', description: '用户的具体问题' }, options: { type: 'array', items: { type: 'string' }, description: '可选的行动方案(可选)' }, time_frame: { type: 'string', enum: ['immediate', 'short_term', 'long_term'], description: '决策的时间框架' } }, required: ['hexagram', 'question'] } }, // 八字分析工具 { name: 'bazi_generate_chart', description: '生成八字命盘', inputSchema: { type: 'object', properties: { birth_time: { type: 'string', format: 'date-time', description: '出生时间(阳历)' }, is_lunar: { type: 'boolean', description: '是否为农历日期' }, gender: { type: 'string', enum: ['male', 'female'], description: '性别' }, birth_location: { type: 'object', properties: { longitude: { type: 'number' }, latitude: { type: 'number' } }, description: '出生地经纬度(可选,用于精确计算)' } }, required: ['birth_time', 'gender'] } }, { name: 'bazi_analyze', description: '分析八字命盘', inputSchema: { type: 'object', properties: { chart: { type: 'object', description: '八字命盘数据' }, analysis_type: { type: 'array', items: { type: 'string', enum: ['personality', 'career', 'wealth', 'relationship', 'health'] }, description: '分析类型' }, detail_level: { type: 'string', enum: ['brief', 'standard', 'detailed'], description: '分析详细程度' } }, required: ['chart', 'analysis_type'] } }, { name: 'bazi_forecast', description: '预测未来运势', inputSchema: { type: 'object', properties: { chart: { type: 'object', description: '八字命盘数据' }, start_date: { type: 'string', format: 'date', description: '预测起始日期' }, end_date: { type: 'string', format: 'date', description: '预测结束日期' }, aspects: { type: 'array', items: { type: 'string', enum: ['overall', 'career', 'wealth', 'relationship', 'health'] }, description: '预测方面' }, resolution: { type: 'string', enum: ['year', 'month', 'day'], description: '预测精度' } }, required: ['chart', 'start_date', 'end_date', 'aspects'] } }, // 综合分析工具 { name: 'combined_analysis', description: '结合易经和八字进行综合分析', inputSchema: { type: 'object', properties: { bazi_chart: { type: 'object', description: '八字命盘数据' }, hexagram: { type: 'object', description: '卦象数据(可选,如不提供则从八字生成)' }, question: { type: 'string', description: '用户的具体问题或关注点' }, analysis_aspects: { type: 'array', items: { type: 'string' }, description: '分析方面' } }, required: ['bazi_chart', 'question'] } }, { name: 'destiny_consult', description: '提供命理咨询服务', inputSchema: { type: 'object', properties: { user_profile: { type: 'object', description: '用户基本信息,包含八字或其他命理数据' }, question: { type: 'string', description: '咨询问题' }, context: { type: 'array', items: { type: 'object' }, description: '历史咨询上下文(可选)' }, consultation_type: { type: 'string', enum: ['guidance', 'analysis', 'prediction', 'suggestion'], description: '咨询类型' } }, required: ['user_profile', 'question', 'consultation_type'] } }, // 学习研究工具 { name: 'knowledge_learn', description: '学习易经和八字知识', inputSchema: { type: 'object', properties: { topic: { type: 'string', description: '学习主题' }, system: { type: 'string', enum: ['yijing', 'bazi', 'both'], description: '知识体系' }, level: { type: 'string', enum: ['beginner', 'intermediate', 'advanced'], description: '学习级别' }, format: { type: 'string', enum: ['text', 'interactive', 'visual'], description: '学习内容格式' } }, required: ['topic', 'system', 'level'] } }, { name: 'case_study', description: '分析易经和八字案例', inputSchema: { type: 'object', properties: { case_id: { type: 'string', description: '案例ID(可选,不提供则返回案例列表)' }, system: { type: 'string', enum: ['yijing', 'bazi', 'combined'], description: '案例类型' }, category: { type: 'string', description: '案例分类(如历史人物、现代案例等)' }, analysis_focus: { type: 'array', items: { type: 'string' }, description: '分析重点' } }, required: ['system'] } } ] }; }); // 工具调用处理器 - 使用箭头函数保持this绑定 this.server.setRequestHandler(CallToolRequestSchema, async (request) => { try { const { name, arguments: args } = request.params; // 验证输入参数 const validationResult = validateToolInput(name, args); if (!validationResult.isValid) { throw new Error(`参数验证失败: ${validationResult.errors.join(', ')}`); } this.logger.info(`调用工具: ${name}`, { args }); let result; // 保存引擎引用以避免this绑定问题 const yijingEngine = this.yijingEngine; const baziEngine = this.baziEngine; const combinedEngine = this.combinedEngine; const knowledgeEngine = this.knowledgeEngine; switch (name) { // 易经工具 case 'yijing_generate_hexagram': result = await yijingEngine.generateHexagram(args); break; case 'yijing_interpret': result = await yijingEngine.interpretHexagram(args); break; case 'yijing_advise': result = await yijingEngine.provideAdvice(args); break; // 八字工具 case 'bazi_generate_chart': // 转换参数格式以匹配BaziEngine期望的格式 const chartArgs = { birth_datetime: args.birth_time, timezone: args.birth_location?.timezone || 'Asia/Shanghai', gender: args.gender, location: args.birth_location, use_true_solar_time: false, is_lunar: args.is_lunar || false }; result = await baziEngine.generateChart(chartArgs); break; case 'bazi_analyze': result = await baziEngine.analyzeChart(args); break; case 'bazi_forecast': // 转换参数格式以匹配BaziEngine期望的格式 // 处理嵌套的params结构 const params = args.params || args; const forecastArgs = { chart: params.chart, period_type: this.mapResolutionToPeriodType(params.resolution), start_date: params.start_date, end_date: params.end_date, focus_aspects: params.aspects || [] }; result = await baziEngine.forecastLuck(forecastArgs); break; // 综合分析工具 case 'combined_analysis': result = await combinedEngine.performCombinedAnalysis(args); break; case 'destiny_consult': result = await combinedEngine.provideConsultation(args); break; // 学习研究工具 case 'knowledge_learn': result = await knowledgeEngine.provideKnowledge(args); break; case 'case_study': result = await knowledgeEngine.analyzeCases(args); break; default: throw new Error(`未知的工具: ${name}`); } this.logger.info(`工具调用成功: ${name}`); return { content: [ { type: 'text', text: JSON.stringify(result, null, 2) } ] }; } catch (error) { this.logger.error(`工具调用失败: ${request.params.name}`, { error: error.message }); return this.errorHandler.handleToolError(error, request.params.name, request.params.arguments); } }); } /** * 启动服务器 */ async start() { try { const transport = new StdioServerTransport(); await this.server.connect(transport); this.logger.info('易经八字分析MCP服务器启动成功'); } catch (error) { this.logger.error('服务器启动失败', { error: error.message }); process.exit(1); } } } // 导出类供测试使用 module.exports = { YijingBaziMCPServer }; // 启动服务器 const server = new YijingBaziMCPServer(); server.start().catch((error) => { console.error('服务器启动失败:', error); process.exit(1); });