mcp-prompt-optimizer
Version:
Professional cloud-based MCP server for AI-powered prompt optimization with intelligent context detection, team collaboration, enterprise-grade features, startup validation, and robust API key management. Universal compatibility with Claude Desktop, Curso
921 lines (804 loc) • 33.8 kB
JavaScript
/**
* MCP Prompt Optimizer - Professional Cloud-Based AI Optimization Server
*
* Features:
* - Intelligent AI context detection (image gen, LLM interaction, technical)
* - 10+ professional optimization techniques
* - Template management with auto-save
* - Team collaboration and shared quotas
* - Universal MCP compatibility
* - Enterprise-grade analytics
*
* Starting at $2.99/month with 5,000 optimizations
* Free trial: 5 optimizations with full feature access
*
* Compatible with: Claude Desktop, Cursor, Windsurf, Cline, VS Code, Zed, Replit, and more
*/
// ✅ FIXED: Use absolute paths to bypass package.json export issues
const { Server } = require('./node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.js');
const { StdioServerTransport } = require('./node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.js');
const fetch = require('node-fetch');
const CloudApiKeyManager = require('./lib/api-key-manager');
class MCPPromptOptimizer {
constructor() {
this.server = new Server({
name: "mcp-prompt-optimizer",
version: "1.3.0" // Updated version for alignment
}, {
capabilities: {
tools: {}
}
});
this.apiKey = process.env.OPTIMIZER_API_KEY;
this.backendUrl = process.env.OPTIMIZER_BACKEND_URL || 'https://p01--project-optimizer--fvrdk8m9k9j.code.run';
this.setupTools();
}
validateApiKey(apiKey) {
if (!apiKey) return { valid: false, error: 'missing' };
// Valid cloud API key formats: sk-opt-*, sk-team-*
const validFormats = [
/^sk-opt-[a-zA-Z0-9_-]+$/, // Individual keys
/^sk-team-[a-zA-Z0-9_-]+$/ // Team keys
];
const isValidFormat = validFormats.some(format => format.test(apiKey));
if (!isValidFormat) {
return {
valid: false,
error: 'invalid_format',
expectedFormats: ['sk-opt-*', 'sk-team-*']
};
}
return { valid: true };
}
detectKeyType(apiKey) {
if (!apiKey) return 'unknown';
if (apiKey.startsWith('sk-opt-')) return 'individual';
if (apiKey.startsWith('sk-team-')) return 'team';
return 'unknown';
}
setupTools() {
// Main optimization tool with full feature set
this.server.setRequestHandler('tools/list', async () => {
return {
tools: [
{
name: "optimize_prompt",
description: "Professional cloud-based AI prompt optimization with intelligent context detection, template management, and team collaboration. All plans include the same sophisticated AI engine - differences are only in quotas, team size, and support levels.",
inputSchema: {
type: "object",
properties: {
prompt: {
type: "string",
description: "The prompt text to optimize (required)",
minLength: 1,
maxLength: 50000
},
goals: {
type: "array",
items: { type: "string" },
description: "Optimization goals: clarity, conciseness, creativity, specificity, actionability, technical_accuracy, keyword_density, parameter_preservation, context_specificity, token_efficiency",
default: ["clarity"],
minItems: 1,
maxItems: 10
},
ai_context: {
type: "string",
enum: [
"human_communication",
"llm_interaction",
"image_generation",
"technical_automation",
"structured_output",
"code_generation",
"api_automation"
],
description: "AI context for intelligent optimization routing (auto-detected if not specified)",
default: "llm_interaction"
}
},
required: ["prompt"]
}
},
{
name: "get_quota_status",
description: "Check your current subscription quota status, usage, and plan details",
inputSchema: {
type: "object",
properties: {},
required: []
}
},
{
name: "search_templates",
description: "Search your saved templates by content, tags, or AI context",
inputSchema: {
type: "object",
properties: {
query: {
type: "string",
description: "Search query for template content",
maxLength: 500
},
ai_context: {
type: "string",
enum: [
"human_communication",
"llm_interaction",
"image_generation",
"technical_automation",
"structured_output",
"code_generation",
"api_automation"
],
description: "Filter by AI context type"
},
limit: {
type: "integer",
minimum: 1,
maximum: 20,
default: 5,
description: "Maximum number of templates to return"
}
},
required: []
}
}
]
};
});
this.server.setRequestHandler('tools/call', async (request) => {
const { name, arguments: args } = request.params;
switch (name) {
case "optimize_prompt":
return await this.handleOptimize(args);
case "get_quota_status":
return await this.handleQuotaStatus(args);
case "search_templates":
return await this.handleSearchTemplates(args);
default:
throw new Error(`Unknown tool: ${name}`);
}
});
}
async handleOptimize(args) {
try {
// Validate API key
const keyValidation = this.validateApiKey(this.apiKey);
if (!keyValidation.valid) {
return this.createSubscriptionRequiredResponse(keyValidation);
}
// Validate required arguments
if (!args.prompt || !args.prompt.trim()) {
return {
content: [{
type: "text",
text: "# ❌ Error\n\nPrompt cannot be empty. Please provide a prompt to optimize."
}],
isError: true
};
}
// Prepare request payload matching backend expectations
const requestPayload = {
prompt: args.prompt.trim(),
goals: args.goals || ["clarity"],
ai_context: args.ai_context || "llm_interaction"
};
// Call backend API using standardized header
const response = await fetch(`${this.backendUrl}/api/v1/mcp/optimize`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': this.apiKey, // ✅ FIXED: Use lowercase header to match backend
'User-Agent': 'mcp-prompt-optimizer/1.3.0'
},
body: JSON.stringify(requestPayload)
});
if (!response.ok) {
return await this.handleApiError(response);
}
const result = await response.json();
return {
content: [{
type: "text",
text: this.formatOptimizationResult(result, args)
}]
};
} catch (error) {
console.error('Optimization error:', error);
return {
content: [{
type: "text",
text: `# ❌ Network Error\n\n${error.message}\n\nPlease check your internet connection and try again.`
}],
isError: true
};
}
}
async handleQuotaStatus(args) {
try {
const keyValidation = this.validateApiKey(this.apiKey);
if (!keyValidation.valid) {
return this.createSubscriptionRequiredResponse(keyValidation);
}
const response = await fetch(`${this.backendUrl}/api/v1/mcp/quota-status`, {
method: 'GET',
headers: {
'x-api-key': this.apiKey, // ✅ FIXED: Use lowercase header
'User-Agent': 'mcp-prompt-optimizer/1.3.0'
}
});
if (!response.ok) {
return await this.handleApiError(response);
}
const result = await response.json();
return {
content: [{
type: "text",
text: this.formatQuotaStatus(result)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: `# ❌ Error Getting Quota Status\n\n${error.message}`
}],
isError: true
};
}
}
async handleSearchTemplates(args) {
try {
const keyValidation = this.validateApiKey(this.apiKey);
if (!keyValidation.valid) {
return this.createSubscriptionRequiredResponse(keyValidation);
}
const params = new URLSearchParams();
if (args.query) params.append('query', args.query);
if (args.ai_context) params.append('ai_context', args.ai_context);
params.append('per_page', (args.limit || 5).toString());
const response = await fetch(`${this.backendUrl}/api/v1/templates?${params.toString()}`, {
method: 'GET',
headers: {
'x-api-key': this.apiKey, // ✅ FIXED: Use lowercase header
'User-Agent': 'mcp-prompt-optimizer/1.3.0'
}
});
if (!response.ok) {
return await this.handleApiError(response);
}
const result = await response.json();
return {
content: [{
type: "text",
text: this.formatTemplateSearchResults(result, args)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: `# ❌ Template Search Error\n\n${error.message}`
}],
isError: true
};
}
}
async handleApiError(response) {
const status = response.status;
let errorMessage = `API Error: ${response.statusText}`;
try {
const errorData = await response.json();
errorMessage = errorData.detail || errorMessage;
} catch (e) {
// Use default message if JSON parsing fails
}
if (status === 401) {
return {
content: [{
type: "text",
text: this.createInvalidKeyResponse(errorMessage)
}],
isError: true
};
} else if (status === 402 || status === 429) {
return {
content: [{
type: "text",
text: this.createQuotaExceededResponse(errorMessage)
}],
isError: true
};
} else if (status === 500) {
return {
content: [{
type: "text",
text: `# ⚠️ Server Error\n\n${errorMessage}\n\nPlease try again in a moment. If the issue persists, contact support@promptoptimizer.help`
}],
isError: true
};
}
return {
content: [{
type: "text",
text: `# ❌ Error (${status})\n\n${errorMessage}`
}],
isError: true
};
}
createSubscriptionRequiredResponse(keyValidation) {
const keyType = this.detectKeyType(this.apiKey);
let content = `# 🔒 Professional MCP Server - Cloud Subscription Required
This professional cloud-based MCP server requires an active subscription starting at **$2.99/month**.
## 🆓 **Get Started Free**
Get your API key with **5 free optimizations** at:
**https://promptoptimizer-blog.vercel.app/pricing**
## 💰 **Cloud Subscription Plans** (same AI quality, different quotas)
- **Explorer ($2.99/mo):** 5,000 optimizations + individual use
- **Creator ($25.99/mo):** 18,000 optimizations + team features (2 members)
- **Innovator ($69.99/mo):** 75,000 optimizations + large teams (5 members) + priority support
## ✨ **Professional Cloud Features** (all plans)
- 🧠 **AI Context Detection** - Automatically detects image generation, LLM interaction, technical contexts
- 🎯 **10+ Optimization Techniques** - Clarity, specificity, technical accuracy, and more
- 📁 **Template Management** - Auto-save high-confidence optimizations, search & reuse
- 📊 **Real-time Analytics** - Confidence scoring, usage tracking, performance insights
- 👥 **Team Collaboration** - Shared quotas, team templates, role-based access
- 🔧 **Universal MCP** - Works with Claude Desktop, Cursor, Windsurf, Cline, VS Code, Zed, Replit
- ☁️ **Cloud Processing** - No local setup, always up-to-date AI models
- 🚀 **Priority Processing** - Creator and Innovator plans get faster response times
## ⚙️ **Setup Instructions**
Add your API key to Claude Desktop config:
\`\`\`json
{
"mcpServers": {
"prompt-optimizer": {
"command": "npx",
"args": ["mcp-prompt-optimizer"],
"env": {
"OPTIMIZER_API_KEY": "sk-opt-your-key-here"
}
}
}
}
\`\`\`
## 🔧 **Other MCP Clients**
- **Cursor:** Add to ~/.cursor/mcp.json
- **Windsurf:** Configure in settings
- **Cline:** Use standard MCP configuration
- **VS Code/Zed/Replit:** Standard MCP setup
## 🏢 **Team Plans Available**
Team API keys (\`sk-team-*\`) provide:
- Shared quotas across team members
- Centralized billing and management
- Team template libraries
- Role-based access control
## 🔧 **Troubleshooting Tools**
- **Check status:** mcp-prompt-optimizer check-status
- **Validate key:** mcp-prompt-optimizer validate-key
- **Clear cache:** mcp-prompt-optimizer clear-cache
## 📧 **Support**
- General: support@promptoptimizer.help
- Enterprise: enterprise@promptoptimizer.help
- Documentation: https://promptoptimizer-blog.vercel.app/docs
- Dashboard: https://promptoptimizer-blog.vercel.app/dashboard`;
if (keyValidation.error === 'invalid_format') {
content += `\n\n## ❌ **API Key Format Issue**
Your API key format is invalid. Expected formats:
- Individual: \`sk-opt-*\`
- Team: \`sk-team-*\`
Current key type detected: \`${keyType}\`
Please get a new API key from: https://promptoptimizer-blog.vercel.app/pricing`;
}
return {
content: [{
type: "text",
text: content
}],
isError: true
};
}
createInvalidKeyResponse(errorMessage) {
return `# 🔑 Invalid API Key
**Error:** ${errorMessage}
## 🔧 **Fix Options:**
1. **Get a new API key** from: https://promptoptimizer-blog.vercel.app/pricing
2. **Check your configuration** - ensure \`OPTIMIZER_API_KEY\` is set correctly
3. **Verify key format** - should start with \`sk-opt-\` (individual) or \`sk-team-\` (team)
## ⚙️ **Claude Desktop Config:**
\`\`\`json
{
"mcpServers": {
"prompt-optimizer": {
"command": "npx",
"args": ["mcp-prompt-optimizer"],
"env": {
"OPTIMIZER_API_KEY": "sk-opt-your-actual-key-here"
}
}
}
}
\`\`\`
## 🔧 **Quick Diagnostic:**
- **Validate your key:** mcp-prompt-optimizer validate-key
- **Check full status:** mcp-prompt-optimizer check-status
- **Clear cache:** mcp-prompt-optimizer clear-cache
## 🆓 **Need a New Key?**
Visit https://promptoptimizer-blog.vercel.app/pricing to:
- Get 5 free trial optimizations
- Choose from Explorer ($2.99), Creator ($25.99), or Innovator ($69.99) plans
- Set up team accounts with shared quotas
## 📧 **Still Having Issues?**
Contact support@promptoptimizer.help with your key prefix (first 8 characters) for assistance.`;
}
createQuotaExceededResponse(errorMessage) {
return `# 📊 Quota Exceeded
**Error:** ${errorMessage}
## 🚀 **Upgrade Options:**
### Current Plans:
- **Explorer ($2.99/mo):** 5,000 optimizations
- **Creator ($25.99/mo):** 18,000 optimizations + team features
- **Innovator ($69.99/mo):** 75,000 optimizations + large teams
## 📈 **Upgrade Now:**
Visit https://promptoptimizer-blog.vercel.app/dashboard to:
- View your current usage
- Upgrade to a higher plan
- Manage team subscriptions
## 📅 **Quota Reset:**
Individual quotas reset monthly on your billing date.
Team quotas reset monthly on the team billing cycle.
## 🔧 **Check Usage:**
- **Detailed status:** mcp-prompt-optimizer check-status
- **Current quota:** Use the \`get_quota_status\` tool
- **Usage trends:** Visit your dashboard
## 💡 **Tips:**
- Consider upgrading if you regularly hit limits
- Team plans offer better value for multiple users
- Pro tip: Use templates to avoid re-optimizing similar prompts
## 📧 **Need Help?**
Contact support@promptoptimizer.help for usage optimization advice or enterprise solutions.`;
}
formatOptimizationResult(result, originalArgs) {
let output = `# 🎯 Optimized Prompt\n\n${result.optimized_prompt}\n\n`;
// Same response for ALL users - no tier differences in optimization quality
output += `**Confidence:** ${(result.confidence_score * 100).toFixed(1)}%\n`;
if (result.tier) {
output += `**Plan:** ${result.tier.charAt(0).toUpperCase() + result.tier.slice(1)}\n`;
}
// AI Context information
if (originalArgs.ai_context || result.ai_context) {
const context = originalArgs.ai_context || result.ai_context;
const contextLabels = {
'human_communication': 'Human Communication',
'llm_interaction': 'LLM Interaction',
'image_generation': 'Image Generation',
'technical_automation': 'Technical Automation',
'structured_output': 'Structured Output',
'code_generation': 'Code Generation',
'api_automation': 'API Automation'
};
output += `**AI Context:** ${contextLabels[context] || context}\n`;
}
// Template auto-saving (available for ALL users)
if (result.template_saved) {
output += `\n✅ **Auto-saved as template** (ID: ${result.template_id})\n`;
output += `*High-confidence optimization automatically saved for future use*\n`;
}
// Template save errors (graceful handling)
if (result.template_save_error) {
output += `\n⚠️ **Template save failed:** ${result.template_save_error}\n`;
}
// Similar templates found (available for ALL users)
if (result.templates_found && result.templates_found.length > 0) {
output += `\n## 📋 Similar Templates Found\n`;
result.templates_found.forEach((t, index) => {
output += `${index + 1}. **${t.title}** (${(t.confidence_score * 100).toFixed(1)}% similarity)\n`;
});
output += `*Use \`search_templates\` tool to explore your template library*\n`;
}
// Optimization insights (available for ALL users)
if (result.optimization_insights) {
output += `\n## 📊 Optimization Insights\n`;
const insights = result.optimization_insights;
// Performance metrics
if (insights.improvement_metrics) {
output += `\n**Performance Analysis:**\n`;
const metrics = insights.improvement_metrics;
output += `- Clarity improvement: +${(metrics.clarity_improvement * 100).toFixed(1)}%\n`;
output += `- Specificity boost: +${(metrics.specificity_improvement * 100).toFixed(1)}%\n`;
output += `- Length optimization: ${(metrics.length_optimization * 100).toFixed(1)}%\n`;
}
// User patterns analysis
if (insights.user_patterns) {
output += `\n**Prompt Analysis:**\n`;
output += `- Complexity level: ${insights.user_patterns.prompt_complexity}\n`;
output += `- Optimization confidence: ${insights.user_patterns.optimization_confidence}\n`;
}
// AI recommendations
if (insights.recommendations && insights.recommendations.length > 0) {
output += `\n**AI Recommendations:**\n`;
insights.recommendations.forEach(rec => {
output += `- ${rec}\n`;
});
}
output += `*Professional analytics and improvement recommendations*\n`;
}
// Professional footer
output += `\n---\n*Professional cloud-based AI optimization*`;
output += `\n💡 **Manage account:** https://promptoptimizer-blog.vercel.app/dashboard`;
output += `\n📊 **Check quota:** Use \`get_quota_status\` tool`;
output += `\n🔍 **Search templates:** Use \`search_templates\` tool`;
return output;
}
formatQuotaStatus(result) {
let output = `# 📊 Subscription Quota Status\n\n`;
// Plan information
output += `**Plan:** ${result.tier.charAt(0).toUpperCase() + result.tier.slice(1)}\n`;
// Quota details
if (result.quota.unlimited) {
output += `**Usage:** Unlimited optimizations\n`;
} else {
output += `**Usage:** ${result.quota.used.toLocaleString()} / ${result.quota.limit.toLocaleString()} optimizations\n`;
output += `**Remaining:** ${result.quota.remaining.toLocaleString()} optimizations\n`;
output += `**Usage:** ${result.quota.usage_percentage}% of monthly quota\n`;
}
// Status indicator
const status = result.status;
const statusEmoji = {
'healthy': '✅',
'warning': '⚠️',
'critical': '🔴'
};
output += `**Status:** ${statusEmoji[status] || '❓'} ${status.charAt(0).toUpperCase() + status.slice(1)}\n`;
// Context information
if (result.api_key_type === 'team') {
output += `\n## 👥 Team Information\n`;
if (result.team_info) {
output += `**Team:** ${result.team_info.team_name || 'Unknown'}\n`;
output += `**Team ID:** ${result.team_info.team_id}\n`;
}
output += `*This is a team subscription with shared quota*\n`;
} else {
output += `\n## 👤 Individual Information\n`;
output += `**Account Type:** Individual subscription\n`;
if (result.user_info) {
output += `**User ID:** ${result.user_info.user_id}\n`;
}
}
// Features available
output += `\n## ✨ Features Available\n`;
const features = result.features_available;
if (features.professional_optimization) output += `- ✅ Professional AI optimization\n`;
if (features.auto_save_templates) output += `- ✅ Template auto-save\n`;
if (features.template_search) output += `- ✅ Template search\n`;
if (features.optimization_insights) output += `- ✅ Optimization insights\n`;
// Upgrade suggestions
if (status === 'warning' || status === 'critical') {
output += `\n## 🚀 Upgrade Recommendations\n`;
output += `Consider upgrading to a higher tier for more optimizations:\n`;
output += `- **Creator ($25.99/mo):** 18,000 optimizations + team features\n`;
output += `- **Innovator ($69.99/mo):** 75,000 optimizations + priority support\n`;
output += `\n**Upgrade:** https://promptoptimizer-blog.vercel.app/dashboard\n`;
}
output += `\n---\n*Use \`optimize_prompt\` to start optimizing with AI context detection*`;
output += `\n*Use \`search_templates\` to find and reuse saved optimizations*`;
return output;
}
formatTemplateSearchResults(result, originalArgs) {
let output = `# 🔍 Template Search Results\n\n`;
if (!result.templates || result.templates.length === 0) {
output += `No templates found`;
if (originalArgs.query) {
output += ` matching "${originalArgs.query}"`;
}
if (originalArgs.ai_context) {
output += ` in context "${originalArgs.ai_context}"`;
}
output += `.\n\n`;
output += `💡 **Tips:**\n`;
output += `- Try broader search terms\n`;
output += `- Remove AI context filter\n`;
output += `- Use \`optimize_prompt\` to create new templates\n`;
return output;
}
output += `Found ${result.templates.length} template(s)`;
if (originalArgs.query) {
output += ` matching "${originalArgs.query}"`;
}
output += `:\n\n`;
result.templates.forEach((template, index) => {
output += `## ${index + 1}. ${template.title}\n`;
// Template metadata
if (template.ai_context_detected) {
const contextLabels = {
'human_communication': 'Human Communication',
'llm_interaction': 'LLM Interaction',
'image_generation': 'Image Generation',
'technical_automation': 'Technical Automation',
'structured_output': 'Structured Output',
'code_generation': 'Code Generation',
'api_automation': 'API Automation'
};
output += `**Context:** ${contextLabels[template.ai_context_detected] || template.ai_context_detected}\n`;
}
if (template.confidence_score) {
output += `**Confidence:** ${(template.confidence_score * 100).toFixed(1)}%\n`;
}
if (template.tags && template.tags.length > 0) {
output += `**Tags:** ${template.tags.join(', ')}\n`;
}
// Show optimized prompt preview
const preview = template.optimized_prompt.length > 200
? template.optimized_prompt.substring(0, 200) + '...'
: template.optimized_prompt;
output += `**Optimized Prompt:** ${preview}\n`;
if (template.created_at) {
const date = new Date(template.created_at).toLocaleDateString();
output += `**Created:** ${date}\n`;
}
output += `\n`;
});
// Show pagination info
if (result.total_pages > 1) {
output += `---\n`;
output += `**Page ${result.page} of ${result.total_pages}** (${result.total} total templates)\n`;
output += `*Adjust \`limit\` parameter to see more results per search*\n\n`;
}
output += `💡 **Template Usage:**\n`;
output += `- Copy optimized prompts for immediate use\n`;
output += `- Study successful patterns for your context\n`;
output += `- Create variations based on proven templates\n`;
output += `\n*Visit https://promptoptimizer-blog.vercel.app/dashboard to manage all templates*`;
return output;
}
async run() {
const transport = new StdioServerTransport();
await this.server.connect(transport);
}
}
// ✅ NEW: Startup validation function (following local pattern)
async function startValidatedMCPServer() {
console.error('🚀 MCP Prompt Optimizer - Professional Cloud Server v1.3.0\n');
try {
// Step 1: Get API key
const apiKey = process.env.OPTIMIZER_API_KEY;
if (!apiKey) {
console.error('❌ API key required');
console.error('\n💡 Get your API key in 30 seconds:');
console.error(' 1. Visit: https://promptoptimizer-blog.vercel.app/pricing');
console.error(' 2. Get your free trial (5 optimizations)');
console.error(' 3. Set: export OPTIMIZER_API_KEY=sk-opt-...');
console.error(' 4. Run: mcp-prompt-optimizer');
console.error('\n🎯 Plans: Explorer ($2.99), Creator ($25.99), Innovator ($69.99)');
process.exit(1);
}
// Step 2: Validate API key and check quota
const manager = new CloudApiKeyManager(apiKey);
const validation = await manager.validateAndPrepare();
// Step 3: Start the MCP server with validated context
console.error('🔧 Starting MCP server...\n');
// Create and start the MCP server instance
const mcpServer = new MCPPromptOptimizer();
console.error('✅ MCP server ready for connections');
console.error(`📊 Plan: ${validation.tier} | Quota: ${validation.quotaStatus.unlimited ? 'Unlimited' : `${validation.quotaStatus.remaining}/${validation.quotaStatus.limit} remaining`}`);
console.error('💡 Connect from your MCP client (Claude Desktop, Cursor, etc.)\n');
// Start the server
await mcpServer.run();
} catch (error) {
console.error(`❌ Failed to start MCP server: ${error.message}`);
if (error.message.includes('quota exceeded')) {
console.error('\n💎 Upgrade for more optimizations:');
console.error(' https://promptoptimizer-blog.vercel.app/pricing');
} else if (error.message.includes('validation failed') || error.message.includes('Invalid')) {
console.error('\n🛠️ Troubleshooting:');
console.error(' 1. Check your API key: mcp-prompt-optimizer validate-key');
console.error(' 2. Clear cache: mcp-prompt-optimizer clear-cache');
console.error(' 3. Get new key: https://promptoptimizer-blog.vercel.app/pricing');
} else if (error.message.includes('Network error')) {
console.error('\n🌐 Connection Issue:');
console.error(' - Check your internet connection');
console.error(' - Verify firewall/proxy settings');
console.error(' - Try again in a moment');
} else {
console.error('\n🔧 General Troubleshooting:');
console.error(' 1. Clear cache: mcp-prompt-optimizer clear-cache');
console.error(' 2. Check status: mcp-prompt-optimizer check-status');
console.error(' 3. Contact support: support@promptoptimizer.help');
}
process.exit(1);
}
}
// Show enhanced help and subscription info when run directly
async function showInfo() {
console.log('🚀 MCP Prompt Optimizer - Professional Cloud-Based Server v1.3.0');
console.log('==================================================================');
console.log('');
console.log('Professional cloud-based MCP server for AI-powered prompt optimization.');
console.log('Requires active subscription starting at $2.99/month.');
console.log('');
console.log('💰 Cloud Subscription Plans (same AI quality, different quotas):');
console.log(' Explorer ($2.99/mo): 5,000 optimizations + individual use');
console.log(' Creator ($25.99/mo): 18,000 optimizations + team features (2 members)');
console.log(' Innovator ($69.99/mo): 75,000 optimizations + large teams (5 members) + priority support');
console.log('');
console.log('✨ Professional Cloud Features (all plans):');
console.log(' 🧠 AI Context Detection - Image gen, LLM interaction, technical automation');
console.log(' 🎯 10+ Optimization Techniques - Clarity, specificity, technical accuracy');
console.log(' 📁 Template Management - Auto-save, search, reuse optimizations');
console.log(' 📊 Real-time Analytics - Confidence scoring, usage tracking');
console.log(' 👥 Team Collaboration - Shared quotas, team templates');
console.log(' ☁️ Cloud Processing - Always up-to-date, no local setup');
console.log(' 🚀 Priority Processing - Faster response times (Creator/Innovator)');
console.log('');
console.log('🆓 Free Trial: 5 optimizations included');
console.log('🌐 Get started: https://promptoptimizer-blog.vercel.app/pricing');
console.log('📊 Dashboard: https://promptoptimizer-blog.vercel.app/dashboard');
console.log('');
console.log('⚙️ Claude Desktop Setup:');
console.log('Add to ~/.claude/claude_desktop_config.json:');
console.log(JSON.stringify({
"mcpServers": {
"prompt-optimizer": {
"command": "npx",
"args": ["mcp-prompt-optimizer"],
"env": {
"OPTIMIZER_API_KEY": "sk-opt-your-key-here"
}
}
}
}, null, 2));
console.log('');
console.log('🔧 Other MCP Clients:');
console.log(' Cursor: Add to ~/.cursor/mcp.json');
console.log(' Windsurf: Configure in settings');
console.log(' Cline: Use standard MCP configuration');
console.log(' VS Code/Zed/Replit: Standard MCP setup');
console.log('');
console.log('🔧 Professional CLI Commands:');
console.log(' mcp-prompt-optimizer check-status Check API key and quota status');
console.log(' mcp-prompt-optimizer validate-key Validate your API key');
console.log(' mcp-prompt-optimizer clear-cache Clear validation cache');
console.log(' mcp-prompt-optimizer help Show this help');
console.log(' mcp-prompt-optimizer version Show version');
console.log('');
console.log('🏢 Enterprise Solutions:');
console.log(' Custom deployment options available');
console.log(' Higher quotas and dedicated support');
console.log(' Contact: enterprise@promptoptimizer.help');
console.log('');
console.log('📧 Support: support@promptoptimizer.help');
}
// ✅ NEW: Enhanced CLI command handling (following local pattern)
if (require.main === module) {
const args = process.argv.slice(2);
if (args.includes('--help') || args.includes('-h') || args.includes('help')) {
showInfo();
} else if (args.includes('--version') || args.includes('-v') || args.includes('version')) {
try {
const packageJson = require('./package.json');
console.log(`mcp-prompt-optimizer v${packageJson.version}`);
console.log('Professional Cloud-Based MCP Server - Starting at $2.99/month');
console.log('🌐 Get started: https://promptoptimizer-blog.vercel.app/pricing');
} catch (error) {
console.log('mcp-prompt-optimizer v1.3.0');
console.log('Professional Cloud-Based MCP Server - Starting at $2.99/month');
console.log('🌐 Get started: https://promptoptimizer-blog.vercel.app/pricing');
}
} else if (args.includes('check-status') || args.includes('status')) {
// ✅ NEW: CLI command integration
require('./lib/check-status');
} else if (args.includes('validate-key')) {
// ✅ NEW: CLI command integration
require('./lib/validate-key');
} else if (args.includes('clear-cache') || args.includes('clear')) {
// ✅ NEW: CLI command integration
require('./lib/clear-cache');
} else if (process.stdin.isTTY) {
// Running in terminal - show info
showInfo();
} else {
// ✅ UPDATED: Running via MCP protocol - start server with validation
startValidatedMCPServer();
}
}
module.exports = MCPPromptOptimizer;