UNPKG

mcp-prompt-optimizer

Version:

Local MCP server for AI-Enhanced Prompt Optimizer API with context awareness and parameter preservation

236 lines (217 loc) 7.83 kB
const PromptOptimizerApiClient = require('./api-client'); class MCPServer { constructor(apiKey) { this.apiClient = new PromptOptimizerApiClient(apiKey); this.tools = [{ name: "optimize_prompt", description: "Optimize prompts for clarity, conciseness, and effectiveness using advanced AI techniques with context awareness", inputSchema: { type: "object", properties: { prompt: { type: "string", description: "The prompt to optimize" }, goals: { type: "array", items: { type: "string", enum: [ // Standard goals "clarity", "conciseness", "technical_accuracy", "contextual_relevance", "specificity", "actionability", "structure", "technical_precision", "linguistic_precision", "holistic_effectiveness", // NEW: AI-specific goals "keyword_density", "parameter_preservation", "token_efficiency", "embedding_strength", "context_specificity", "ai_model_compatibility", "quality_enhancement", "role_clarity", "code_protection" ] }, description: "Optimization goals including AI-specific enhancements (default: clarity)", default: ["clarity"] }, ai_context: { type: "string", enum: ["image_generation", "llm_interaction", "technical_automation", "human_communication"], description: "AI context type for optimization routing (auto-detected if not specified)" }, preserve_formatting: { type: "boolean", description: "Whether to preserve technical formatting and parameters", default: true }, target_ai_model: { type: "string", description: "Target AI model (e.g., 'midjourney', 'chatgpt', 'claude')" }, optimization_level: { type: "string", enum: ["conservative", "balanced", "aggressive"], description: "Optimization level: conservative, balanced, or aggressive", default: "balanced" } }, required: ["prompt"] } }]; } async initialize() { try { const userData = await this.apiClient.validateKey(); console.error(`✅ Connected to Prompt Optimizer API (AI-Enhanced)`); console.error(` Tier: ${userData.tier}`); console.error(` Quota: ${userData.quota_used}/${userData.quota_limit} used`); console.error(` Status: ${userData.subscription_status}`); console.error(` AI Features: Context Detection, Parameter Preservation, Enhanced Goals`); return true; } catch (error) { console.error(`❌ Failed to connect: ${error.message}`); return false; } } async handleToolCall(name, args) { if (name === 'optimize_prompt') { const { prompt, goals = ['clarity'], ai_context = null, preserve_formatting = true, target_ai_model = null, optimization_level = "balanced" } = args; // Validate prompt if (!prompt || typeof prompt !== 'string' || prompt.trim().length === 0) { return { content: [{ type: "text", text: "❌ **Error:** Prompt cannot be empty" }], isError: true }; } // Validate goals (including new AI-specific goals) const validGoals = [ "clarity", "conciseness", "technical_accuracy", "contextual_relevance", "specificity", "actionability", "structure", "technical_precision", "linguistic_precision", "holistic_effectiveness", // AI-specific goals "keyword_density", "parameter_preservation", "token_efficiency", "embedding_strength", "context_specificity", "ai_model_compatibility", "quality_enhancement", "role_clarity", "code_protection" ]; const filteredGoals = goals.filter(goal => validGoals.includes(goal)); if (filteredGoals.length === 0) { filteredGoals.push('clarity'); // Default fallback } try { const options = { ai_context, preserve_formatting, target_ai_model, optimization_level }; const result = await this.apiClient.optimize(prompt.trim(), filteredGoals, options); // Enhanced response with AI context information let responseText = `# AI-Optimized Prompt\n\n${result.optimized_prompt}\n\n---\n\n`; responseText += `**Confidence Score:** ${result.confidence_score.toFixed(2)}\n`; responseText += `**Goals Applied:** ${filteredGoals.join(', ')}\n`; // Add AI context information if available if (result.metadata?.ai_context) { responseText += `**AI Context Detected:** ${result.metadata.ai_context}\n`; } if (result.metadata?.optimization_strategy) { responseText += `**Optimization Strategy:** ${result.metadata.optimization_strategy}\n`; } if (result.metadata?.goal_enhancement_applied) { responseText += `**Goal Enhancement:** Applied\n`; } if (result.metadata?.preserved_parameters) { responseText += `**Parameters Preserved:** ${result.metadata.preserved_parameters}\n`; } if (result.metadata?.original_goals && result.metadata?.enhanced_goals) { responseText += `**Original Goals:** ${result.metadata.original_goals.join(', ')}\n`; responseText += `**Enhanced Goals:** ${result.metadata.enhanced_goals.join(', ')}\n`; } responseText += `**Quota Remaining:** ${result.metadata?.quota_remaining ?? 'Unknown'}`; return { content: [{ type: "text", text: responseText }] }; } catch (error) { return { content: [{ type: "text", text: `❌ **Optimization Error:** ${error.message}` }], isError: true }; } } throw new Error(`Unknown tool: ${name}`); } async handleMessage(message) { const { method, params, id } = message; try { switch (method) { case 'initialize': return { jsonrpc: "2.0", id, result: { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "mcp-prompt-optimizer", version: "1.1.0" // Updated version for AI features } } }; case 'tools/list': return { jsonrpc: "2.0", id, result: { tools: this.tools } }; case 'tools/call': if (!params || !params.name) { throw new Error('Missing tool name in call parameters'); } const result = await this.handleToolCall(params.name, params.arguments || {}); return { jsonrpc: "2.0", id, result }; default: throw new Error(`Unknown method: ${method}`); } } catch (error) { return { jsonrpc: "2.0", id, error: { code: -32000, message: error.message } }; } } } module.exports = MCPServer;