mcp-prompt-optimizer 1.3.2 → 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,110 +1,85 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * MCP Prompt Optimizer - Professional Cloud-Based AI Optimization Server
4
+ * MCP Prompt Optimizer - Professional Cloud-Based MCP Server
5
+ * Production-grade with enhanced network resilience and development mode
5
6
  *
6
- * Features:
7
- * - Intelligent AI context detection (image gen, LLM interaction, technical)
8
- * - 10+ professional optimization techniques
9
- * - Template management with auto-save
10
- * - Team collaboration and shared quotas
11
- * - Universal MCP compatibility
12
- * - Enterprise-grade analytics
13
- *
14
- * Starting at $2.99/month with 5,000 optimizations
15
- * Free trial: 5 optimizations with full feature access
16
- *
17
- * Compatible with: Claude Desktop, Cursor, Windsurf, Cline, VS Code, Zed, Replit, and more
7
+ * Version: 1.3.2
8
+ * Documentation: https://promptoptimizer-blog.vercel.app/docs
9
+ * Pricing: https://promptoptimizer-blog.vercel.app/pricing
18
10
  */
19
11
 
20
- // ✅ FIXED: Use absolute paths to bypass package.json export issues
21
- const { Server } = require('./node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.js');
22
- const { StdioServerTransport } = require('./node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.js');
23
- const fetch = require('node-fetch');
12
+ // ✅ MCP SDK imports (required for MCP server compliance)
13
+ const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
14
+ const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
15
+ const { CallToolRequestSchema, ListToolsRequestSchema } = require('@modelcontextprotocol/sdk/types.js');
16
+
17
+ // ✅ Other required imports
18
+ const https = require('https');
24
19
  const CloudApiKeyManager = require('./lib/api-key-manager');
20
+ const packageJson = require('./package.json');
25
21
 
