UNPKG

@xujiefeng/mcp-prompt-optimizer

Version:

ByteFun MCP服务:智能提示词优化,支持AI处理完成回调监听,提升Cursor使用体验

342 lines (339 loc) 14.1 kB
#!/usr/bin/env node "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js"); const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js"); const types_js_1 = require("@modelcontextprotocol/sdk/types.js"); const fs = __importStar(require("fs")); const path = __importStar(require("path")); const os = __importStar(require("os")); class EnhancedPromptOptimizerServer { constructor() { this.activeRequests = new Map(); // 设置通信目录 this.communicationDir = path.join(os.homedir(), '.bytefun-mcp'); this.ensureCommunicationDir(); this.server = new index_js_1.Server({ name: 'enhanced-prompt-optimizer', version: '1.0.0', }, { capabilities: { tools: {}, }, }); this.setupHandlers(); } ensureCommunicationDir() { try { if (!fs.existsSync(this.communicationDir)) { fs.mkdirSync(this.communicationDir, { recursive: true }); } // 创建子目录 const requestsDir = path.join(this.communicationDir, 'requests'); const responsesDir = path.join(this.communicationDir, 'responses'); if (!fs.existsSync(requestsDir)) { fs.mkdirSync(requestsDir, { recursive: true }); } if (!fs.existsSync(responsesDir)) { fs.mkdirSync(responsesDir, { recursive: true }); } } catch (error) { console.error('创建通信目录失败:', error); } } setupHandlers() { // 列出可用的工具 this.server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => { return { tools: [ { name: 'optimize_with_callback', description: '优化提示词并支持AI处理完成后的回调通知', inputSchema: { type: 'object', properties: { user_input: { type: 'string', description: '用户的原始输入', }, context_type: { type: 'string', enum: ['coding', 'writing', 'analysis', 'general'], description: '上下文类型', default: 'general', }, enable_callback: { type: 'boolean', description: '是否启用回调通知', default: true, }, }, required: ['user_input'], }, }, { name: 'notify_ai_complete', description: 'AI处理完成后的通知工具(由AI调用)', inputSchema: { type: 'object', properties: { request_id: { type: 'string', description: '请求ID', }, ai_response: { type: 'string', description: 'AI的完整响应内容', }, processing_time: { type: 'number', description: '处理时间(毫秒)', }, metadata: { type: 'object', description: '额外的元数据', }, }, required: ['request_id', 'ai_response'], }, }, { name: 'get_request_status', description: '获取请求状态', inputSchema: { type: 'object', properties: { request_id: { type: 'string', description: '请求ID', }, }, required: ['request_id'], }, }, ], }; }); // 处理工具调用 this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; switch (name) { case 'optimize_with_callback': return await this.optimizeWithCallback(args); case 'notify_ai_complete': return await this.notifyAIComplete(args); case 'get_request_status': return await this.getRequestStatus(args); default: throw new Error(`未知的工具: ${name}`); } }); } async optimizeWithCallback(args) { const { user_input, context_type = 'general', enable_callback = true } = args; if (!user_input) { throw new Error('用户输入不能为空'); } // 生成唯一的请求ID const requestId = `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; // 优化提示词 let optimizedPrompt = this.optimizePrompt(user_input, context_type); // 如果启用回调,添加回调指令 if (enable_callback) { optimizedPrompt += this.generateCallbackInstruction(requestId); } // 记录请求 const tracker = { id: requestId, originalPrompt: user_input, optimizedPrompt: optimizedPrompt, timestamp: Date.now(), status: 'pending', metadata: { context_type, enable_callback, }, }; this.activeRequests.set(requestId, tracker); // 保存请求到文件 await this.saveRequestToFile(tracker); return { content: [ { type: 'text', text: JSON.stringify({ success: true, request_id: requestId, original_prompt: user_input, optimized_prompt: optimizedPrompt, context_type: context_type, callback_enabled: enable_callback, timestamp: new Date().toISOString(), message: '✅ 提示词已优化,请使用优化后的提示词进行处理', instructions: enable_callback ? `处理完成后,请调用 notify_ai_complete 工具,传入 request_id: "${requestId}" 和你的完整回复内容` : '直接使用优化后的提示词进行处理', }, null, 2), }, ], }; } async notifyAIComplete(args) { const { request_id, ai_response, processing_time = 0, metadata = {} } = args; if (!request_id || !ai_response) { throw new Error('request_id 和 ai_response 是必需的'); } // 查找对应的请求 const tracker = this.activeRequests.get(request_id); if (!tracker) { throw new Error(`未找到请求ID: ${request_id}`); } // 更新请求状态 tracker.status = 'completed'; tracker.metadata = { ...tracker.metadata, ...metadata, processing_time }; // 创建响应数据 const responseData = { requestId: request_id, originalPrompt: tracker.originalPrompt, optimizedPrompt: tracker.optimizedPrompt, aiResponse: ai_response, processingTime: processing_time, timestamp: Date.now(), metadata: tracker.metadata, }; // 保存响应到文件(供VSCode插件监听) await this.saveResponseToFile(responseData); // 清理已完成的请求 this.activeRequests.delete(request_id); return { content: [ { type: 'text', text: JSON.stringify({ success: true, message: '✅ AI处理完成通知已记录', request_id: request_id, response_saved: true, timestamp: new Date().toISOString(), }, null, 2), }, ], }; } async getRequestStatus(args) { const { request_id } = args; if (!request_id) { throw new Error('request_id 是必需的'); } const tracker = this.activeRequests.get(request_id); return { content: [ { type: 'text', text: JSON.stringify({ success: true, request_id: request_id, found: !!tracker, status: tracker?.status || 'not_found', timestamp: tracker?.timestamp, metadata: tracker?.metadata, message: tracker ? '✅ 请求状态查询成功' : '⚠️ 请求未找到', }, null, 2), }, ], }; } optimizePrompt(userInput, contextType) { // 基础优化逻辑 let optimized = userInput; // 根据上下文类型添加前缀 const contextPrefixes = { coding: '作为一个专业的软件开发工程师,', writing: '作为一个专业的内容创作专家,', analysis: '作为一个专业的数据分析师,', general: '作为一个专业的助手,', }; const prefix = contextPrefixes[contextType] || contextPrefixes.general; optimized = prefix + optimized; // 添加质量要求 if (this.isVagueRequest(userInput)) { optimized += '\n\n请提供详细、具体的回答,包括步骤说明和最佳实践建议。'; } return optimized; } generateCallbackInstruction(requestId) { return ` [重要指令] 当你完成回复后,请立即调用以下MCP工具来通知处理完成: 工具名称: notify_ai_complete 参数: - request_id: "${requestId}" - ai_response: "[你的完整回复内容]" - processing_time: [处理时间,可选] 这将通知VSCode插件AI处理已完成,并传递相关数据。`; } isVagueRequest(request) { const vaguePatterns = [ /^(做|写|创建|制作|设计|开发).*$/, /^(帮我|给我|能否|可以).*$/, /^.{1,15}$/ // 非常短的请求 ]; return vaguePatterns.some(pattern => pattern.test(request)); } async saveRequestToFile(tracker) { try { const filename = `request_${tracker.id}.json`; const filepath = path.join(this.communicationDir, 'requests', filename); await fs.promises.writeFile(filepath, JSON.stringify(tracker, null, 2)); } catch (error) { console.error('保存请求文件失败:', error); } } async saveResponseToFile(responseData) { try { const filename = `response_${responseData.requestId}_${Date.now()}.json`; const filepath = path.join(this.communicationDir, 'responses', filename); await fs.promises.writeFile(filepath, JSON.stringify(responseData, null, 2)); console.log(`响应已保存: ${filename}`); } catch (error) { console.error('保存响应文件失败:', error); } } getCommunicationDir() { return this.communicationDir; } async run() { const transport = new stdio_js_1.StdioServerTransport(); await this.server.connect(transport); console.error('Enhanced Prompt Optimizer MCP Server 已启动'); } } // 启动服务器 const server = new EnhancedPromptOptimizerServer(); server.run().catch(console.error); //# sourceMappingURL=enhancedPromptOptimizer.js.map