UNPKG

@toponextech/smartembed-mcp-server

Version:

MCP server for intelligent embedded development with PlatformIO - AI-powered project creation, error diagnosis, and device detection

381 lines (372 loc) 15.2 kB
"use strict"; /** * SmartEmbed Suggestion Tool * Provides device identification and context-aware suggestions */ Object.defineProperty(exports, "__esModule", { value: true }); exports.suggestionTool = void 0; const device_parser_js_1 = require("./parsers/device-parser.js"); const context_suggestion_generator_js_1 = require("./generators/context-suggestion-generator.js"); exports.suggestionTool = { definition: { name: 'smartembed_suggest', description: '提供设备识别、最佳实践和上下文感知的智能建议', inputSchema: { type: 'object', properties: { type: { type: 'string', enum: ['device', 'best-practice', 'next-steps', 'context'], description: '建议类型:device(设备识别),best-practice(最佳实践),next-steps(下一步建议),context(上下文建议)', }, data: { type: 'string', description: '相关数据,如 pio device list 输出', }, context: { type: 'object', properties: { board: { type: 'string' }, framework: { type: 'string' }, libraries: { type: 'array', items: { type: 'string' } }, features: { type: 'array', items: { type: 'string' } }, errors: { type: 'array', items: { type: 'string' } }, stage: { type: 'string' }, }, description: '项目上下文信息', }, }, required: ['type'], }, }, handler: async (args) => { const { type, data, context } = args; console.error(`[DEBUG] Generating ${type} suggestions`); try { let responseText = ''; switch (type) { case 'device': responseText = await handleDeviceSuggestions(data); break; case 'best-practice': responseText = await handleBestPracticeSuggestions(context); break; case 'next-steps': responseText = await handleNextStepsSuggestions(context); break; case 'context': responseText = await handleContextualSuggestions(context); break; default: responseText = '❌ 未知的建议类型。支持的类型:device, best-practice, next-steps, context'; } const response = { content: [ { type: 'text', text: responseText, }, ], }; return response; } catch (error) { console.error(`[ERROR] Suggestion generation failed: ${error}`); throw error; } }, }; /** * Handle device identification and suggestions */ async function handleDeviceSuggestions(deviceListOutput) { const parser = new device_parser_js_1.DeviceParser(); const suggestionGen = new context_suggestion_generator_js_1.ContextSuggestionGenerator(); if (!deviceListOutput || deviceListOutput.trim() === '') { // If truly no data provided, give instructions if (deviceListOutput === undefined) { return `💡 **设备识别和建议** 请提供 PlatformIO 设备列表输出以识别连接的开发板。 **使用方法:** 1. 运行命令:\`pio device list\` 2. 复制输出结果 3. 使用本工具:\`smartembed_suggest\` 类型为 "device",并提供输出数据 **示例:** \`\`\` pio device list \`\`\` 这将帮助我: - 🔍 自动识别您的开发板型号 - 📌 推荐正确的板型配置 - 🔧 提供驱动安装建议 - 📡 配置上传端口`; } // If empty string provided, assume no devices detected } // Parse devices const devices = parser.parseDeviceList(deviceListOutput); if (devices.length === 0) { return `⚠️ **未检测到设备** **请检查以下事项:** 1. ✅ 开发板已通过 USB 连接 2. ✅ USB 线支持数据传输(非仅充电线) 3. ✅ 驱动程序已安装(Windows 检查设备管理器) 4. ✅ 尝试不同的 USB 端口 **常见驱动下载:** - CH340/CH341: http://www.wch.cn/download/CH341SER_EXE.html - CP2102: https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers - FTDI: https://ftdichip.com/drivers/vcp-drivers/`; } let response = `🔍 **检测到 ${devices.length} 个设备**\n\n`; for (let i = 0; i < devices.length; i++) { const device = devices[i]; const identification = parser.identifyBoard(device); const suggestions = suggestionGen.generateDeviceSuggestions(device, identification); response += `### 设备 ${i + 1}: ${device.port}\n`; response += `**描述**: ${device.description}\n`; if (device.vid && device.pid) { response += `**VID:PID**: ${device.vid}:${device.pid}\n`; } response += `\n**识别结果**:\n`; response += `- 推测板型: ${identification.detectedBoard}\n`; response += `- 置信度: ${translateConfidence(identification.confidence)}\n`; if (identification.alternativeBoards.length > 0) { response += `- 备选板型: ${identification.alternativeBoards.join(', ')}\n`; } response += `\n**建议**:\n`; for (const suggestion of suggestions) { response += `\n${formatSuggestion(suggestion)}\n`; } response += '\n---\n\n'; } // Add general connection tips const connectionTips = parser.generateConnectionSuggestions(devices); if (connectionTips.length > 0) { response += `### 💡 连接提示\n`; connectionTips.forEach(tip => { response += `- ${tip}\n`; }); } return response; } /** * Handle best practice suggestions */ async function handleBestPracticeSuggestions(context) { const suggestionGen = new context_suggestion_generator_js_1.ContextSuggestionGenerator(); // Create default context if not provided const projectContext = context || { currentStage: context_suggestion_generator_js_1.ProjectStage.DEVELOPMENT, }; const suggestions = suggestionGen.generateProjectSuggestions(projectContext); let response = `📚 **最佳实践建议**\n\n`; if (projectContext.board) { response += `开发板: ${projectContext.board}\n`; } if (projectContext.framework) { response += `框架: ${projectContext.framework}\n`; } response += `\n`; // Group suggestions by priority const criticalSuggestions = suggestions.filter(s => s.priority === context_suggestion_generator_js_1.SuggestionPriority.CRITICAL); const highSuggestions = suggestions.filter(s => s.priority === context_suggestion_generator_js_1.SuggestionPriority.HIGH); const mediumSuggestions = suggestions.filter(s => s.priority === context_suggestion_generator_js_1.SuggestionPriority.MEDIUM); if (criticalSuggestions.length > 0) { response += `### 🚨 关键建议\n`; criticalSuggestions.forEach(s => { response += formatSuggestion(s) + '\n'; }); } if (highSuggestions.length > 0) { response += `### ⚡ 重要建议\n`; highSuggestions.forEach(s => { response += formatSuggestion(s) + '\n'; }); } if (mediumSuggestions.length > 0) { response += `### 💡 推荐优化\n`; mediumSuggestions.forEach(s => { response += formatSuggestion(s) + '\n'; }); } if (suggestions.length === 0 || (!projectContext.board && !projectContext.framework)) { response += `请提供项目上下文信息以获得更具体的建议。\n\n`; response += `**可提供的上下文信息**:\n`; response += `- board: 开发板类型\n`; response += `- framework: 使用的框架\n`; response += `- libraries: 已安装的库\n`; response += `- features: 项目特性\n`; response += `- stage: 项目阶段\n`; } return response; } /** * Handle next steps suggestions */ async function handleNextStepsSuggestions(context) { const suggestionGen = new context_suggestion_generator_js_1.ContextSuggestionGenerator(); // Create default context if not provided let projectContext; if (!context) { projectContext = { currentStage: context_suggestion_generator_js_1.ProjectStage.INITIAL_SETUP }; } else { // Handle both 'stage' and 'currentStage' fields // Map stage string to ProjectStage enum let stage = context.currentStage || context.stage; if (typeof stage === 'string') { // Map string values to enum const stageMap = { 'initial_setup': context_suggestion_generator_js_1.ProjectStage.INITIAL_SETUP, 'development': context_suggestion_generator_js_1.ProjectStage.DEVELOPMENT, 'testing': context_suggestion_generator_js_1.ProjectStage.TESTING, 'optimization': context_suggestion_generator_js_1.ProjectStage.OPTIMIZATION, 'deployment': context_suggestion_generator_js_1.ProjectStage.DEPLOYMENT, }; stage = stageMap[stage] || context_suggestion_generator_js_1.ProjectStage.INITIAL_SETUP; } projectContext = { ...context, currentStage: stage || context_suggestion_generator_js_1.ProjectStage.INITIAL_SETUP, }; } const suggestions = suggestionGen.generateNextSteps(projectContext); let response = `🚀 **下一步建议**\n\n`; response += `当前阶段: ${translateProjectStage(projectContext.currentStage || context_suggestion_generator_js_1.ProjectStage.INITIAL_SETUP)}\n\n`; suggestions.forEach((suggestion, index) => { response += `### ${index + 1}. ${suggestion.title}\n`; response += formatSuggestion(suggestion) + '\n'; }); return response; } /** * Handle contextual suggestions based on full project context */ async function handleContextualSuggestions(context) { const suggestionGen = new context_suggestion_generator_js_1.ContextSuggestionGenerator(); if (!context) { return `📋 **上下文感知建议** 请提供项目上下文信息以获得智能建议。 **示例上下文**: \`\`\`json { "board": "esp32dev", "framework": "arduino", "libraries": ["WiFi", "PubSubClient"], "features": ["wifi", "mqtt", "sensors"], "hasWifi": true, "hasSensors": true, "currentStage": "development" } \`\`\` **支持的阶段**: - initial_setup: 初始设置 - development: 开发中 - testing: 测试阶段 - optimization: 优化阶段 - deployment: 部署准备`; } const suggestions = suggestionGen.generateProjectSuggestions(context); const nextSteps = suggestionGen.generateNextSteps(context); let response = `🎯 **智能项目建议**\n\n`; // Project overview response += `**项目概况**:\n`; if (context.board) response += `- 开发板: ${context.board}\n`; if (context.framework) response += `- 框架: ${context.framework}\n`; if (context.libraries && Array.isArray(context.libraries) && context.libraries.length > 0) { response += `- 已用库: ${context.libraries.join(', ')}\n`; } if (context.features && Array.isArray(context.features) && context.features.length > 0) { response += `- 功能特性: ${context.features.join(', ')}\n`; } response += `\n`; // All suggestions const allSuggestions = [...suggestions, ...nextSteps]; // Group by type const setupSuggestions = allSuggestions.filter(s => s.type === 'setup'); const configSuggestions = allSuggestions.filter(s => s.type === 'configuration'); const featureSuggestions = allSuggestions.filter(s => s.type === 'feature'); const optimizationSuggestions = allSuggestions.filter(s => s.type === 'optimization'); const warningSuggestions = allSuggestions.filter(s => s.type === 'warning'); if (warningSuggestions.length > 0) { response += `### ⚠️ 注意事项\n`; warningSuggestions.forEach(s => { response += formatSuggestion(s) + '\n'; }); } if (setupSuggestions.length > 0) { response += `### 🔧 设置建议\n`; setupSuggestions.forEach(s => { response += formatSuggestion(s) + '\n'; }); } if (configSuggestions.length > 0) { response += `### ⚙️ 配置建议\n`; configSuggestions.forEach(s => { response += formatSuggestion(s) + '\n'; }); } if (featureSuggestions.length > 0) { response += `### ✨ 功能建议\n`; featureSuggestions.forEach(s => { response += formatSuggestion(s) + '\n'; }); } if (optimizationSuggestions.length > 0) { response += `### 🚀 优化建议\n`; optimizationSuggestions.forEach(s => { response += formatSuggestion(s) + '\n'; }); } return response; } /** * Format a suggestion for display */ function formatSuggestion(suggestion) { let formatted = `**${suggestion.title}**\n`; formatted += `${suggestion.description}\n`; if (suggestion.actions && suggestion.actions.length > 0) { formatted += `\n📌 **操作步骤**:\n`; suggestion.actions.forEach(action => { formatted += `- ${action}\n`; }); } if (suggestion.codeSnippet) { formatted += `\n📝 **代码示例**:\n\`\`\`cpp\n${suggestion.codeSnippet}\n\`\`\`\n`; } if (suggestion.relatedPractices && suggestion.relatedPractices.length > 0) { formatted += `\n📚 **相关最佳实践**:\n`; suggestion.relatedPractices.forEach(practice => { formatted += `- ${practice.title}: ${practice.recommendations[0]}\n`; }); } return formatted; } /** * Translate confidence level to Chinese */ function translateConfidence(confidence) { const translations = { 'high': '高', 'medium': '中', 'low': '低', }; return translations[confidence] || confidence; } /** * Translate project stage to Chinese */ function translateProjectStage(stage) { const translations = { [context_suggestion_generator_js_1.ProjectStage.INITIAL_SETUP]: '初始设置', [context_suggestion_generator_js_1.ProjectStage.DEVELOPMENT]: '开发中', [context_suggestion_generator_js_1.ProjectStage.TESTING]: '测试阶段', [context_suggestion_generator_js_1.ProjectStage.OPTIMIZATION]: '优化阶段', [context_suggestion_generator_js_1.ProjectStage.DEPLOYMENT]: '部署准备', }; return translations[stage] || stage; } //# sourceMappingURL=suggest.js.map