22
+ /**
23
+ * MCPPromptOptimizer - Main MCP Server Class
24
+ * Enhanced with production-grade resilience and development mode
25
+ */
26
26
  class MCPPromptOptimizer {
27
27
  constructor() {
28
- this.server = new Server({
29
- name: "mcp-prompt-optimizer",
30
- version: "1.3.0" // Updated version for alignment
31
- }, {
32
- capabilities: {
33
- tools: {}
28
+ this.server = new Server(
29
+ {
30
+ name: "mcp-prompt-optimizer",
31
+ version: packageJson.version,
32
+ },
33
+ {
34
+ capabilities: {
35
+ tools: {},
36
+ },
34
37
  }
35
- });
38
+ );
36
39
 
37
- this.apiKey = process.env.OPTIMIZER_API_KEY;
38
40
  this.backendUrl = process.env.OPTIMIZER_BACKEND_URL || 'https://p01--project-optimizer--fvrdk8m9k9j.code.run';
39
- this.setupTools();
40
- }
41
-
42
- validateApiKey(apiKey) {
43
- if (!apiKey) return { valid: false, error: 'missing' };
44
-
45
- // Valid cloud API key formats: sk-opt-*, sk-team-*
46
- const validFormats = [
47
- /^sk-opt-[a-zA-Z0-9_-]+$/, // Individual keys
48
- /^sk-team-[a-zA-Z0-9_-]+$/ // Team keys
49
- ];
50
-
51
- const isValidFormat = validFormats.some(format => format.test(apiKey));
52
- if (!isValidFormat) {
53
- return {
54
- valid: false,
55
- error: 'invalid_format',
56
- expectedFormats: ['sk-opt-*', 'sk-team-*']
57
- };
58
- }
59
-
60
- return { valid: true };
61
- }
41
+ this.apiKey = process.env.OPTIMIZER_API_KEY;
42
+ this.developmentMode = process.env.NODE_ENV === 'development' || process.env.OPTIMIZER_DEV_MODE === 'true';
43
+ this.requestTimeout = parseInt(process.env.OPTIMIZER_REQUEST_TIMEOUT) || 30000;
62
44
 
63
- detectKeyType(apiKey) {
64
- if (!apiKey) return 'unknown';
65
- if (apiKey.startsWith('sk-opt-')) return 'individual';
66
- if (apiKey.startsWith('sk-team-')) return 'team';
67
- return 'unknown';
45
+ // ✅ Set up MCP handlers
46
+ this.setupMCPHandlers();
68
47
  }
69
48
 
70
- setupTools() {
71
- // Main optimization tool with full feature set
72
- this.server.setRequestHandler('tools/list', async () => {
49
+ // ✅ Enhanced MCP handlers setup
50
+ setupMCPHandlers() {
51
+ // Handler for listing available tools
52
+ this.server.setRequestHandler(ListToolsRequestSchema, async () => {
73
53
  return {
74
54
  tools: [
75
55
  {
76
56
  name: "optimize_prompt",
77
- 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.",
57
+ description: "Professional AI-powered prompt optimization with intelligent context detection and goal enhancement",
78
58
  inputSchema: {
79
59
  type: "object",
80
60
  properties: {
81
- prompt: {
61
+ prompt: {
82
62
  type: "string",
83
- description: "The prompt text to optimize (required)",
84
- minLength: 1,
85
- maxLength: 50000
63
+ description: "The prompt text to optimize"
86
64
  },
87
- goals: {
88
- type: "array",
65
+ goals: {
66
+ type: "array",
89
67
  items: { type: "string" },
90
- description: "Optimization goals: clarity, conciseness, creativity, specificity, actionability, technical_accuracy, keyword_density, parameter_preservation, context_specificity, token_efficiency",
91
- default: ["clarity"],
92
- minItems: 1,
93
- maxItems: 10
68
+ description: "Optimization goals (e.g., 'clarity', 'conciseness', 'creativity')",
69
+ default: ["clarity"]
94
70
  },
95
71
  ai_context: {
96
72
  type: "string",
97
73
  enum: [
98
- "human_communication",
74
+ "human_communication",
99
75
  "llm_interaction",
100
- "image_generation",
101
- "technical_automation",
102
- "structured_output",
103
- "code_generation",
76
+ "image_generation",
77
+ "technical_automation",
78
+ "structured_output",
79
+ "code_generation",
104
80
  "api_automation"
105
81
  ],
106
- description: "AI context for intelligent optimization routing (auto-detected if not specified)",
107
- default: "llm_interaction"
82
+ description: "The context for the AI's task (auto-detected if not specified)"
108
83
  }
109
84
  },
110
85
  required: ["prompt"]
@@ -112,810 +87,1203 @@ class MCPPromptOptimizer {
112
87
  },
113
88
  {
114
89
  name: "get_quota_status",
115
- description: "Check your current subscription quota status, usage, and plan details",
90
+ description: "Check subscription status, quota usage, and account information",
116
91
  inputSchema: {
117
92
  type: "object",
118
93
  properties: {},
119
- required: []
94
+ additionalProperties: false
120
95
  }
121
96
  },
122
97
  {
123
98
  name: "search_templates",
124
- description: "Search your saved templates by content, tags, or AI context",
99
+ description: "Search your saved template library for reusable optimizations",
125
100
  inputSchema: {
126
- type: "object",
101
+ type: "object",
127
102
  properties: {
128
103
  query: {
129
104
  type: "string",
130
- description: "Search query for template content",
131
- maxLength: 500
105
+ description: "Search term to filter templates by content or title"
132
106
  },
133
107
  ai_context: {
134
108
  type: "string",
135
109
  enum: [
136
110
  "human_communication",
137
- "llm_interaction",
138
- "image_generation",
111
+ "llm_interaction",
112
+ "image_generation",
139
113
  "technical_automation",
140
114
  "structured_output",
141
- "code_generation",
115
+ "code_generation",
142
116
  "api_automation"
143
117
  ],
144
- description: "Filter by AI context type"
118
+ description: "Filter templates by AI context type"
145
119
  },
146
120
  limit: {
147
- type: "integer",
148
- minimum: 1,
149
- maximum: 20,
121
+ type: "number",
122
+ description: "Maximum number of templates to return (default: 5)",
150
123
  default: 5,
151
- description: "Maximum number of templates to return"
124
+ minimum: 1,
125
+ maximum: 20
152
126
  }
153
127
  },
154
- required: []
128
+ additionalProperties: false
155
129
  }
156
130
  }
157
131
  ]
158
132
  };
159
133
  });
160
134
 
161
- this.server.setRequestHandler('tools/call', async (request) => {
135
+ // Handler for tool calls
136
+ this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
162
137
  const { name, arguments: args } = request.params;
163
-
164
- switch (name) {
165
- case "optimize_prompt":
166
- return await this.handleOptimize(args);
167
- case "get_quota_status":
168
- return await this.handleQuotaStatus(args);
169
- case "search_templates":
170
- return await this.handleSearchTemplates(args);
171
- default:
172
- throw new Error(`Unknown tool: ${name}`);
138
+
139
+ try {
140
+ switch (name) {
141
+ case "optimize_prompt":
142
+ return await this.handleOptimizePrompt(args);
143
+ case "get_quota_status":
144
+ return await this.handleGetQuotaStatus();
145
+ case "search_templates":
146
+ return await this.handleSearchTemplates(args);
147
+ default:
148
+ throw new Error(`Unknown tool: ${name}`);
149
+ }
150
+ } catch (error) {
151
+ throw new Error(`Tool execution failed: ${error.message}`);
173
152
  }
174
153
  });
175
154
  }
176
155
 
177
- async handleOptimize(args) {
178
- try {
179
- // Validate API key
180
- const keyValidation = this.validateApiKey(this.apiKey);
181
- if (!keyValidation.valid) {
182
- return this.createSubscriptionRequiredResponse(keyValidation);
183
- }
184
-
185
- // Validate required arguments
186
- if (!args.prompt || !args.prompt.trim()) {
187
- return {
188
- content: [{
189
- type: "text",
190
- text: "# ❌ Error\n\nPrompt cannot be empty. Please provide a prompt to optimize."
191
- }],
192
- isError: true
193
- };
194
- }
156
+ // Enhanced AI context detection method
157
+ detectAIContext(prompt) {
158
+ const promptLower = prompt.toLowerCase();
159
+
160
+ // Image Generation Context Detection
161
+ const imagePatterns = [
162
+ /--ar\s+\d+:\d+/, // --ar 16:9
163
+ /--v\s+\d+/, // --v 6
164
+ /midjourney/,
165
+ /dall-?e/,
166
+ /photorealistic/,
167
+ /4k|8k\s+(resolution|quality)/,
168
+ /digital art/,
169
+ /concept art/,
170
+ /hyperrealistic/,
171
+ /ultra.?detailed/,
172
+ /masterpiece/
173
+ ];
195
174
 
196
- // Prepare request payload matching backend expectations
197
- const requestPayload = {
198
- prompt: args.prompt.trim(),
199
- goals: args.goals || ["clarity"],
200
- ai_context: args.ai_context || "llm_interaction"
201
- };
175
+ if (imagePatterns.some(pattern => pattern.test(promptLower))) {
176
+ return 'image_generation';
177
+ }
202
178
 
203
- // Call backend API using standardized header
204
- const response = await fetch(`${this.backendUrl}/api/v1/mcp/optimize`, {
205
- method: 'POST',
206
- headers: {
207
- 'Content-Type': 'application/json',
208
- 'x-api-key': this.apiKey, // ✅ FIXED: Use lowercase header to match backend
209
- 'User-Agent': 'mcp-prompt-optimizer/1.3.0'
210
- },
211
- body: JSON.stringify(requestPayload)
212
- });
179
+ // LLM Interaction Context Detection
180
+ const llmPatterns = [
181
+ /act as/,
182
+ /you are a/,
183
+ /role:/,
184
+ /persona:/,
185
+ /behave like/,
186
+ /pretend to be/,
187
+ /simulate/,
188
+ /roleplay/,
189
+ /character:/
190
+ ];
213
191
 
214
- if (!response.ok) {
215
- return await this.handleApiError(response);
216
- }
192
+ if (llmPatterns.some(pattern => pattern.test(promptLower))) {
193
+ return 'llm_interaction';
194
+ }
217
195
 
218
- const result = await response.json();
219
- return {
220
- content: [{
221
- type: "text",
222
- text: this.formatOptimizationResult(result, args)
223
- }]
224
- };
196
+ // Technical Automation Context Detection
197
+ const techPatterns = [
198
+ /\bdef\s+\w+\(/, // function definitions
199
+ /function\s*\(/, // function keyword
200
+ /execute|automation/,
201
+ /script|deploy/,
202
+ /\$\{.*\}/, // variable substitution
203
+ /#!/, // shebang
204
+ /import\s+|require\(/,
205
+ /\.sh|\.py|\.js/,
206
+ /sudo|chmod|mkdir/
207
+ ];
225
208
 
226
- } catch (error) {
227
- console.error('Optimization error:', error);
228
- return {
229
- content: [{
230
- type: "text",
231
- text: `# ❌ Network Error\n\n${error.message}\n\nPlease check your internet connection and try again.`
232
- }],
233
- isError: true
234
- };
209
+ if (techPatterns.some(pattern => pattern.test(promptLower))) {
210
+ return 'technical_automation';
235
211
  }
236
- }
237
212
 
238
- async handleQuotaStatus(args) {
239
- try {
240
- const keyValidation = this.validateApiKey(this.apiKey);
241
- if (!keyValidation.valid) {
242
- return this.createSubscriptionRequiredResponse(keyValidation);
243
- }
213
+ // Code Generation Context Detection
214
+ const codePatterns = [
215
+ /class\s+\w+/,
216
+ /interface\s+\w+/,
217
+ /public\s+|private\s+|protected\s+/,
218
+ /return\s+|return;/,
219
+ /console\.log|print\(/,
220
+ /\{[\s\S]*\}/ // code blocks
221
+ ];
244
222
 
245
- const response = await fetch(`${this.backendUrl}/api/v1/mcp/quota-status`, {
246
- method: 'GET',
247
- headers: {
248
- 'x-api-key': this.apiKey, // ✅ FIXED: Use lowercase header
249
- 'User-Agent': 'mcp-prompt-optimizer/1.3.0'
250
- }
251
- });
223
+ if (codePatterns.some(pattern => pattern.test(promptLower))) {
224
+ return 'code_generation';
225
+ }
252
226
 
253
- if (!response.ok) {
254
- return await this.handleApiError(response);
255
- }
227
+ // Structured Output Context Detection
228
+ const structuredPatterns = [
229
+ /json|xml|yaml/,
230
+ /\[.*\]|\{.*\}/, // array/object literals
231
+ /schema|format/,
232
+ /template|structure/
233
+ ];
256
234
 
257
- const result = await response.json();
258
- return {
259
- content: [{
260
- type: "text",
261
- text: this.formatQuotaStatus(result)
262
- }]
263
- };
235
+ if (structuredPatterns.some(pattern => pattern.test(promptLower))) {
236
+ return 'structured_output';
237
+ }
264
238
 
265
- } catch (error) {
266
- return {
267
- content: [{
268
- type: "text",
269
- text: `# ❌ Error Getting Quota Status\n\n${error.message}`
270
- }],
271
- isError: true
272
- };
239
+ // API Automation Context Detection
240
+ const apiPatterns = [
241
+ /api|endpoint/,
242
+ /get|post|put|delete|patch/,
243
+ /webhook|rest|graphql/,
244
+ /integration|workflow/
245
+ ];
246
+
247
+ if (apiPatterns.some(pattern => pattern.test(promptLower))) {
248
+ return 'api_automation';
273
249
  }
250
+
251
+ // Default to human communication
252
+ return 'human_communication';
274
253
  }
275
254
 
276
- async handleSearchTemplates(args) {
277
- try {
278
- const keyValidation = this.validateApiKey(this.apiKey);
279
- if (!keyValidation.valid) {
280
- return this.createSubscriptionRequiredResponse(keyValidation);
281
- }
255
+ // Enhanced goal enhancement method
256
+ enhanceGoalsForContext(originalGoals, aiContext) {
257
+ let enhancedGoals = [...originalGoals];
282
258
 
283
- const params = new URLSearchParams();
284
- if (args.query) params.append('query', args.query);
285
- if (args.ai_context) params.append('ai_context', args.ai_context);
286
- params.append('per_page', (args.limit || 5).toString());
259
+ // Remove duplicates
260
+ enhancedGoals = [...new Set(enhancedGoals)];
287
261
 
288
- const response = await fetch(`${this.backendUrl}/api/v1/templates?${params.toString()}`, {
289
- method: 'GET',
290
- headers: {
291
- 'x-api-key': this.apiKey, // ✅ FIXED: Use lowercase header
292
- 'User-Agent': 'mcp-prompt-optimizer/1.3.0'
262
+ switch (aiContext) {
263
+ case 'image_generation':
264
+ if (!enhancedGoals.includes('keyword_density')) {
265
+ enhancedGoals.push('keyword_density');
293
266
  }
294
- });
267
+ if (!enhancedGoals.includes('parameter_preservation')) {
268
+ enhancedGoals.push('parameter_preservation');
269
+ }
270
+ if (!enhancedGoals.includes('technical_accuracy')) {
271
+ enhancedGoals.push('technical_accuracy');
272
+ }
273
+ break;
295
274
 
296
- if (!response.ok) {
297
- return await this.handleApiError(response);
298
- }
275
+ case 'llm_interaction':
276
+ if (!enhancedGoals.includes('context_specificity')) {
277
+ enhancedGoals.push('context_specificity');
278
+ }
279
+ if (!enhancedGoals.includes('token_efficiency')) {
280
+ enhancedGoals.push('token_efficiency');
281
+ }
282
+ if (!enhancedGoals.includes('actionability')) {
283
+ enhancedGoals.push('actionability');
284
+ }
285
+ break;
299
286
 
300
- const result = await response.json();
301
- return {
302
- content: [{
303
- type: "text",
304
- text: this.formatTemplateSearchResults(result, args)
305
- }]
306
- };
287
+ case 'technical_automation':
288
+ if (!enhancedGoals.includes('technical_accuracy')) {
289
+ enhancedGoals.push('technical_accuracy');
290
+ }
291
+ if (!enhancedGoals.includes('parameter_preservation')) {
292
+ enhancedGoals.push('parameter_preservation');
293
+ }
294
+ if (!enhancedGoals.includes('specificity')) {
295
+ enhancedGoals.push('specificity');
296
+ }
297
+ break;
307
298
 
308
- } catch (error) {
309
- return {
310
- content: [{
311
- type: "text",
312
- text: `# ❌ Template Search Error\n\n${error.message}`
313
- }],
314
- isError: true
315
- };
316
- }
317
- }
299
+ case 'code_generation':
300
+ if (!enhancedGoals.includes('technical_accuracy')) {
301
+ enhancedGoals.push('technical_accuracy');
302
+ }
303
+ if (!enhancedGoals.includes('specificity')) {
304
+ enhancedGoals.push('specificity');
305
+ }
306
+ break;
318
307
 
319
- async handleApiError(response) {
320
- const status = response.status;
321
- let errorMessage = `API Error: ${response.statusText}`;
322
-
323
- try {
324
- const errorData = await response.json();
325
- errorMessage = errorData.detail || errorMessage;
326
- } catch (e) {
327
- // Use default message if JSON parsing fails
328
- }
308
+ case 'structured_output':
309
+ if (!enhancedGoals.includes('technical_accuracy')) {
310
+ enhancedGoals.push('technical_accuracy');
311
+ }
312
+ if (!enhancedGoals.includes('parameter_preservation')) {
313
+ enhancedGoals.push('parameter_preservation');
314
+ }
315
+ break;
329
316
 
330
- if (status === 401) {
331
- return {
332
- content: [{
333
- type: "text",
334
- text: this.createInvalidKeyResponse(errorMessage)
335
- }],
336
- isError: true
337
- };
338
- } else if (status === 402 || status === 429) {
339
- return {
340
- content: [{
341
- type: "text",
342
- text: this.createQuotaExceededResponse(errorMessage)
343
- }],
344
- isError: true
345
- };
346
- } else if (status === 500) {
347
- return {
348
- content: [{
349
- type: "text",
350
- text: `# ⚠️ Server Error\n\n${errorMessage}\n\nPlease try again in a moment. If the issue persists, contact support@promptoptimizer.help`
351
- }],
352
- isError: true
353
- };
317
+ case 'api_automation':
318
+ if (!enhancedGoals.includes('technical_accuracy')) {
319
+ enhancedGoals.push('technical_accuracy');
320
+ }
321
+ if (!enhancedGoals.includes('specificity')) {
322
+ enhancedGoals.push('specificity');
323
+ }
324
+ break;
325
+
326
+ case 'human_communication':
327
+ default:
328
+ if (!enhancedGoals.includes('clarity')) {
329
+ enhancedGoals.push('clarity');
330
+ }
331
+ if (!enhancedGoals.includes('actionability')) {
332
+ enhancedGoals.push('actionability');
333
+ }
334
+ break;
354
335
  }
355
336
 
356
- return {
357
- content: [{
358
- type: "text",
359
- text: `# ❌ Error (${status})\n\n${errorMessage}`
360
- }],
361
- isError: true
362
- };
337
+ return enhancedGoals;
363
338
  }
364
339
 
365
- createSubscriptionRequiredResponse(keyValidation) {
366
- const keyType = this.detectKeyType(this.apiKey);
367
-
368
- let content = `# 🔒 Professional MCP Server - Cloud Subscription Required
369
-
370
- This professional cloud-based MCP server requires an active subscription starting at **$2.99/month**.
371
-
372
- ## 🆓 **Get Started Free**
373
- Get your API key with **5 free optimizations** at:
374
- **https://promptoptimizer-blog.vercel.app/pricing**
375
-
376
- ## 💰 **Cloud Subscription Plans** (same AI quality, different quotas)
377
- - **Explorer ($2.99/mo):** 5,000 optimizations + individual use
378
- - **Creator ($25.99/mo):** 18,000 optimizations + team features (2 members)
379
- - **Innovator ($69.99/mo):** 75,000 optimizations + large teams (5 members) + priority support
380
-
381
- ## ✨ **Professional Cloud Features** (all plans)
382
- - 🧠 **AI Context Detection** - Automatically detects image generation, LLM interaction, technical contexts
383
- - 🎯 **10+ Optimization Techniques** - Clarity, specificity, technical accuracy, and more
384
- - 📁 **Template Management** - Auto-save high-confidence optimizations, search & reuse
385
- - 📊 **Real-time Analytics** - Confidence scoring, usage tracking, performance insights
386
- - 👥 **Team Collaboration** - Shared quotas, team templates, role-based access
387
- - 🔧 **Universal MCP** - Works with Claude Desktop, Cursor, Windsurf, Cline, VS Code, Zed, Replit
388
- - ☁️ **Cloud Processing** - No local setup, always up-to-date AI models
389
- - 🚀 **Priority Processing** - Creator and Innovator plans get faster response times
390
-
391
- ## ⚙️ **Setup Instructions**
392
- Add your API key to Claude Desktop config:
393
- \`\`\`json
394
- {
395
- "mcpServers": {
396
- "prompt-optimizer": {
397
- "command": "npx",
398
- "args": ["mcp-prompt-optimizer"],
399
- "env": {
400
- "OPTIMIZER_API_KEY": "sk-opt-your-key-here"
340
+ // ✅ Development mode mock optimization
341
+ generateMockOptimization(prompt, goals, aiContext) {
342
+ const mockResponses = {
343
+ 'image_generation': {
344
+ prefix: "Create a stunning, photorealistic",
345
+ suffix: "with ultra-detailed textures, professional lighting, and cinematic composition --ar 16:9 --v 6",
346
+ confidence: 0.92
347
+ },
348
+ 'llm_interaction': {
349
+ prefix: "Act as an expert professional who specializes in",
350
+ suffix: "Provide detailed, actionable guidance with specific examples and clear step-by-step instructions.",
351
+ confidence: 0.88
352
+ },
353
+ 'technical_automation': {
354
+ prefix: "Execute the following automated process with error handling:",
355
+ suffix: "Ensure proper logging, validation, and rollback procedures are in place.",
356
+ confidence: 0.85
357
+ },
358
+ 'code_generation': {
359
+ prefix: "Implement a robust, well-documented solution for",
360
+ suffix: "Include comprehensive error handling, type safety, and unit tests.",
361
+ confidence: 0.90
362
+ },
363
+ 'structured_output': {
364
+ prefix: "Generate a well-formatted, schema-compliant",
365
+ suffix: "Ensure proper validation, consistent formatting, and complete data coverage.",
366
+ confidence: 0.87
367
+ },
368
+ 'api_automation': {
369
+ prefix: "Design a reliable API integration that handles",
370
+ suffix: "Include proper authentication, rate limiting, and error recovery mechanisms.",
371
+ confidence: 0.89
372
+ },
373
+ 'human_communication': {
374
+ prefix: "Communicate clearly and effectively about",
375
+ suffix: "Use accessible language, provide concrete examples, and ensure actionable outcomes.",
376
+ confidence: 0.86
401
377
  }
402
- }
403
- }
404
- }
405
- \`\`\`
406
-
407
- ## 🔧 **Other MCP Clients**
408
- - **Cursor:** Add to ~/.cursor/mcp.json
409
- - **Windsurf:** Configure in settings
410
- - **Cline:** Use standard MCP configuration
411
- - **VS Code/Zed/Replit:** Standard MCP setup
412
-
413
- ## 🏢 **Team Plans Available**
414
- Team API keys (\`sk-team-*\`) provide:
415
- - Shared quotas across team members
416
- - Centralized billing and management
417
- - Team template libraries
418
- - Role-based access control
419
-
420
- ## 🔧 **Troubleshooting Tools**
421
- - **Check status:** mcp-prompt-optimizer check-status
422
- - **Validate key:** mcp-prompt-optimizer validate-key
423
- - **Clear cache:** mcp-prompt-optimizer clear-cache
424
-
425
- ## 📧 **Support**
426
- - General: support@promptoptimizer.help
427
- - Enterprise: enterprise@promptoptimizer.help
428
- - Documentation: https://promptoptimizer-blog.vercel.app/docs
429
- - Dashboard: https://promptoptimizer-blog.vercel.app/dashboard`;
430
-
431
- if (keyValidation.error === 'invalid_format') {
432
- content += `\n\n## ❌ **API Key Format Issue**
433
- Your API key format is invalid. Expected formats:
434
- - Individual: \`sk-opt-*\`
435
- - Team: \`sk-team-*\`
436
-
437
- Current key type detected: \`${keyType}\`
438
- Please get a new API key from: https://promptoptimizer-blog.vercel.app/pricing`;
439
- }
378
+ };
379
+
380
+ const template = mockResponses[aiContext] || mockResponses['human_communication'];
381
+ const optimizedPrompt = `${template.prefix} ${prompt.toLowerCase()} ${template.suffix}`;
440
382
 
441
383
  return {
442
- content: [{
443
- type: "text",
444
- text: content
445
- }],
446
- isError: true
384
+ optimized_prompt: optimizedPrompt,
385
+ confidence_score: template.confidence + (Math.random() * 0.1 - 0.05), // Add some variance
386
+ subscription_tier: 'development',
387
+ mock_mode: true,
388
+ insights: {
389
+ performance: {
390
+ clarity_improvement: 0.25,
391
+ specificity_boost: 0.30,
392
+ length_optimization: 0.15
393
+ },
394
+ analysis: {
395
+ complexity_level: prompt.length > 100 ? 'advanced' : 'intermediate',
396
+ optimization_confidence: template.confidence
397
+ },
398
+ recommendations: [
399
+ `Context automatically detected as ${aiContext}`,
400
+ `Goals enhanced for optimal ${aiContext} performance`,
401
+ "Mock optimization - connect to backend for full processing"
402
+ ]
403
+ },
404
+ template_saved: template.confidence > 0.85,
405
+ template_id: `mock-${Date.now()}`
447
406
  };
448
407
  }
449
408
 
450
- createInvalidKeyResponse(errorMessage) {
451
- return `# 🔑 Invalid API Key
409
+ // Enhanced optimize_prompt handler with fallback support
410
+ async handleOptimizePrompt(args) {
411
+ if (!args.prompt) {
412
+ throw new Error('Prompt is required');
413
+ }
452
414
 
453
- **Error:** ${errorMessage}
415
+ // Auto-detect AI context if not provided
416
+ const detectedContext = args.ai_context || this.detectAIContext(args.prompt);
417
+
418
+ // Enhance goals based on context
419
+ const originalGoals = args.goals || ['clarity'];
420
+ const enhancedGoals = this.enhanceGoalsForContext(originalGoals, detectedContext);
421
+
422
+ // Check if we should use development mode
423
+ const manager = new CloudApiKeyManager(this.apiKey, {
424
+ developmentMode: this.developmentMode,
425
+ backendUrl: this.backendUrl
426
+ });
427
+
428
+ try {
429
+ // Try to validate API key first
430
+ const validation = await manager.validateApiKey();
431
+
432
+ // If in mock/development mode, return mock response
433
+ if (validation.mock_mode || this.developmentMode) {
434
+ const mockResult = this.generateMockOptimization(args.prompt, enhancedGoals, detectedContext);
435
+ const formatted = this.formatOptimizationResult(mockResult, {
436
+ originalPrompt: args.prompt,
437
+ detectedContext,
438
+ enhancedGoals,
439
+ originalGoals
440
+ });
441
+
442
+ return {
443
+ content: [
444
+ {
445
+ type: "text",
446
+ text: formatted
447
+ }
448
+ ]
449
+ };
450
+ }
454
451
 
455
- ## 🔧 **Fix Options:**
452
+ // Prepare request for backend
453
+ const requestPayload = {
454
+ prompt: args.prompt,
455
+ goals: enhancedGoals,
456
+ ai_context: detectedContext,
457
+ enhanced_from_original: !args.ai_context
458
+ };
456
459
 
457
- 1. **Get a new API key** from: https://promptoptimizer-blog.vercel.app/pricing
458
- 2. **Check your configuration** - ensure \`OPTIMIZER_API_KEY\` is set correctly
459
- 3. **Verify key format** - should start with \`sk-opt-\` (individual) or \`sk-team-\` (team)
460
+ const result = await this.callBackendAPI('/api/v1/mcp/optimize', requestPayload);
461
+ const formatted = this.formatOptimizationResult(result, {
462
+ originalPrompt: args.prompt,
463
+ detectedContext,
464
+ enhancedGoals,
465
+ originalGoals
466
+ });
467
+
468
+ return {
469
+ content: [
470
+ {
471
+ type: "text",
472
+ text: formatted
473
+ }
474
+ ]
475
+ };
460
476
 
461
- ## ⚙️ **Claude Desktop Config:**
462
- \`\`\`json
463
- {
464
- "mcpServers": {
465
- "prompt-optimizer": {
466
- "command": "npx",
467
- "args": ["mcp-prompt-optimizer"],
468
- "env": {
469
- "OPTIMIZER_API_KEY": "sk-opt-your-actual-key-here"
477
+ } catch (error) {
478
+ // Enhanced fallback: try mock response if backend fails
479
+ if (error.message.includes('Network') || error.message.includes('DNS') || error.message.includes('timeout')) {
480
+ console.error(`Backend unavailable: ${error.message}. Providing fallback response.`);
481
+
482
+ const fallbackResult = this.generateMockOptimization(args.prompt, enhancedGoals, detectedContext);
483
+ fallbackResult.fallback_mode = true;
484
+ fallbackResult.error_reason = error.message;
485
+
486
+ const formatted = this.formatOptimizationResult(fallbackResult, {
487
+ originalPrompt: args.prompt,
488
+ detectedContext,
489
+ enhancedGoals,
490
+ originalGoals
491
+ });
492
+
493
+ return {
494
+ content: [
495
+ {
496
+ type: "text",
497
+ text: formatted
498
+ }
499
+ ]
500
+ };
470
501
  }
502
+
503
+ throw new Error(`Optimization failed: ${error.message}`);
471
504
  }
472
505
  }
473
- }
474
- \`\`\`
475
506
 
476
- ## 🔧 **Quick Diagnostic:**
477
- - **Validate your key:** mcp-prompt-optimizer validate-key
478
- - **Check full status:** mcp-prompt-optimizer check-status
479
- - **Clear cache:** mcp-prompt-optimizer clear-cache
480
-
481
- ## 🆓 **Need a New Key?**
482
- Visit https://promptoptimizer-blog.vercel.app/pricing to:
483
- - Get 5 free trial optimizations
484
- - Choose from Explorer ($2.99), Creator ($25.99), or Innovator ($69.99) plans
485
- - Set up team accounts with shared quotas
507
+ // Enhanced quota status handler with fallback
508
+ async handleGetQuotaStatus() {
509
+ const manager = new CloudApiKeyManager(this.apiKey, {
510
+ developmentMode: this.developmentMode,
511
+ backendUrl: this.backendUrl
512
+ });
486
513
 
487
- ## 📧 **Still Having Issues?**
488
- Contact support@promptoptimizer.help with your key prefix (first 8 characters) for assistance.`;
514
+ try {
515
+ const apiKeyInfo = await manager.getApiKeyInfo();
516
+ const formatted = this.formatQuotaStatus({
517
+ subscription_tier: apiKeyInfo.tier,
518
+ api_key_type: apiKeyInfo.keyType,
519
+ quota: apiKeyInfo.quota,
520
+ features: apiKeyInfo.features,
521
+ mode: apiKeyInfo.mode
522
+ });
523
+
524
+ return {
525
+ content: [
526
+ {
527
+ type: "text",
528
+ text: formatted
529
+ }
530
+ ]
531
+ };
532
+ } catch (error) {
533
+ // Fallback quota status
534
+ const fallbackStatus = {
535
+ subscription_tier: 'unknown',
536
+ api_key_type: 'unknown',
537
+ quota: { allowed: false },
538
+ features: {},
539
+ error: error.message,
540
+ fallback_mode: true
541
+ };
542
+
543
+ const formatted = this.formatQuotaStatus(fallbackStatus);
544
+
545
+ return {
546
+ content: [
547
+ {
548
+ type: "text",
549
+ text: formatted
550
+ }
551
+ ]
552
+ };
553
+ }
489
554
  }
490
555
 
491
- createQuotaExceededResponse(errorMessage) {
492
- return `# 📊 Quota Exceeded
493
-
494
- **Error:** ${errorMessage}
556
+ // Enhanced template search with fallback
557
+ async handleSearchTemplates(args) {
558
+ const requestPayload = {
559
+ query: args.query || '',
560
+ ai_context: args.ai_context || null,
561
+ limit: args.limit || 5
562
+ };
495
563
 
496
- ## 🚀 **Upgrade Options:**
564
+ try {
565
+ const result = await this.callBackendAPI('/api/v1/mcp/search-templates', requestPayload);
566
+ const formatted = this.formatTemplateSearchResults(result, args);
567
+
568
+ return {
569
+ content: [
570
+ {
571
+ type: "text",
572
+ text: formatted
573
+ }
574
+ ]
575
+ };
576
+ } catch (error) {
577
+ // Fallback template search response
578
+ const fallbackResult = {
579
+ templates: [],
580
+ total: 0,
581
+ message: "Template search unavailable - backend connection failed",
582
+ error: error.message,
583
+ fallback_mode: true
584
+ };
585
+
586
+ const formatted = this.formatTemplateSearchResults(fallbackResult, args);
587
+
588
+ return {
589
+ content: [
590
+ {
591
+ type: "text",
592
+ text: formatted
593
+ }
594
+ ]
595
+ };
596
+ }
597
+ }
497
598
 
498
- ### Current Plans:
499
- - **Explorer ($2.99/mo):** 5,000 optimizations
500
- - **Creator ($25.99/mo):** 18,000 optimizations + team features
501
- - **Innovator ($69.99/mo):** 75,000 optimizations + large teams
599
+ // Enhanced backend API call with better timeout and error handling
600
+ async callBackendAPI(endpoint, data, method = 'POST') {
601
+ return new Promise((resolve, reject) => {
602
+ const url = `${this.backendUrl}${endpoint}`;
603
+
604
+ const options = {
605
+ method: method,
606
+ headers: {
607
+ 'x-api-key': this.apiKey,
608
+ 'Content-Type': 'application/json',
609
+ 'User-Agent': `mcp-prompt-optimizer/${packageJson.version}`,
610
+ 'Connection': 'close'
611
+ },
612
+ timeout: this.requestTimeout
613
+ };
502
614
 
503
- ## 📈 **Upgrade Now:**
504
- Visit https://promptoptimizer-blog.vercel.app/dashboard to:
505
- - View your current usage
506
- - Upgrade to a higher plan
507
- - Manage team subscriptions
615
+ const req = https.request(url, options, (res) => {
616
+ let responseData = '';
617
+
618
+ res.on('data', (chunk) => {
619
+ responseData += chunk;
620
+ });
621
+
622
+ res.on('end', () => {
623
+ try {
624
+ if (res.statusCode === 200) {
625
+ const result = JSON.parse(responseData);
626
+ resolve(result);
627
+ } else {
628
+ let errorMessage;
629
+ try {
630
+ const error = JSON.parse(responseData);
631
+ errorMessage = error.detail || error.message || `HTTP ${res.statusCode}`;
632
+ } catch {
633
+ errorMessage = `HTTP ${res.statusCode}: ${responseData}`;
634
+ }
635
+ reject(new Error(errorMessage));
636
+ }
637
+ } catch (parseError) {
638
+ reject(new Error(`Invalid response: ${parseError.message}`));
639
+ }
640
+ });
641
+ });
508
642
 
509
- ## 📅 **Quota Reset:**
510
- Individual quotas reset monthly on your billing date.
511
- Team quotas reset monthly on the team billing cycle.
643
+ req.on('error', (error) => {
644
+ if (error.code === 'ENOTFOUND') {
645
+ reject(new Error(`DNS resolution failed: Cannot resolve backend server`));
646
+ } else if (error.code === 'ECONNREFUSED') {
647
+ reject(new Error(`Connection refused: Backend server may be down`));
648
+ } else if (error.code === 'ETIMEDOUT') {
649
+ reject(new Error(`Connection timeout: Backend server is not responding`));
650
+ } else {
651
+ reject(new Error(`Network error: ${error.message}`));
652
+ }
653
+ });
512
654
 
513
- ## 🔧 **Check Usage:**
514
- - **Detailed status:** mcp-prompt-optimizer check-status
515
- - **Current quota:** Use the \`get_quota_status\` tool
516
- - **Usage trends:** Visit your dashboard
655
+ req.on('timeout', () => {
656
+ req.destroy();
657
+ reject(new Error('Request timeout - backend may be unavailable'));
658
+ });
517
659
 
518
- ## 💡 **Tips:**
519
- - Consider upgrading if you regularly hit limits
520
- - Team plans offer better value for multiple users
521
- - Pro tip: Use templates to avoid re-optimizing similar prompts
660
+ req.setTimeout(this.requestTimeout);
522
661
 
523
- ## 📧 **Need Help?**
524
- Contact support@promptoptimizer.help for usage optimization advice or enterprise solutions.`;
662
+ if (method !== 'GET' && data) {
663
+ req.write(JSON.stringify(data));
664
+ }
665
+
666
+ req.end();
667
+ });
525
668
  }
526
669
 
527
- formatOptimizationResult(result, originalArgs) {
528
- let output = `# 🎯 Optimized Prompt\n\n${result.optimized_prompt}\n\n`;
670
+ // Enhanced optimization result formatting
671
+ formatOptimizationResult(result, context) {
672
+ let output = `# 🎯 Optimized Prompt\n\n`;
673
+
674
+ output += `${result.optimized_prompt}\n\n`;
529
675
 
530
- // Same response for ALL users - no tier differences in optimization quality
531
676
  output += `**Confidence:** ${(result.confidence_score * 100).toFixed(1)}%\n`;
677
+ output += `**Plan:** ${result.subscription_tier || 'Unknown'}\n`;
532
678
 
533
- if (result.tier) {
534
- output += `**Plan:** ${result.tier.charAt(0).toUpperCase() + result.tier.slice(1)}\n`;
535
- }
536
-
537
- // AI Context information
538
- if (originalArgs.ai_context || result.ai_context) {
539
- const context = originalArgs.ai_context || result.ai_context;
679
+ if (context.detectedContext) {
540
680
  const contextLabels = {
541
681
  'human_communication': 'Human Communication',
542
- 'llm_interaction': 'LLM Interaction',
682
+ 'llm_interaction': 'LLM Interaction',
543
683
  'image_generation': 'Image Generation',
544
684
  'technical_automation': 'Technical Automation',
545
685
  'structured_output': 'Structured Output',
546
686
  'code_generation': 'Code Generation',
547
687
  'api_automation': 'API Automation'
548
688
  };
549
- output += `**AI Context:** ${contextLabels[context] || context}\n`;
689
+ output += `**AI Context:** ${contextLabels[context.detectedContext] || context.detectedContext}\n`;
550
690
  }
551
-
552
- // Template auto-saving (available for ALL users)
553
- if (result.template_saved) {
554
- output += `\n✅ **Auto-saved as template** (ID: ${result.template_id})\n`;
555
- output += `*High-confidence optimization automatically saved for future use*\n`;
691
+
692
+ if (context.enhancedGoals && context.originalGoals) {
693
+ const wasEnhanced = context.enhancedGoals.length > context.originalGoals.length;
694
+ output += `**Goals Enhanced:** ${wasEnhanced ? 'Yes' : 'No'}`;
695
+ if (wasEnhanced) {
696
+ output += ` (${context.originalGoals.join(', ')} → ${context.enhancedGoals.join(', ')})`;
697
+ }
698
+ output += `\n`;
556
699
  }
557
700
 
558
- // Template save errors (graceful handling)
559
- if (result.template_save_error) {
560
- output += `\n⚠️ **Template save failed:** ${result.template_save_error}\n`;
701
+ // Mode indicators
702
+ if (result.mock_mode) {
703
+ output += `**Mode:** Development/Mock\n`;
704
+ } else if (result.fallback_mode) {
705
+ output += `**Mode:** Fallback (Backend Unavailable)\n`;
561
706
  }
562
707
 
563
- // Similar templates found (available for ALL users)
564
- if (result.templates_found && result.templates_found.length > 0) {
565
- output += `\n## 📋 Similar Templates Found\n`;
566
- result.templates_found.forEach((t, index) => {
567
- output += `${index + 1}. **${t.title}** (${(t.confidence_score * 100).toFixed(1)}% similarity)\n`;
708
+ output += `\n`;
709
+
710
+ // AI Context Benefits section
711
+ if (context.detectedContext && context.detectedContext !== 'human_communication') {
712
+ output += `# 🧠 AI Context Benefits Applied\n`;
713
+
714
+ switch (context.detectedContext) {
715
+ case 'image_generation':
716
+ output += `- ✅ Technical parameters preserved (--ar, --v, etc.)\n`;
717
+ output += `- ✅ Visual keywords optimized for better generation\n`;
718
+ output += `- ✅ Art terminology enhanced\n`;
719
+ break;
720
+ case 'llm_interaction':
721
+ output += `- ✅ Role clarity improved\n`;
722
+ output += `- ✅ Context specificity enhanced\n`;
723
+ output += `- ✅ Token efficiency optimized\n`;
724
+ break;
725
+ case 'technical_automation':
726
+ output += `- ✅ Technical accuracy preserved\n`;
727
+ output += `- ✅ Command syntax protected\n`;
728
+ output += `- ✅ Automation flow optimized\n`;
729
+ break;
730
+ default:
731
+ output += `- ✅ Context-specific optimization applied\n`;
732
+ }
733
+ output += `\n`;
734
+ } else {
735
+ output += `# 🧠 AI Context Benefits Applied\n`;
736
+ output += `- ✅ Standard optimization rules applied\n`;
737
+ output += `- ✅ Human communication optimized\n\n`;
738
+ }
739
+
740
+ // Template auto-save notification
741
+ if (result.template_saved && result.template_id) {
742
+ output += `✅ Auto-saved as template (ID: ${result.template_id})\n`;
743
+ if (result.mock_mode) {
744
+ output += `*Mock template - connect to backend for persistent storage*\n\n`;
745
+ } else {
746
+ output += `*High-confidence optimization automatically saved for future use*\n\n`;
747
+ }
748
+ }
749
+
750
+ // Similar templates section
751
+ if (result.similar_templates && result.similar_templates.length > 0) {
752
+ output += `# 📋 Similar Templates Found\n`;
753
+ result.similar_templates.forEach((template, index) => {
754
+ output += `${index + 1}. ${template.title} (${(template.similarity * 100).toFixed(1)}% similarity)\n`;
568
755
  });
569
- output += `*Use \`search_templates\` tool to explore your template library*\n`;
756
+ output += `*Use \`search_templates\` tool to explore your template library*\n\n`;
570
757
  }
571
758
 
572
- // Optimization insights (available for ALL users)
573
- if (result.optimization_insights) {
574
- output += `\n## 📊 Optimization Insights\n`;
575
- const insights = result.optimization_insights;
759
+ // Optimization insights
760
+ if (result.insights) {
761
+ output += `# 📊 Optimization Insights\n\n`;
576
762
 
577
- // Performance metrics
578
- if (insights.improvement_metrics) {
579
- output += `\n**Performance Analysis:**\n`;
580
- const metrics = insights.improvement_metrics;
581
- output += `- Clarity improvement: +${(metrics.clarity_improvement * 100).toFixed(1)}%\n`;
582
- output += `- Specificity boost: +${(metrics.specificity_improvement * 100).toFixed(1)}%\n`;
583
- output += `- Length optimization: ${(metrics.length_optimization * 100).toFixed(1)}%\n`;
763
+ if (result.insights.performance) {
764
+ output += `**Performance Analysis:**\n`;
765
+ const perf = result.insights.performance;
766
+ if (perf.clarity_improvement) output += `- Clarity improvement: +${(perf.clarity_improvement * 100).toFixed(1)}%\n`;
767
+ if (perf.specificity_boost) output += `- Specificity boost: +${(perf.specificity_boost * 100).toFixed(1)}%\n`;
768
+ if (perf.length_optimization) output += `- Length optimization: +${(perf.length_optimization * 100).toFixed(1)}%\n`;
769
+ output += `\n`;
584
770
  }
585
-
586
- // User patterns analysis
587
- if (insights.user_patterns) {
588
- output += `\n**Prompt Analysis:**\n`;
589
- output += `- Complexity level: ${insights.user_patterns.prompt_complexity}\n`;
590
- output += `- Optimization confidence: ${insights.user_patterns.optimization_confidence}\n`;
771
+
772
+ if (result.insights.analysis) {
773
+ output += `**Prompt Analysis:**\n`;
774
+ const analysis = result.insights.analysis;
775
+ if (analysis.complexity_level) output += `- Complexity level: ${analysis.complexity_level}\n`;
776
+ if (result.confidence_score) output += `- Optimization confidence: ${(result.confidence_score * 100).toFixed(1)}%\n`;
777
+ output += `\n`;
591
778
  }
592
-
593
- // AI recommendations
594
- if (insights.recommendations && insights.recommendations.length > 0) {
595
- output += `\n**AI Recommendations:**\n`;
596
- insights.recommendations.forEach(rec => {
779
+
780
+ if (result.insights.recommendations) {
781
+ output += `**AI Recommendations:**\n`;
782
+ result.insights.recommendations.forEach(rec => {
597
783
  output += `- ${rec}\n`;
598
784
  });
785
+ output += `\n`;
599
786
  }
600
-
601
- output += `*Professional analytics and improvement recommendations*\n`;
787
+
788
+ const insightType = result.mock_mode ? 'Mock analytics and recommendations' : 'Professional analytics and improvement recommendations';
789
+ output += `*${insightType}*\n\n`;
602
790
  }
603
791
 
604
- // Professional footer
605
- output += `\n---\n*Professional cloud-based AI optimization*`;
606
- output += `\n💡 **Manage account:** https://promptoptimizer-blog.vercel.app/dashboard`;
607
- output += `\n📊 **Check quota:** Use \`get_quota_status\` tool`;
608
- output += `\n🔍 **Search templates:** Use \`search_templates\` tool`;
609
-
792
+ // Fallback mode warning
793
+ if (result.fallback_mode) {
794
+ output += `⚠️ **Fallback Mode Active**\n`;
795
+ output += `Backend temporarily unavailable: ${result.error_reason}\n`;
796
+ output += `Using local optimization with reduced functionality.\n\n`;
797
+ }
798
+
799
+ output += `---\n`;
800
+ const modeText = result.mock_mode ? 'Development mode optimization' :
801
+ result.fallback_mode ? 'Fallback optimization (backend unavailable)' :
802
+ 'Professional cloud-based AI optimization with context awareness';
803
+ output += `*${modeText}*\n`;
804
+ output += `💡 Manage account & configure models: https://promptoptimizer-blog.vercel.app/dashboard\n`;
805
+ output += `📊 Check quota: Use \`get_quota_status\` tool\n`;
806
+ output += `🔍 Search templates: Use \`search_templates\` tool\n`;
807
+
610
808
  return output;
611
809
  }
612
810
 
811
+ // Enhanced quota status formatting
613
812
  formatQuotaStatus(result) {
614
- let output = `# 📊 Subscription Quota Status\n\n`;
813
+ let output = `# 📊 Subscription Status\n\n`;
615
814
 
616
- // Plan information
617
- output += `**Plan:** ${result.tier.charAt(0).toUpperCase() + result.tier.slice(1)}\n`;
815
+ output += `**Plan:** ${result.subscription_tier || 'Unknown'}\n`;
816
+ output += `**API Key Type:** ${result.api_key_type || 'Individual'}\n`;
618
817
 
619
- // Quota details
620
- if (result.quota.unlimited) {
621
- output += `**Usage:** Unlimited optimizations\n`;
622
- } else {
623
- output += `**Usage:** ${result.quota.used.toLocaleString()} / ${result.quota.limit.toLocaleString()} optimizations\n`;
624
- output += `**Remaining:** ${result.quota.remaining.toLocaleString()} optimizations\n`;
625
- output += `**Usage:** ${result.quota.usage_percentage}% of monthly quota\n`;
626
- }
627
-
628
- // Status indicator
629
- const status = result.status;
630
- const statusEmoji = {
631
- 'healthy': '✅',
632
- 'warning': '⚠️',
633
- 'critical': '🔴'
634
- };
635
- output += `**Status:** ${statusEmoji[status] || '❓'} ${status.charAt(0).toUpperCase() + status.slice(1)}\n`;
636
-
637
- // Context information
638
- if (result.api_key_type === 'team') {
639
- output += `\n## 👥 Team Information\n`;
640
- if (result.team_info) {
641
- output += `**Team:** ${result.team_info.team_name || 'Unknown'}\n`;
642
- output += `**Team ID:** ${result.team_info.team_id}\n`;
643
- }
644
- output += `*This is a team subscription with shared quota*\n`;
645
- } else {
646
- output += `\n## 👤 Individual Information\n`;
647
- output += `**Account Type:** Individual subscription\n`;
648
- if (result.user_info) {
649
- output += `**User ID:** ${result.user_info.user_id}\n`;
818
+ if (result.mode) {
819
+ const modes = [];
820
+ if (result.mode.development) modes.push('Development');
821
+ if (result.mode.mock) modes.push('Mock');
822
+ if (result.mode.fallback) modes.push('Fallback');
823
+ if (result.mode.offline) modes.push('Offline');
824
+
825
+ if (modes.length > 0) {
826
+ output += `**Mode:** ${modes.join(', ')}\n`;
650
827
  }
651
828
  }
652
829
 
653
- // Features available
654
- output += `\n## ✨ Features Available\n`;
655
- const features = result.features_available;
656
- if (features.professional_optimization) output += `- ✅ Professional AI optimization\n`;
657
- if (features.auto_save_templates) output += `- ✅ Template auto-save\n`;
658
- if (features.template_search) output += `- ✅ Template search\n`;
659
- if (features.optimization_insights) output += `- ✅ Optimization insights\n`;
660
-
661
- // Upgrade suggestions
662
- if (status === 'warning' || status === 'critical') {
663
- output += `\n## 🚀 Upgrade Recommendations\n`;
664
- output += `Consider upgrading to a higher tier for more optimizations:\n`;
665
- output += `- **Creator ($25.99/mo):** 18,000 optimizations + team features\n`;
666
- output += `- **Innovator ($69.99/mo):** 75,000 optimizations + priority support\n`;
667
- output += `\n**Upgrade:** https://promptoptimizer-blog.vercel.app/dashboard\n`;
830
+ if (result.quota) {
831
+ if (result.quota.unlimited) {
832
+ output += `**Usage:** Unlimited\n`;
833
+ } else if (result.quota.allowed) {
834
+ const used = result.quota.used || 0;
835
+ const limit = result.quota.limit || 0;
836
+ const remaining = result.quota.remaining || 0;
837
+ const percentage = limit > 0 ? ((used / limit) * 100).toFixed(1) : 0;
838
+
839
+ output += `**Usage:** ${used.toLocaleString()}/${limit.toLocaleString()} (${percentage}% used)\n`;
840
+ output += `**Remaining:** ${remaining.toLocaleString()} optimizations\n`;
841
+ } else {
842
+ output += `**Usage:** Quota check failed\n`;
843
+ }
668
844
  }
669
845
 
670
- output += `\n---\n*Use \`optimize_prompt\` to start optimizing with AI context detection*`;
671
- output += `\n*Use \`search_templates\` to find and reuse saved optimizations*`;
672
-
673
- return output;
674
- }
675
-
676
- formatTemplateSearchResults(result, originalArgs) {
677
- let output = `# 🔍 Template Search Results\n\n`;
678
-
679
- if (!result.templates || result.templates.length === 0) {
680
- output += `No templates found`;
681
- if (originalArgs.query) {
682
- output += ` matching "${originalArgs.query}"`;
683
- }
684
- if (originalArgs.ai_context) {
685
- output += ` in context "${originalArgs.ai_context}"`;
686
- }
687
- output += `.\n\n`;
688
- output += `💡 **Tips:**\n`;
689
- output += `- Try broader search terms\n`;
690
- output += `- Remove AI context filter\n`;
691
- output += `- Use \`optimize_prompt\` to create new templates\n`;
692
- return output;
846
+ if (result.billing_cycle) {
847
+ output += `**Billing Cycle:** ${result.billing_cycle}\n`;
693
848
  }
694
849
 
695
- output += `Found ${result.templates.length} template(s)`;
696
- if (originalArgs.query) {
697
- output += ` matching "${originalArgs.query}"`;
850
+ if (result.next_reset) {
851
+ const resetDate = new Date(result.next_reset).toLocaleDateString();
852
+ output += `**Quota Resets:** ${resetDate}\n`;
698
853
  }
699
- output += `:\n\n`;
700
854
 
701
- result.templates.forEach((template, index) => {
702
- output += `## ${index + 1}. ${template.title}\n`;
703
-
704
- // Template metadata
705
- if (template.ai_context_detected) {
706
- const contextLabels = {
707
- 'human_communication': 'Human Communication',
708
- 'llm_interaction': 'LLM Interaction',
709
- 'image_generation': 'Image Generation',
710
- 'technical_automation': 'Technical Automation',
711
- 'structured_output': 'Structured Output',
712
- 'code_generation': 'Code Generation',
713
- 'api_automation': 'API Automation'
714
- };
715
- output += `**Context:** ${contextLabels[template.ai_context_detected] || template.ai_context_detected}\n`;
716
- }
717
-
718
- if (template.confidence_score) {
719
- output += `**Confidence:** ${(template.confidence_score * 100).toFixed(1)}%\n`;
720
- }
721
-
722
- if (template.tags && template.tags.length > 0) {
723
- output += `**Tags:** ${template.tags.join(', ')}\n`;
724
- }
725
-
726
- // Show optimized prompt preview
727
- const preview = template.optimized_prompt.length > 200
728
- ? template.optimized_prompt.substring(0, 200) + '...'
729
- : template.optimized_prompt;
730
- output += `**Optimized Prompt:** ${preview}\n`;
855
+ output += `\n`;
856
+
857
+ // Features section
858
+ if (result.features) {
859
+ output += `## ✨ Available Features\n`;
860
+ const features = result.features;
731
861
 
732
- if (template.created_at) {
733
- const date = new Date(template.created_at).toLocaleDateString();
734
- output += `**Created:** ${date}\n`;
735
- }
862
+ if (features.ai_context_detection) output += `✅ AI Context Detection\n`;
863
+ if (features.template_management) output += `✅ Template Management\n`;
864
+ if (features.team_collaboration) output += `✅ Team Collaboration\n`;
865
+ if (features.priority_processing) output += `✅ Priority Processing\n`;
866
+ if (features.analytics_dashboard) output += `✅ Analytics Dashboard\n`;
867
+ if (features.development_mode) output += `🔧 Development Mode\n`;
868
+ if (features.testing_mode) output += `🧪 Testing Mode\n`;
736
869
 
737
870
  output += `\n`;
738
- });
739
-
740
- // Show pagination info
741
- if (result.total_pages > 1) {
742
- output += `---\n`;
743
- output += `**Page ${result.page} of ${result.total_pages}** (${result.total} total templates)\n`;
744
- output += `*Adjust \`limit\` parameter to see more results per search*\n\n`;
745
871
  }
746
-
747
- output += `💡 **Template Usage:**\n`;
748
- output += `- Copy optimized prompts for immediate use\n`;
749
- output += `- Study successful patterns for your context\n`;
750
- output += `- Create variations based on proven templates\n`;
751
- output += `\n*Visit https://promptoptimizer-blog.vercel.app/dashboard to manage all templates*`;
752
-
753
- return output;
754
- }
755
872
 
756
- async run() {
757
- const transport = new StdioServerTransport();
758
- await this.server.connect(transport);
759
- }
873
+ // Error handling
874
+ if (result.error) {
875
+ output += `⚠️ **Status Check Error:**\n`;
876
+ output += `${result.error}\n\n`;
877
+
878
+ if (result.fallback_mode) {
879
+ output += `Using cached information. Check network connection and try again.\n\n`;
880
+ }
881
+ }
882
+
883
+ // Team info
884
+ if (result.team_info && result.api_key_type === 'team') {
885
+ output += `## 👥 Team Information\n`;
886
+ output += `**Team Size:** ${result.team_info.members || 0} members\n`;
887
+ output += `**API Keys:** ${result.team_info.api_keys || 0} total\n`;
888
+ output += `\n`;
889
+ }
890
+
891
+ output += `💡 **Manage Account & Configure Models:** https://promptoptimizer-blog.vercel.app/dashboard\n`;
892
+ output += `📈 **Upgrade Plans:** https://promptoptimizer-blog.vercel.app/pricing\n`;
893
+
894
+ if (!result.quota || (!result.quota.unlimited && result.quota.remaining < 100)) {
895
+ output += `\n⚠️ **Low Quota Warning**\n`;
896
+ output += `Consider upgrading your plan for more optimizations.\n`;
897
+ }
898
+
899
+ return output;
900
+ }
901
+
902
+ formatTemplateSearchResults(result, originalArgs) {
903
+ let output = `# 🔍 Template Search Results\n\n`;
904
+
905
+ if (result.fallback_mode) {
906
+ output += `⚠️ **Template search temporarily unavailable**\n`;
907
+ output += `Backend connection failed: ${result.error}\n`;
908
+ output += `Please try again when network connectivity is restored.\n\n`;
909
+ return output;
910
+ }
911
+
912
+ if (!result.templates || result.templates.length === 0) {
913
+ output += `No templates found`;
914
+ if (originalArgs.query) {
915
+ output += ` matching "${originalArgs.query}"`;
916
+ }
917
+ if (originalArgs.ai_context) {
918
+ output += ` in context "${originalArgs.ai_context}"`;
919
+ }
920
+ output += `.\n\n`;
921
+ output += `💡 **Tips:**\n`;
922
+ output += `- Try broader search terms\n`;
923
+ output += `- Remove AI context filter\n`;
924
+ output += `- Use \`optimize_prompt\` to create new templates\n`;
925
+ return output;
926
+ }
927
+
928
+ output += `Found ${result.templates.length} template(s)`;
929
+ if (originalArgs.query) {
930
+ output += ` matching "${originalArgs.query}"`;
931
+ }
932
+ output += `:\n\n`;
933
+
934
+ result.templates.forEach((template, index) => {
935
+ output += `## ${index + 1}. ${template.title}\n`;
936
+
937
+ // Template metadata
938
+ if (template.ai_context_detected) {
939
+ const contextLabels = {
940
+ 'human_communication': 'Human Communication',
941
+ 'llm_interaction': 'LLM Interaction',
942
+ 'image_generation': 'Image Generation',
943
+ 'technical_automation': 'Technical Automation',
944
+ 'structured_output': 'Structured Output',
945
+ 'code_generation': 'Code Generation',
946
+ 'api_automation': 'API Automation'
947
+ };
948
+ output += `**Context:** ${contextLabels[template.ai_context_detected] || template.ai_context_detected}\n`;
949
+ }
950
+
951
+ if (template.confidence_score) {
952
+ output += `**Confidence:** ${(template.confidence_score * 100).toFixed(1)}%\n`;
953
+ }
954
+
955
+ if (template.tags && template.tags.length > 0) {
956
+ output += `**Tags:** ${template.tags.join(', ')}\n`;
957
+ }
958
+
959
+ // Show optimized prompt preview
960
+ const preview = template.optimized_prompt.length > 200
961
+ ? template.optimized_prompt.substring(0, 200) + '...'
962
+ : template.optimized_prompt;
963
+ output += `**Optimized Prompt:** ${preview}\n`;
964
+
965
+ if (template.created_at) {
966
+ const date = new Date(template.created_at).toLocaleDateString();
967
+ output += `**Created:** ${date}\n`;
968
+ }
969
+
970
+ output += `\n`;
971
+ });
972
+
973
+ // Show pagination info
974
+ if (result.total_pages > 1) {
975
+ output += `---\n`;
976
+ output += `**Page ${result.page} of ${result.total_pages}** (${result.total} total templates)\n`;
977
+ output += `*Adjust \`limit\` parameter to see more results per search*\n\n`;
978
+ }
979
+
980
+ output += `💡 **Template Usage:**\n`;
981
+ output += `- Copy optimized prompts for immediate use\n`;
982
+ output += `- Study successful patterns for your context\n`;
983
+ output += `- Create variations based on proven templates\n`;
984
+ output += `\n*Visit https://promptoptimizer-blog.vercel.app/dashboard to manage all templates*`;
985
+
986
+ return output;
987
+ }
988
+
989
+ async run() {
990
+ const transport = new StdioServerTransport();
991
+ await this.server.connect(transport);
992
+ }
760
993
  }
761
994
 
762
- // ✅ NEW: Startup validation function (following local pattern)
995
+ // ✅ Enhanced startup validation function with development mode support
763
996
  async function startValidatedMCPServer() {
764
- console.error('🚀 MCP Prompt Optimizer - Professional Cloud Server v1.3.0\n');
765
-
766
- try {
767
- // Step 1: Get API key
768
- const apiKey = process.env.OPTIMIZER_API_KEY;
769
-
770
- if (!apiKey) {
771
- console.error('❌ API key required');
772
- console.error('\n💡 Get your API key in 30 seconds:');
773
- console.error(' 1. Visit: https://promptoptimizer-blog.vercel.app/pricing');
774
- console.error(' 2. Get your free trial (5 optimizations)');
775
- console.error(' 3. Set: export OPTIMIZER_API_KEY=sk-opt-...');
776
- console.error(' 4. Run: mcp-prompt-optimizer');
777
- console.error('\n🎯 Plans: Explorer ($2.99), Creator ($25.99), Innovator ($69.99)');
778
- process.exit(1);
779
- }
997
+ console.error(`🚀 MCP Prompt Optimizer - Professional Cloud Server v${packageJson.version}\n`);
998
+
999
+ try {
1000
+ // Step 1: Get API key
1001
+ const apiKey = process.env.OPTIMIZER_API_KEY;
1002
+
1003
+ if (!apiKey) {
1004
+ console.error('❌ API key required');
1005
+ console.error('\n💡 Get your API key in 30 seconds:');
1006
+ console.error(' 1. Visit: https://promptoptimizer-blog.vercel.app/pricing');
1007
+ console.error(' 2. Get your free trial (5 optimizations)');
1008
+ console.error(' 3. Set: export OPTIMIZER_API_KEY=sk-opt-...');
1009
+ console.error(' 4. Run: mcp-prompt-optimizer');
1010
+ console.error('\n🔧 Development mode available with sk-dev-* keys');
1011
+ console.error('🎯 Plans: Explorer ($2.99), Creator ($25.99), Innovator ($69.99)');
1012
+ process.exit(1);
1013
+ }
1014
+
1015
+ // Step 2: Enhanced validation with development mode support
1016
+ const developmentMode = process.env.NODE_ENV === 'development' || process.env.OPTIMIZER_DEV_MODE === 'true';
1017
+ const manager = new CloudApiKeyManager(apiKey, { developmentMode });
1018
+
1019
+ console.error('🔧 Validating API key and checking connectivity...\n');
1020
+
1021
+ try {
1022
+ const validation = await manager.validateAndPrepare();
1023
+
1024
+ // Step 3: Start the MCP server with validated context
1025
+ console.error('🔧 Starting MCP server...\n');
1026
+
1027
+ // Create and start the MCP server instance
1028
+ const mcpServer = new MCPPromptOptimizer();
1029
+
1030
+ console.error('✅ MCP server ready for connections');
1031
+
1032
+ // Enhanced status reporting
1033
+ const mode = validation.mode;
1034
+ const modeIndicators = [];
1035
+ if (mode.development) modeIndicators.push('Development');
1036
+ if (mode.mock) modeIndicators.push('Mock');
1037
+ if (mode.fallback) modeIndicators.push('Fallback');
1038
+ if (mode.offline) modeIndicators.push('Offline');
1039
+
1040
+ const modeText = modeIndicators.length > 0 ? ` (${modeIndicators.join(', ')})` : '';
1041
+ const quotaText = validation.quotaStatus.unlimited ? 'Unlimited' : `${validation.quotaStatus.remaining}/${validation.quotaStatus.limit} remaining`;
1042
+
1043
+ console.error(`📊 Plan: ${validation.tier}${modeText} | Quota: ${quotaText}`);
1044
+ console.error('💡 Connect from your MCP client (Claude Desktop, Cursor, etc.)\n');
1045
+
1046
+ // Start the server
1047
+ await mcpServer.run();
1048
+
1049
+ } catch (validationError) {
1050
+ // Enhanced fallback handling
1051
+ console.error(`⚠️ API validation failed: ${validationError.message}`);
1052
+
1053
+ // Check if we can run in fallback mode
1054
+ if (validationError.message.includes('Network') || validationError.message.includes('DNS') || validationError.message.includes('timeout')) {
1055
+ console.error('\n🔄 Attempting to start in fallback mode...');
1056
+
1057
+ try {
1058
+ const mcpServer = new MCPPromptOptimizer();
1059
+ console.error('✅ MCP server started in fallback mode');
1060
+ console.error('📊 Plan: Fallback | Limited functionality due to network issues');
1061
+ console.error('💡 Connect from your MCP client - basic optimization available\n');
1062
+
1063
+ await mcpServer.run();
1064
+ } catch (fallbackError) {
1065
+ console.error(`❌ Failed to start even in fallback mode: ${fallbackError.message}`);
1066
+ throw validationError; // Throw original error
1067
+ }
1068
+ } else {
1069
+ throw validationError;
1070
+ }
1071
+ }
780
1072
 
781
- // Step 2: Validate API key and check quota
782
- const manager = new CloudApiKeyManager(apiKey);
783
- const validation = await manager.validateAndPrepare();
784
-
785
- // Step 3: Start the MCP server with validated context
786
- console.error('🔧 Starting MCP server...\n');
787
-
788
- // Create and start the MCP server instance
789
- const mcpServer = new MCPPromptOptimizer();
790
-
791
- console.error(' MCP server ready for connections');
792
- console.error(`📊 Plan: ${validation.tier} | Quota: ${validation.quotaStatus.unlimited ? 'Unlimited' : `${validation.quotaStatus.remaining}/${validation.quotaStatus.limit} remaining`}`);
793
- console.error('💡 Connect from your MCP client (Claude Desktop, Cursor, etc.)\n');
794
-
795
- // Start the server
796
- await mcpServer.run();
797
-
798
- } catch (error) {
799
- console.error(`❌ Failed to start MCP server: ${error.message}`);
800
-
801
- if (error.message.includes('quota exceeded')) {
802
- console.error('\n💎 Upgrade for more optimizations:');
803
- console.error(' https://promptoptimizer-blog.vercel.app/pricing');
804
- } else if (error.message.includes('validation failed') || error.message.includes('Invalid')) {
805
- console.error('\n🛠️ Troubleshooting:');
806
- console.error(' 1. Check your API key: mcp-prompt-optimizer validate-key');
807
- console.error(' 2. Clear cache: mcp-prompt-optimizer clear-cache');
808
- console.error(' 3. Get new key: https://promptoptimizer-blog.vercel.app/pricing');
809
- } else if (error.message.includes('Network error')) {
810
- console.error('\n🌐 Connection Issue:');
811
- console.error(' - Check your internet connection');
812
- console.error(' - Verify firewall/proxy settings');
813
- console.error(' - Try again in a moment');
814
- } else {
815
- console.error('\n🔧 General Troubleshooting:');
816
- console.error(' 1. Clear cache: mcp-prompt-optimizer clear-cache');
817
- console.error(' 2. Check status: mcp-prompt-optimizer check-status');
818
- console.error(' 3. Contact support: support@promptoptimizer.help');
819
- }
820
-
821
- process.exit(1);
822
- }
1073
+ } catch (error) {
1074
+ console.error(`❌ Failed to start MCP server: ${error.message}`);
1075
+
1076
+ if (error.message.includes('quota exceeded')) {
1077
+ console.error('\n💎 Upgrade for more optimizations:');
1078
+ console.error(' https://promptoptimizer-blog.vercel.app/pricing');
1079
+ } else if (error.message.includes('validation failed') || error.message.includes('Invalid')) {
1080
+ console.error('\n🛠️ Troubleshooting:');
1081
+ console.error(' 1. Check your API key: mcp-prompt-optimizer validate-key');
1082
+ console.error(' 2. Clear cache: mcp-prompt-optimizer clear-cache');
1083
+ console.error(' 3. Get new key: https://promptoptimizer-blog.vercel.app/pricing');
1084
+ console.error(' 4. Try development mode: export OPTIMIZER_DEV_MODE=true');
1085
+ } else if (error.message.includes('Network error') || error.message.includes('DNS')) {
1086
+ console.error('\n🌐 Connection Issue:');
1087
+ console.error(' - Check your internet connection');
1088
+ console.error(' - Verify firewall/proxy settings');
1089
+ console.error(' - Try development mode: export OPTIMIZER_DEV_MODE=true');
1090
+ console.error(' - Try again in a moment');
1091
+ } else {
1092
+ console.error('\n🔧 General Troubleshooting:');
1093
+ console.error(' 1. Clear cache: mcp-prompt-optimizer clear-cache');
1094
+ console.error(' 2. Check status: mcp-prompt-optimizer check-status');
1095
+ console.error(' 3. Try development mode: export OPTIMIZER_DEV_MODE=true');
1096
+ console.error(' 4. Contact support: support@promptoptimizer.help');
1097
+ }
1098
+
1099
+ process.exit(1);
1100
+ }
823
1101
  }
824
1102
 
825
- // Show enhanced help and subscription info when run directly
1103
+ // Enhanced help with development mode information
826
1104
  async function showInfo() {
827
- console.log('🚀 MCP Prompt Optimizer - Professional Cloud-Based Server v1.3.0');
828
- console.log('==================================================================');
1105
+ console.log(`🚀 MCP Prompt Optimizer - Professional Cloud-Based Server v${packageJson.version}`);
1106
+ console.log('Production-grade with enhanced network resilience and development mode\n');
1107
+
1108
+ console.log('📋 Available Commands:');
1109
+ console.log(' mcp-prompt-optimizer Start MCP server');
1110
+ console.log(' mcp-prompt-optimizer validate-key Validate API key');
1111
+ console.log(' mcp-prompt-optimizer check-status Check service status');
1112
+ console.log(' mcp-prompt-optimizer clear-cache Clear local cache');
1113
+ console.log(' mcp-prompt-optimizer test Test integration');
1114
+ console.log(' mcp-prompt-optimizer diagnose Run diagnostic');
1115
+ console.log(' mcp-prompt-optimizer help Show this help');
829
1116
  console.log('');
830
- console.log('Professional cloud-based MCP server for AI-powered prompt optimization.');
831
- console.log('Requires active subscription starting at $2.99/month.');
1117
+
1118
+ console.log('🔧 Setup Instructions:');
1119
+ console.log(' 1. Get API key: https://promptoptimizer-blog.vercel.app/pricing');
1120
+ console.log(' 2. Set environment: export OPTIMIZER_API_KEY=sk-opt-...');
1121
+ console.log(' 3. Configure Claude Desktop with this server');
1122
+ console.log(' 4. Start using: mcp-prompt-optimizer');
832
1123
  console.log('');
833
- console.log('💰 Cloud Subscription Plans (same AI quality, different quotas):');
834
- console.log(' Explorer ($2.99/mo): 5,000 optimizations + individual use');
835
- console.log(' Creator ($25.99/mo): 18,000 optimizations + team features (2 members)');
836
- console.log(' Innovator ($69.99/mo): 75,000 optimizations + large teams (5 members) + priority support');
1124
+
1125
+ console.log('🧪 Development Mode:');
1126
+ console.log(' Enable development mode for offline testing:');
1127
+ console.log(' export OPTIMIZER_DEV_MODE=true');
1128
+ console.log(' export OPTIMIZER_API_KEY=sk-dev-test-key');
1129
+ console.log(' Features: Mock optimization, offline operation, no backend required');
837
1130
  console.log('');
838
- console.log('✨ Professional Cloud Features (all plans):');
839
- console.log(' 🧠 AI Context Detection - Image gen, LLM interaction, technical automation');
840
- console.log(' 🎯 10+ Optimization Techniques - Clarity, specificity, technical accuracy');
841
- console.log(' 📁 Template Management - Auto-save, search, reuse optimizations');
842
- console.log(' 📊 Real-time Analytics - Confidence scoring, usage tracking');
843
- console.log(' 👥 Team Collaboration - Shared quotas, team templates');
844
- console.log(' ☁️ Cloud Processing - Always up-to-date, no local setup');
845
- console.log(' 🚀 Priority Processing - Faster response times (Creator/Innovator)');
1131
+
1132
+ console.log('🎛️ Advanced Model Configuration (Optional):');
1133
+ console.log(' Configure your own OpenRouter API key and model preferences in the WebUI:');
1134
+ console.log(' 1. Visit: https://promptoptimizer-blog.vercel.app/dashboard');
1135
+ console.log(' 2. Go to Settings User Settings');
1136
+ console.log(' 3. Add OpenRouter API key and select models');
1137
+ console.log(' 4. NPM package automatically uses your settings!');
846
1138
  console.log('');
847
- console.log('🆓 Free Trial: 5 optimizations included');
848
- console.log('🌐 Get started: https://promptoptimizer-blog.vercel.app/pricing');
849
- console.log('📊 Dashboard: https://promptoptimizer-blog.vercel.app/dashboard');
1139
+ console.log('💡 Benefits: Cost control, model choice, better performance');
1140
+ console.log('📝 Two API keys: Service key (sk-opt-*) + OpenRouter key (optional)');
850
1141
  console.log('');
851
- console.log('⚙️ Claude Desktop Setup:');
852
- console.log('Add to ~/.claude/claude_desktop_config.json:');
853
- console.log(JSON.stringify({
854
- "mcpServers": {
855
- "prompt-optimizer": {
856
- "command": "npx",
857
- "args": ["mcp-prompt-optimizer"],
858
- "env": {
859
- "OPTIMIZER_API_KEY": "sk-opt-your-key-here"
860
- }
861
- }
862
- }
863
- }, null, 2));
1142
+
1143
+ console.log('🛠️ MCP Client Configuration:');
1144
+ console.log(' Add to Claude Desktop config (~/.claude/claude_desktop_config.json):');
1145
+ console.log(' {');
1146
+ console.log(' "mcpServers": {');
1147
+ console.log(' "prompt-optimizer": {');
1148
+ console.log(' "command": "npx",');
1149
+ console.log(' "args": ["mcp-prompt-optimizer"],');
1150
+ console.log(' "env": {');
1151
+ console.log(' "OPTIMIZER_API_KEY": "sk-opt-your-key-here"');
1152
+ console.log(' }');
1153
+ console.log(' }');
1154
+ console.log(' }');
1155
+ console.log(' }');
864
1156
  console.log('');
865
- console.log('🔧 Other MCP Clients:');
866
- console.log(' Cursor: Add to ~/.cursor/mcp.json');
867
- console.log(' Windsurf: Configure in settings');
868
- console.log(' Cline: Use standard MCP configuration');
869
- console.log(' VS Code/Zed/Replit: Standard MCP setup');
1157
+
1158
+ console.log(' Production Features:');
1159
+ console.log(' AI Context Detection (Image, LLM, Code, etc.)');
1160
+ console.log(' Goal Enhancement & Optimization');
1161
+ console.log(' Template Library & Search');
1162
+ console.log(' ✅ Quota Management & Analytics');
1163
+ console.log(' ✅ Team Collaboration (Pro plans)');
1164
+ console.log(' ✅ Custom Model Configuration via WebUI');
1165
+ console.log(' ✅ Network Resilience & Fallback Modes');
1166
+ console.log(' ✅ Development Mode for Testing');
870
1167
  console.log('');
871
- console.log('🔧 Professional CLI Commands:');
872
- console.log(' mcp-prompt-optimizer check-status Check API key and quota status');
873
- console.log(' mcp-prompt-optimizer validate-key Validate your API key');
874
- console.log(' mcp-prompt-optimizer clear-cache Clear validation cache');
875
- console.log(' mcp-prompt-optimizer help Show this help');
876
- console.log(' mcp-prompt-optimizer version Show version');
1168
+
1169
+ console.log('🎯 Pricing Plans:');
1170
+ console.log(' Explorer: $2.99/month (5,000 optimizations)');
1171
+ console.log(' Creator: $25.99/month (18,000 optimizations)');
1172
+ console.log(' Innovator: $69.99/month (75,000 optimizations)');
1173
+ console.log('');
1174
+
1175
+ console.log('🔄 Network Resilience:');
1176
+ console.log(' ✅ Automatic retry with exponential backoff');
1177
+ console.log(' ✅ Intelligent caching (24h normal, 7d fallback)');
1178
+ console.log(' ✅ Graceful degradation during outages');
1179
+ console.log(' ✅ Fallback mode with reduced functionality');
1180
+ console.log(' ✅ Development mode for offline testing');
877
1181
  console.log('');
878
- console.log('🏢 Enterprise Solutions:');
879
- console.log(' Custom deployment options available');
880
- console.log(' Higher quotas and dedicated support');
881
- console.log(' Contact: enterprise@promptoptimizer.help');
1182
+
1183
+ console.log('📚 Documentation & Support:');
1184
+ console.log(' 📖 Docs: https://promptoptimizer-blog.vercel.app/docs');
1185
+ console.log(' 💰 Pricing: https://promptoptimizer-blog.vercel.app/pricing');
1186
+ console.log(' 🎛️ Dashboard: https://promptoptimizer-blog.vercel.app/dashboard');
1187
+ console.log(' 📧 Support: support@promptoptimizer.help');
882
1188
  console.log('');
883
- console.log('📧 Support: support@promptoptimizer.help');
1189
+
1190
+ console.log('🚀 Quick Start:');
1191
+ console.log(' Production: export OPTIMIZER_API_KEY=sk-opt-your-key');
1192
+ console.log(' Development: export OPTIMIZER_DEV_MODE=true && export OPTIMIZER_API_KEY=sk-dev-test');
1193
+ console.log(' 1. mcp-prompt-optimizer validate-key');
1194
+ console.log(' 2. Configure your MCP client');
1195
+ console.log(' 3. Start optimizing prompts!');
1196
+ }
1197
+
1198
+ // ✅ Enhanced CLI command handling
1199
+ async function handleCLICommand() {
1200
+ const command = process.argv[2];
1201
+
1202
+ switch (command) {
1203
+ case 'validate-key':
1204
+ const validateKey = require('./lib/validate-key');
1205
+ await validateKey();
1206
+ break;
1207
+
1208
+ case 'check-status':
1209
+ const checkStatus = require('./lib/check-status');
1210
+ await checkStatus();
1211
+ break;
1212
+
1213
+ case 'clear-cache':
1214
+ const clearCache = require('./lib/clear-cache');
1215
+ await clearCache();
1216
+ break;
1217
+
1218
+ case 'test':
1219
+ const testIntegration = require('./lib/test-integration');
1220
+ await testIntegration();
1221
+ break;
1222
+
1223
+ case 'diagnose':
1224
+ const diagnose = require('./lib/diagnose');
1225
+ await diagnose();
1226
+ break;
1227
+
1228
+ case 'help':
1229
+ case '--help':
1230
+ case '-h':
1231
+ await showInfo();
1232
+ break;
1233
+
1234
+ case 'version':
1235
+ case '--version':
1236
+ case '-v':
1237
+ console.log(`MCP Prompt Optimizer v${packageJson.version}`);
1238
+ console.log(`Production-grade with network resilience and development mode`);
1239
+ console.log(`Documentation: https://promptoptimizer-blog.vercel.app/docs`);
1240
+ break;
1241
+
1242
+ default:
1243
+ // No command provided, start MCP server
1244
+ await startValidatedMCPServer();
1245
+ break;
1246
+ }
884
1247
  }
885
1248
 
886
- // NEW: Enhanced CLI command handling (following local pattern)
1249
+ // Main execution
887
1250
  if (require.main === module) {
888
- const args = process.argv.slice(2);
889
-
890
- if (args.includes('--help') || args.includes('-h') || args.includes('help')) {
891
- showInfo();
892
- } else if (args.includes('--version') || args.includes('-v') || args.includes('version')) {
893
- try {
894
- const packageJson = require('./package.json');
895
- console.log(`mcp-prompt-optimizer v${packageJson.version}`);
896
- console.log('Professional Cloud-Based MCP Server - Starting at $2.99/month');
897
- console.log('🌐 Get started: https://promptoptimizer-blog.vercel.app/pricing');
898
- } catch (error) {
899
- console.log('mcp-prompt-optimizer v1.3.0');
900
- console.log('Professional Cloud-Based MCP Server - Starting at $2.99/month');
901
- console.log('🌐 Get started: https://promptoptimizer-blog.vercel.app/pricing');
1251
+ handleCLICommand().catch(error => {
1252
+ console.error(`❌ Command failed: ${error.message}`);
1253
+
1254
+ // Enhanced error handling with context-specific guidance
1255
+ if (error.message.includes('Cannot find module')) {
1256
+ console.error('\n🔧 Module Error:');
1257
+ console.error(' - Ensure all dependencies are installed: npm install');
1258
+ console.error(' - Check that lib/ directory exists with CLI tools');
1259
+ console.error(' - Reinstall package: npm install -g mcp-prompt-optimizer');
1260
+ } else if (error.message.includes('API key')) {
1261
+ console.error('\n🔑 API Key Issue:');
1262
+ console.error(' - Set your API key: export OPTIMIZER_API_KEY=sk-opt-...');
1263
+ console.error(' - Get API key: https://promptoptimizer-blog.vercel.app/pricing');
1264
+ console.error(' - Validate key: mcp-prompt-optimizer validate-key');
1265
+ console.error(' - Try development mode: export OPTIMIZER_DEV_MODE=true');
1266
+ } else if (error.message.includes('Network') || error.message.includes('timeout') || error.message.includes('DNS')) {
1267
+ console.error('\n🌐 Network Issue:');
1268
+ console.error(' - Check internet connection');
1269
+ console.error(' - Verify firewall/proxy settings');
1270
+ console.error(' - Try development mode: export OPTIMIZER_DEV_MODE=true');
1271
+ console.error(' - Try again in a moment');
1272
+ } else {
1273
+ console.error('\n🛠️ General Troubleshooting:');
1274
+ console.error(' 1. Run diagnostic: mcp-prompt-optimizer diagnose');
1275
+ console.error(' 2. Check status: mcp-prompt-optimizer check-status');
1276
+ console.error(' 3. Clear cache: mcp-prompt-optimizer clear-cache');
1277
+ console.error(' 4. Try development mode: export OPTIMIZER_DEV_MODE=true');
1278
+ console.error(' 5. Contact support: support@promptoptimizer.help');
902
1279
  }
903
- } else if (args.includes('check-status') || args.includes('status')) {
904
- // ✅ NEW: CLI command integration
905
- require('./lib/check-status');
906
- } else if (args.includes('validate-key')) {
907
- // ✅ NEW: CLI command integration
908
- require('./lib/validate-key');
909
- } else if (args.includes('clear-cache') || args.includes('clear')) {
910
- // ✅ NEW: CLI command integration
911
- require('./lib/clear-cache');
912
- } else if (process.stdin.isTTY) {
913
- // Running in terminal - show info
914
- showInfo();
915
- } else {
916
- // ✅ UPDATED: Running via MCP protocol - start server with validation
917
- startValidatedMCPServer();
918
- }
1280
+
1281
+ process.exit(1);
1282
+ });
919
1283
  }
920
1284
 
921
- module.exports = MCPPromptOptimizer;
1285
+ // Export for testing - compatible with both require('./index.js') and new require('./index.js')()
1286
+ module.exports = MCPPromptOptimizer;
1287
+ module.exports.MCPPromptOptimizer = MCPPromptOptimizer;
1288
+ module.exports.startValidatedMCPServer = startValidatedMCPServer;
1289
+ module.exports.showInfo = showInfo;