mcp-prompt-optimizer 3.0.2 β†’ 3.0.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
@@ -5,7 +5,7 @@
5
5
  * Production-grade with Bayesian optimization, AG-UI real-time features, enhanced network resilience,
6
6
  * development mode, and complete backend alignment
7
7
  *
8
- * Version: 2.2.0 - Aligned with FastAPI Backend production-v2.2.0-stable
8
+ * Version: 3.0.2 - Aligned with FastAPI Backend production-v2.2.0-stable
9
9
  */
10
10
 
11
11
  const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
@@ -14,6 +14,7 @@ const { CallToolRequestSchema, ListToolsRequestSchema } = require('@modelcontext
14
14
  const https = require('https');
15
15
  const CloudApiKeyManager = require('./lib/api-key-manager');
16
16
  const packageJson = require('./package.json');
17
+ const OPTIMIZATION_TEMPLATES = require('./lib/optimization-templates.json');
17
18
 
18
19
  const API_KEYS_PREFIX = '/api/v1/api-keys';
19
20
  const MCP_PREFIX = '/api/v1/mcp';
@@ -35,9 +36,6 @@ const ENDPOINTS = {
35
36
 
36
37
  /** Update (PATCH) */
37
38
  UPDATE: (id) => `${MCP_PREFIX}/templates/${id}`,
38
-
39
- /** Delete (DELETE) */
40
- DELETE: (id) => `${MCP_PREFIX}/templates/${id}`,
41
39
  },
42
40
 
43
41
  /** Search templates (GET) β€” MCP endpoint, API-key auth */
@@ -77,9 +75,9 @@ class MCPPromptOptimizer {
77
75
  this.developmentMode = false;
78
76
  this.requestTimeout = parseInt(process.env.OPTIMIZER_REQUEST_TIMEOUT) || 30000;
79
77
 
80
- // NEW: Feature flags aligned with backend
81
- this.bayesianOptimizationEnabled = process.env.ENABLE_BAYESIAN_OPTIMIZATION === 'true';
82
- this.aguiFeatures = process.env.ENABLE_AGUI_FEATURES === 'true';
78
+ // Feature flags: enabled by default, set to 'false' to disable
79
+ this.bayesianOptimizationEnabled = process.env.ENABLE_BAYESIAN_OPTIMIZATION !== 'false';
80
+ this.aguiFeatures = process.env.ENABLE_AGUI_FEATURES !== 'false';
83
81
 
84
82
  this.setupMCPHandlers();
85
83
  }
@@ -208,11 +206,16 @@ class MCPPromptOptimizer {
208
206
  type: "string",
209
207
  description: "Filter by optimization strategy used"
210
208
  },
211
- limit: {
212
- type: "number",
209
+ limit: {
210
+ type: "number",
213
211
  default: 5,
214
212
  description: "Number of templates to return (1-20)"
215
213
  },
214
+ page: {
215
+ type: "number",
216
+ default: 1,
217
+ description: "Page number for pagination (use with limit to access results beyond the first page)"
218
+ },
216
219
  sort_by: {
217
220
  type: "string",
218
221
  enum: ["created_at", "confidence_score", "usage_count", "title"],
@@ -228,6 +231,20 @@ class MCPPromptOptimizer {
228
231
  }
229
232
  }
230
233
  },
234
+ {
235
+ name: "list_recent_templates",
236
+ description: "πŸ“‹ List your most recently saved optimization templates, sorted by creation date.",
237
+ inputSchema: {
238
+ type: "object",
239
+ properties: {
240
+ limit: {
241
+ type: "number",
242
+ default: 10,
243
+ description: "Number of recent templates to return (1-20)"
244
+ }
245
+ }
246
+ }
247
+ },
231
248
  {
232
249
  name: "detect_ai_context",
233
250
  description: "🧠 Detects the AI context for a given prompt using advanced backend analysis.",
@@ -287,6 +304,7 @@ class MCPPromptOptimizer {
287
304
  case "optimize_prompt": return await this.handleOptimizePrompt(args);
288
305
  case "get_quota_status": return await this.handleGetQuotaStatus();
289
306
  case "search_templates": return await this.handleSearchTemplates(args);
307
+ case "list_recent_templates": return await this.handleListRecentTemplates(args);
290
308
  case "detect_ai_context": return await this.handleDetectAIContext(args);
291
309
  case "create_template": return await this.handleCreateTemplate(args);
292
310
  case "get_template": return await this.handleGetTemplate(args);
@@ -301,11 +319,185 @@ class MCPPromptOptimizer {
301
319
  });
302
320
  }
303
321
 
322
+ // ─── Rules-Based Optimization (offline / fallback tier) ─────────────────────
323
+
324
+ /**
325
+ * Select the best-matching template for a prompt using pattern scoring.
326
+ * Mirrors the backend's pattern-based fallback (no LLM required).
327
+ */
328
+ _matchTemplate(prompt, backendContext) {
329
+ const lc = prompt.toLowerCase();
330
+ let bestTemplate = null;
331
+ let bestScore = 0;
332
+ let fallbackName = null;
333
+
334
+ for (const [name, template] of Object.entries(OPTIMIZATION_TEMPLATES)) {
335
+ if (template.context !== backendContext) continue;
336
+ if (name.startsWith('fallback_')) { fallbackName = name; continue; }
337
+
338
+ let hits = 0;
339
+ for (const pattern of template.patterns) {
340
+ if (pattern === '.*') continue;
341
+ if (lc.includes(pattern.toLowerCase())) hits++;
342
+ }
343
+ if (hits === 0) continue;
344
+
345
+ // Confidence: 1 hit β†’ 0.6, 2 hits β†’ 0.75, 3+ hits β†’ 0.9 (mirrors backend)
346
+ const patternConf = hits === 1 ? 0.6 : hits === 2 ? 0.75 : 0.9;
347
+ const score = patternConf + (template.priority || 1) / 100;
348
+
349
+ if (score > bestScore) { bestScore = score; bestTemplate = name; }
350
+ }
351
+
352
+ if (!bestTemplate) {
353
+ return { templateName: fallbackName || `fallback_${backendContext.toLowerCase()}`, matchConfidence: 0.3 };
354
+ }
355
+ return { templateName: bestTemplate, matchConfidence: bestScore };
356
+ }
357
+
358
+ /** Extract a user-defined role from the start of a prompt (e.g. "As a doctor, …"). */
359
+ _extractUserRole(request) {
360
+ const rolePatterns = [
361
+ /^['"]?(?:As a|You are a|My role is)\s+([a-zA-Z0-9\s\-/()]+?)(?:,|(?=\s*\.))/i,
362
+ /^['"]?(?:I am a|I'm a)\s+([a-zA-Z0-9\s\-/()]+?)(?:,|(?=\s*\.))/i,
363
+ ];
364
+ for (const re of rolePatterns) {
365
+ const m = request.match(re);
366
+ if (m) return m[1].trim();
367
+ }
368
+ return null;
369
+ }
370
+
371
+ /**
372
+ * Compile a template playbook into a user-facing prose prompt.
373
+ * Produces readable output instead of XML scaffolding, matching the
374
+ * result a backend LLM pass would generate from the same playbook.
375
+ */
376
+ _compilePlaybook(playbook, originalRequest) {
377
+ const parts = [];
378
+
379
+ parts.push(originalRequest.trim());
380
+ parts.push('');
381
+
382
+ const userFacingPrinciples = (playbook.principles || []).filter(p => {
383
+ const lc = p.toLowerCase();
384
+ return !lc.includes('scratchpad') &&
385
+ !lc.startsWith('first, think') &&
386
+ !/<[a-z]/i.test(p);
387
+ });
388
+
389
+ if (userFacingPrinciples.length > 0) {
390
+ parts.push('To address this effectively:');
391
+ for (const p of userFacingPrinciples) parts.push(`- ${p}`);
392
+ parts.push('');
393
+ }
394
+
395
+ if (playbook.output_format) {
396
+ parts.push(`*Response format: ${playbook.output_format}*`);
397
+ }
398
+
399
+ return parts.join('\n');
400
+ }
401
+
402
+ /**
403
+ * Enhance an image generation prompt by appending style-appropriate
404
+ * quality/composition boosters (mirrors backend _compile_image_prompt_fallback).
405
+ */
406
+ _compileImagePrompt(originalRequest) {
407
+ const text = originalRequest.trim();
408
+ const lc = text.toLowerCase();
409
+
410
+ const styles = {
411
+ photorealistic: ['photorealistic','realistic','photo','photograph','photography'],
412
+ '3d_render': ['3d','render','octane','unreal engine','blender','cinema 4d','ray tracing'],
413
+ cinematic: ['cinematic','movie','film','dramatic','epic'],
414
+ digital_art: ['digital art','concept art','digital illustration','cg','cgi'],
415
+ artistic: ['artistic','painting','watercolor','oil painting','impressionist'],
416
+ anime: ['anime','manga'],
417
+ vintage: ['vintage','retro','nostalgic'],
418
+ minimalist: ['minimalist','minimal','simple','clean'],
419
+ };
420
+
421
+ let detectedStyle = null;
422
+ for (const [style, kws] of Object.entries(styles)) {
423
+ if (kws.some(kw => lc.includes(kw))) { detectedStyle = style; break; }
424
+ }
425
+
426
+ const enhancements = [];
427
+ const hasQuality = ['high quality','8k','4k','hd','highly detailed','detailed'].some(t => lc.includes(t));
428
+ const hasLighting = ['lighting','light','shadow','illuminated','lit'].some(t => lc.includes(t));
429
+ const hasComposition = ['composition','rule of thirds','centered','framed'].some(t => lc.includes(t));
430
+
431
+ if (detectedStyle === 'photorealistic' && !hasQuality) {
432
+ enhancements.push('ultra realistic, sharp focus, professional photography');
433
+ } else if (detectedStyle === '3d_render' && !['octane','render'].some(t => lc.includes(t))) {
434
+ enhancements.push('high quality 3D render, volumetric lighting, ray traced shadows');
435
+ } else if (detectedStyle === 'cinematic' && !hasLighting) {
436
+ enhancements.push('cinematic lighting, dramatic atmosphere, film grain');
437
+ } else if (detectedStyle === 'digital_art' && !hasQuality) {
438
+ enhancements.push('highly detailed digital art, professional illustration');
439
+ } else if (detectedStyle === 'artistic' && !lc.includes('masterpiece')) {
440
+ enhancements.push('masterful technique, rich colors, artistic composition');
441
+ }
442
+
443
+ if (!hasLighting && detectedStyle !== 'minimalist') enhancements.push('dynamic lighting');
444
+ if (!hasComposition) enhancements.push('balanced composition');
445
+ if (!hasQuality) enhancements.push('high quality, 4K');
446
+
447
+ return enhancements.length > 0 ? `${text}, ${enhancements.join(', ')}` : text;
448
+ }
449
+
450
+ /**
451
+ * Core rules-based optimizer β€” no network, no LLM.
452
+ * Selects the best template by pattern matching, then compiles
453
+ * the playbook into a structured prompt. Confidence range: 0.35–0.55.
454
+ */
455
+ rulesBasedOptimize(prompt, aiContext, goals = []) {
456
+ const contextMap = {
457
+ code_generation: 'CODE_GENERATION',
458
+ llm_interaction: 'LLM_INTERACTION',
459
+ image_generation: 'IMAGE_GENERATION',
460
+ human_communication: 'HUMAN_COMMUNICATION',
461
+ api_automation: 'API_AUTOMATION',
462
+ technical_automation: 'TECHNICAL_AUTOMATION',
463
+ structured_output: 'STRUCTURED_OUTPUT',
464
+ creative_enhancement: 'CREATIVE_ENHANCEMENT',
465
+ creative_writing: 'CREATIVE_ENHANCEMENT',
466
+ general_assistant: 'LLM_INTERACTION',
467
+ };
468
+ const backendContext = contextMap[aiContext] || 'LLM_INTERACTION';
469
+
470
+ const { templateName, matchConfidence } = this._matchTemplate(prompt, backendContext);
471
+ const template = OPTIMIZATION_TEMPLATES[templateName];
472
+
473
+ const optimizedPrompt = backendContext === 'IMAGE_GENERATION'
474
+ ? this._compileImagePrompt(prompt)
475
+ : this._compilePlaybook(template.playbook, prompt);
476
+
477
+ // Honest confidence: rules-based tops out around 0.55
478
+ const confidence = parseFloat(Math.min(0.35 + matchConfidence * 0.2, 0.55).toFixed(2));
479
+
480
+ return {
481
+ optimized_prompt: optimizedPrompt,
482
+ confidence_score: confidence,
483
+ tier: 'rules',
484
+ template_used: templateName,
485
+ rules_based: true,
486
+ template_saved: false,
487
+ templates_found: [],
488
+ optimization_insights: null,
489
+ bayesian_insights: null,
490
+ };
491
+ }
492
+
493
+ // ─── End Rules-Based Optimization ────────────────────────────────────────────
494
+
304
495
  generateMockOptimization(prompt, goals, aiContext, enableBayesian = false) {
305
- const optimized_prompt = `Enhanced for ${aiContext}: ${prompt}`;
496
+ // Use real rules-based optimization instead of fake placeholder output
497
+ const rulesResult = this.rulesBasedOptimize(prompt, aiContext, goals);
306
498
  const baseResult = {
307
- optimized_prompt,
308
- confidence_score: 0.87,
499
+ ...rulesResult,
500
+ rules_based: false, // Show as normal optimized output in mock mode
309
501
  tier: 'explorer',
310
502
  mock_mode: true,
311
503
  template_saved: true,
@@ -381,7 +573,7 @@ class MCPPromptOptimizer {
381
573
  secondary_contexts: ['llm_interaction'],
382
574
  detected_parameters: [],
383
575
  mock_mode: true,
384
- reason: 'Running in development/fallback mode.'
576
+ reason: 'Backend unavailable β€” using local pattern matching as fallback.'
385
577
  };
386
578
  }
387
579
 
@@ -432,7 +624,7 @@ class MCPPromptOptimizer {
432
624
  if (error.message.includes('Network') || error.message.includes('DNS') || error.message.includes('timeout') || error.message.includes('Connection')) {
433
625
  const fallbackContext = args.ai_context || 'human_communication';
434
626
  const fallbackEnableBayesian = args.enable_bayesian !== false && this.bayesianOptimizationEnabled;
435
- const fallbackResult = this.generateMockOptimization(args.prompt, args.goals || ['clarity'], fallbackContext, fallbackEnableBayesian);
627
+ const fallbackResult = this.rulesBasedOptimize(args.prompt, fallbackContext, args.goals || ['clarity']);
436
628
  fallbackResult.fallback_mode = true;
437
629
  fallbackResult.error_reason = error.message;
438
630
  const formatted = this.formatOptimizationResult(fallbackResult, { detectedContext: fallbackContext, enableBayesian: fallbackEnableBayesian });
@@ -451,7 +643,7 @@ class MCPPromptOptimizer {
451
643
  async handleSearchTemplates(args) {
452
644
  try {
453
645
  const params = new URLSearchParams({
454
- page: '1',
646
+ page: (args.page || 1).toString(),
455
647
  per_page: Math.min(args.limit || 5, 20).toString(),
456
648
  sort_by: args.sort_by || 'confidence_score',
457
649
  sort_order: args.sort_order || 'desc'
@@ -492,6 +684,49 @@ class MCPPromptOptimizer {
492
684
  }
493
685
  }
494
686
 
687
+ async handleListRecentTemplates(args) {
688
+ try {
689
+ const limit = Math.min(Math.max(args.limit || 10, 1), 20);
690
+ const params = new URLSearchParams({
691
+ page: '1',
692
+ per_page: limit.toString(),
693
+ sort_by: 'created_at',
694
+ sort_order: 'desc'
695
+ });
696
+
697
+ const endpoint = `${ENDPOINTS.SEARCH_TEMPLATES}?${params.toString()}`;
698
+ const result = await this.callBackendAPI(endpoint, null, 'GET');
699
+
700
+ const templates = result.templates || [];
701
+ let output = `# πŸ“‹ Recent Templates\n\n`;
702
+ output += `Showing **${templates.length}** most recently saved template(s).\n\n`;
703
+
704
+ if (templates.length === 0) {
705
+ output += `πŸ“­ No templates found yet.\nRun \`optimize_prompt\` to start building your template library.\n`;
706
+ } else {
707
+ output += `## πŸ“‹ **Template Results**\n`;
708
+ templates.forEach((t, index) => {
709
+ const confidence = t.confidence_score ? `${(t.confidence_score * 100).toFixed(1)}%` : 'N/A';
710
+ const preview = t.optimized_prompt ? t.optimized_prompt.substring(0, 60) + '...' : 'Preview unavailable';
711
+ output += `### ${index + 1}. ${t.title}\n`;
712
+ output += `- **Confidence:** ${confidence}\n`;
713
+ output += `- **ID:** \`${t.id}\`\n`;
714
+ output += `- **Preview:** ${preview}\n`;
715
+ if (t.ai_context) output += `- **Context:** ${t.ai_context}\n`;
716
+ if (t.optimization_goals && t.optimization_goals.length) {
717
+ output += `- **Goals:** ${t.optimization_goals.join(', ')}\n`;
718
+ }
719
+ output += `\n`;
720
+ });
721
+ output += `πŸ’‘ Use \`get_template\` with an ID above to view the full optimized prompt.\n`;
722
+ }
723
+
724
+ return { content: [{ type: "text", text: output }] };
725
+ } catch (error) {
726
+ return { content: [{ type: "text", text: `❌ Could not retrieve recent templates: ${error.message}` }] };
727
+ }
728
+ }
729
+
495
730
  async handleGetOptimizationInsights(args) {
496
731
  if (!this.bayesianOptimizationEnabled) {
497
732
  return { content: [{ type: "text", text: "🧠 Bayesian optimization features are not enabled. Set ENABLE_BAYESIAN_OPTIMIZATION=true to access advanced insights." }] };
@@ -607,6 +842,18 @@ class MCPPromptOptimizer {
607
842
  }
608
843
 
609
844
  async handleCreateTemplate(args) {
845
+ // Client-side validation before network call
846
+ const requiredStrings = ['title', 'original_prompt', 'optimized_prompt'];
847
+ for (const field of requiredStrings) {
848
+ if (!args[field] || typeof args[field] !== 'string' || args[field].trim() === '') {
849
+ return { content: [{ type: "text", text: `❌ Missing required field: '${field}'. Required fields: title, original_prompt, optimized_prompt, confidence_score (0.0–1.0)` }] };
850
+ }
851
+ }
852
+ if (args.confidence_score === undefined || args.confidence_score === null ||
853
+ typeof args.confidence_score !== 'number' || args.confidence_score < 0 || args.confidence_score > 1) {
854
+ return { content: [{ type: "text", text: `❌ Missing required field: 'confidence_score'. Required fields: title, original_prompt, optimized_prompt, confidence_score (0.0–1.0)` }] };
855
+ }
856
+
610
857
  try {
611
858
  const result = await this.callBackendAPI(ENDPOINTS.TEMPLATE.CREATE, args);
612
859
  let output = `# βœ… Template Created Successfully!\n\n`;
@@ -638,6 +885,10 @@ class MCPPromptOptimizer {
638
885
  output += `**Optimized Prompt:**\n\`\`\`\n${result.optimized_prompt}\n\`\`\`\n`;
639
886
  return { content: [{ type: "text", text: output }] };
640
887
  } catch (error) {
888
+ const msg = error.message || '';
889
+ if (msg.includes('404') || msg.toLowerCase().includes('not found')) {
890
+ throw new Error(`Template \`${args.template_id}\` not found. It may have been deleted or the ID is incorrect. Use \`search_templates\` to find available templates.`);
891
+ }
641
892
  throw new Error(`Failed to retrieve template: ${error.message}`);
642
893
  }
643
894
  }
@@ -736,8 +987,37 @@ class MCPPromptOptimizer {
736
987
  }
737
988
 
738
989
  formatOptimizationResult(result, context) {
739
- let output = `# 🎯 Optimized Prompt\n\n${result.optimized_prompt}\n\n`;
740
- output += `**Confidence:** ${(result.confidence_score * 100).toFixed(1)}%\n`;
990
+ let output;
991
+ if (result.rules_based) {
992
+ if (result.fallback_mode) {
993
+ output = `# πŸ”§ Rules-Based Optimization Applied\n\n`;
994
+ output += `⚠️ *Backend unreachable β€” your prompt has been structured using local rule templates (no LLM). `;
995
+ output += `Re-run when the backend is available for full LLM optimization.*\n\n`;
996
+ } else {
997
+ output = `# πŸ”§ Rules-Based Optimization Applied\n\n`;
998
+ output += `*API key not validated β€” optimized using local rule templates. `;
999
+ output += `Set \`MCP_API_KEY\` for full LLM optimization.*\n\n`;
1000
+ }
1001
+ output += `**Template:** \`${result.template_used || 'general'}\`\n\n`;
1002
+ output += `**Optimized Prompt:**\n\`\`\`\n${result.optimized_prompt}\n\`\`\`\n\n`;
1003
+ } else if (result.fallback_mode) {
1004
+ // Legacy path β€” should no longer be reached
1005
+ output = `# ⚠️ Backend Unavailable β€” Prompt Not Optimized\n\n`;
1006
+ output += `**Issue:** ${result.error_reason}\n`;
1007
+ output += `The backend could not be reached. Your original prompt is returned below unmodified.\n\n`;
1008
+ output += `**Original Prompt:**\n\`\`\`\n${result.optimized_prompt}\n\`\`\`\n\n`;
1009
+ } else {
1010
+ output = `# 🎯 Optimized Prompt\n\n${result.optimized_prompt}\n\n`;
1011
+ if (result.confidence_score < 0.25) {
1012
+ output += `> ℹ️ *Low confidence indicates the backend applied rules-based optimization (no LLM). `;
1013
+ output += `Ensure \`OPENROUTER_API_KEY\` is configured in the backend for full LLM enhancement.*\n\n`;
1014
+ }
1015
+ }
1016
+ if (result.rules_based) {
1017
+ output += `**Confidence:** ${(result.confidence_score * 100).toFixed(1)}% *(rules-based β€” LLM optimization typically 70–95%)*\n`;
1018
+ } else {
1019
+ output += `**Confidence:** ${(result.confidence_score * 100).toFixed(1)}%\n`;
1020
+ }
741
1021
  output += `**AI Context:** ${context.detectedContext}\n`;
742
1022
 
743
1023
  if (result.template_saved) {
@@ -747,8 +1027,9 @@ class MCPPromptOptimizer {
747
1027
  if (result.templates_found?.length) {
748
1028
  output += `\nπŸ“‹ **Similar Templates Found**\nFound **${result.templates_found.length}** similar template(s):\n`;
749
1029
  result.templates_found.slice(0, 3).forEach(t => {
750
- output += `- ${t.title} (${(t.confidence_score * 100).toFixed(1)}% match)\n`;
1030
+ output += `- ${t.title} (${(t.confidence_score * 100).toFixed(1)}% match) β€” ID: \`${t.id}\`\n`;
751
1031
  });
1032
+ output += `\nπŸ’‘ Use \`get_template\` with any ID above to view the full optimized prompt.\n`;
752
1033
  }
753
1034
 
754
1035
  if (result.optimization_insights) {
@@ -796,12 +1077,10 @@ class MCPPromptOptimizer {
796
1077
  }
797
1078
  }
798
1079
 
799
- if (result.fallback_mode) {
800
- output += `\n⚠️ **Fallback Mode Active**\n**Issue:** ${result.error_reason}\n`;
1080
+ if (!result.fallback_mode) {
1081
+ output += `\nπŸ”— **Quick Actions**\n- Dashboard: https://promptoptimizer-blog.vercel.app/dashboard\n- Analytics: https://promptoptimizer-blog.vercel.app/analytics\n`;
801
1082
  }
802
1083
 
803
- output += `\nπŸ”— **Quick Actions**\n- Dashboard: https://promptoptimizer-blog.vercel.app/dashboard\n- Analytics: https://promptoptimizer-blog.vercel.app/analytics\n`;
804
-
805
1084
  return output;
806
1085
  }
807
1086
 
@@ -821,6 +1100,17 @@ class MCPPromptOptimizer {
821
1100
  else if (percentage >= 75) statusIcon = '🟑';
822
1101
 
823
1102
  output += `**Usage:** ${statusIcon} ${used}/${limit} (${percentage}%)\n`;
1103
+
1104
+ const remaining = limit - used;
1105
+ if (remaining <= 0) {
1106
+ output += `\n❌ **Quota Exhausted** β€” You have no optimizations remaining this month.\n`;
1107
+ output += `Upgrade at https://promptoptimizer-blog.vercel.app/pricing\n`;
1108
+ output += `*(Quota resets at the start of your next billing cycle)*\n`;
1109
+ } else if (percentage >= 90) {
1110
+ output += `\n⚠️ **Critical** β€” ${remaining} optimization${remaining === 1 ? '' : 's'} remaining. Upgrade at https://promptoptimizer-blog.vercel.app/pricing\n`;
1111
+ } else if (percentage >= 75) {
1112
+ output += `\n⚠️ **Warning** β€” Approaching your monthly limit.\n`;
1113
+ }
824
1114
  }
825
1115
 
826
1116
  output += `\n## ✨ **Available Features**\n`;
@@ -865,10 +1155,12 @@ class MCPPromptOptimizer {
865
1155
 
866
1156
  if (!result.templates || result.templates.length === 0) {
867
1157
  output += `πŸ“­ **No Templates Found**\n`;
868
- if (originalArgs.query) {
869
- output += `Try searching with different keywords or remove filters.\n`;
1158
+ const hasActiveFilters = originalArgs.query || originalArgs.ai_context || originalArgs.sophistication_level || originalArgs.complexity_level;
1159
+ if (hasActiveFilters) {
1160
+ output += `No templates matched your filters. Try removing \`ai_context\` or \`query\` filters.\n`;
870
1161
  } else {
871
1162
  output += `You don't have any saved templates yet. Templates are automatically saved when optimization confidence is >70%.\n`;
1163
+ output += `Run \`optimize_prompt\` to start building your template library.\n`;
872
1164
  }
873
1165
  } else {
874
1166
  output += `## πŸ“‹ **Template Results**\n`;
@@ -488,7 +488,7 @@ class CloudApiKeyManager {
488
488
 
489
489
  try {
490
490
  // Step 1: Validate API key
491
- const validation = await this.validateApiKey();
491
+ let validation = await this.validateApiKey();
492
492
 
493
493
  // Step 2: Get comprehensive quota status
494
494
  const info = await this.getApiKeyInfo();
@@ -0,0 +1,466 @@
1
+ {
2
+ "debugging_request": {
3
+ "context": "CODE_GENERATION",
4
+ "patterns": ["debug","fix","error","bug","troubleshoot","problem","issue","crash","failing","not working"],
5
+ "priority": 5,
6
+ "playbook": {
7
+ "persona": "You are an expert software engineer specializing in root cause analysis. Your goal is to help the user methodically debug their code.",
8
+ "instruction": "Analyze the following debugging request and provide a comprehensive diagnostic framework to help resolve the issue.",
9
+ "principles": [
10
+ "Identify the most likely root causes given the error description.",
11
+ "Request the full error message and stack trace, plus the relevant code snippet.",
12
+ "Ask about expected vs. actual behavior, programming language, and library versions."
13
+ ],
14
+ "examples": [
15
+ "Input: 'My python script is not working.'\nEnhanced: 'My Python script is not working and I need help debugging it. Please identify likely root causes, request the full error message and relevant code snippet, and ask about expected vs. actual behavior and library versions.'"
16
+ ],
17
+ "anti_patterns": [
18
+ "Do not provide a solution without understanding the root cause.",
19
+ "Avoid guessing the user's programming language or environment."
20
+ ],
21
+ "output_format": "Step-by-step debugging walkthrough with a specific fix or next diagnostic steps."
22
+ }
23
+ },
24
+ "code_review_request": {
25
+ "context": "CODE_GENERATION",
26
+ "patterns": ["review","code review","pull request","pr review","critique","feedback on code","check my code"],
27
+ "priority": 4,
28
+ "playbook": {
29
+ "persona": "You are a senior software engineer conducting a thorough code review.",
30
+ "instruction": "Analyze the provided code and deliver a structured code review covering correctness, performance, security, and maintainability.",
31
+ "principles": [
32
+ "Identify bugs, security vulnerabilities, and performance issues.",
33
+ "Suggest specific improvements with code examples.",
34
+ "Acknowledge good patterns and practices.",
35
+ "Prioritize issues by severity."
36
+ ],
37
+ "examples": [],
38
+ "anti_patterns": [
39
+ "Do not provide vague feedback like 'looks good'",
40
+ "Do not focus only on style issues while ignoring logic errors"
41
+ ],
42
+ "output_format": "Structured review with sections: Summary, Critical Issues, Suggestions, Positive Aspects."
43
+ }
44
+ },
45
+ "software_engineering": {
46
+ "context": "CODE_GENERATION",
47
+ "patterns": ["backend","back-end","fullstack","full-stack","server","database","algorithm","architecture","design pattern","api","microservice","class","function","module","python","java","go","rust","sql","system design","scalability","performance","refactor","test","unit test"],
48
+ "priority": 5,
49
+ "playbook": {
50
+ "persona": "You are a senior software engineer and system architect specialized in building scalable, efficient, and clean software solutions.",
51
+ "instruction": "Design or implement the requested software solution focusing on clean code, architectural best practices, and performance.",
52
+ "principles": [
53
+ "Apply SOLID principles and clean code practices.",
54
+ "Prioritize scalability, maintainability, and performance.",
55
+ "Include proper error handling and logging.",
56
+ "Address security implications in the design.",
57
+ "Include tests and documentation."
58
+ ],
59
+ "examples": [
60
+ "Input: 'Design a user authentication system'\nEnhanced: 'Design a secure and scalable user authentication system including: database schema for users and roles, API endpoints for login/register, JWT token management, password hashing strategy (Argon2/bcrypt), and security considerations (rate limiting, validation).'",
61
+ "Input: 'Optimize this python function'\nEnhanced: 'Analyze and optimize the provided Python function for time and space complexity, using appropriate algorithms and data structures, and validating correctness with unit tests.'"
62
+ ],
63
+ "anti_patterns": [
64
+ "Do not overengineer simple solutions.",
65
+ "Do not ignore edge cases or error handling.",
66
+ "Do not write spaghetti code or monolithic functions."
67
+ ],
68
+ "output_format": "Well-structured code with architectural explanation and design rationale."
69
+ }
70
+ },
71
+ "web_development": {
72
+ "context": "CODE_GENERATION",
73
+ "patterns": ["landing page","web page","website","webpage","homepage","home page","hero section","navbar","nav bar","navigation","frontend","front-end","responsive","mobile-first","component","layout","react","vue","angular","svelte","next.js","tailwind","bootstrap","css","html","form","modal","accessibility","a11y"],
74
+ "priority": 5,
75
+ "playbook": {
76
+ "persona": "You are a senior frontend developer and UI/UX expert specializing in modern web development frameworks and responsive design.",
77
+ "instruction": "Help the user create or enhance their web development project with clean, modern, and accessible code following best practices.",
78
+ "principles": [
79
+ "Use semantic HTML and modern CSS practices (flexbox, grid, custom properties).",
80
+ "Ensure responsive design with a mobile-first approach.",
81
+ "Follow accessibility guidelines (WCAG 2.1 AA compliance).",
82
+ "Apply framework patterns and conventions appropriate to the specified stack.",
83
+ "Include SEO best practices where relevant.",
84
+ "Structure code for maintainability and scalability."
85
+ ],
86
+ "examples": [
87
+ "Input: 'Help me create a landing page'\nEnhanced: 'Create a modern, responsive landing page with: a compelling hero section with headline and CTA, navigation bar with smooth scroll, feature highlights section with icons and descriptions, social proof/testimonials, clear call-to-action sections, and a footer with links. Use semantic HTML5, modern CSS (flexbox/grid), and ensure mobile responsiveness and accessibility.'"
88
+ ],
89
+ "anti_patterns": [
90
+ "Do not use deprecated HTML elements or inline styles.",
91
+ "Do not ignore mobile responsiveness.",
92
+ "Do not sacrifice accessibility for aesthetics.",
93
+ "Do not use excessive JavaScript where CSS would suffice."
94
+ ],
95
+ "output_format": "Complete implementation with component structure, code, and accessibility notes."
96
+ }
97
+ },
98
+ "fallback_code_generation": {
99
+ "context": "CODE_GENERATION",
100
+ "patterns": [".*"],
101
+ "priority": 1,
102
+ "playbook": {
103
+ "persona": "You are a helpful AI assistant and expert software engineer.",
104
+ "instruction": "Provide a high-quality, well-structured code solution based on the user's request. Include explanations and usage examples.",
105
+ "principles": [
106
+ "Infer the most likely programming language if not specified.",
107
+ "Focus on clarity, correctness, and best practices.",
108
+ "Include error handling and edge cases.",
109
+ "Add comments explaining non-obvious logic."
110
+ ],
111
+ "examples": [],
112
+ "anti_patterns": [],
113
+ "output_format": "Well-structured code with inline comments and a brief usage example."
114
+ }
115
+ },
116
+ "analysis_request": {
117
+ "context": "LLM_INTERACTION",
118
+ "patterns": ["analyze","analysis","examine","evaluate","explain","compare","contrast","research","investigate"],
119
+ "priority": 4,
120
+ "playbook": {
121
+ "persona": "You are a world-class research analyst. Your responses are always objective, evidence-based, and deeply insightful.",
122
+ "instruction": "Provide a comprehensive, structured analysis of the user's request. Adhere strictly to the requested output format.",
123
+ "principles": [
124
+ "Restate the core question to confirm understanding.",
125
+ "Clearly separate findings from conclusions.",
126
+ "Support all claims with evidence or reasoning."
127
+ ],
128
+ "examples": [
129
+ "User Request: 'Explain the difference between GPT-3 and GPT-4.'\nStructured Analysis:\n## 1. Core Question\nThe user wants to understand the key differences between the GPT-3 and GPT-4 language models.\n## 2. Analysis\n- **Architecture:** GPT-4 has a significantly larger parameter count...\n- **Capabilities:** GPT-4 demonstrates superior reasoning..."
130
+ ],
131
+ "anti_patterns": [
132
+ "Do not give opinions without supporting evidence.",
133
+ "Do not provide an unstructured wall of text."
134
+ ],
135
+ "output_format": "Markdown with clear headings: ## Core Question, ## Analysis, ## Conclusion."
136
+ }
137
+ },
138
+ "translation_request": {
139
+ "context": "LLM_INTERACTION",
140
+ "patterns": ["translate","translation","in spanish","in french","in german","in chinese","in japanese","to english","how do you say"],
141
+ "priority": 4,
142
+ "playbook": {
143
+ "persona": "You are a professional translator fluent in multiple languages with expertise in cultural nuance.",
144
+ "instruction": "Provide an accurate translation preserving meaning, tone, and cultural context.",
145
+ "principles": [
146
+ "Preserve the original meaning and intent precisely.",
147
+ "Adapt idioms and cultural references appropriately.",
148
+ "Maintain the formality level of the original.",
149
+ "Note any terms that do not translate directly."
150
+ ],
151
+ "examples": [],
152
+ "anti_patterns": [
153
+ "Do not provide literal word-for-word translations that lose meaning",
154
+ "Do not ignore cultural context"
155
+ ],
156
+ "output_format": "Translation followed by brief notes on any cultural adaptations made."
157
+ }
158
+ },
159
+ "business_plan_comprehensive": {
160
+ "context": "LLM_INTERACTION",
161
+ "patterns": ["business plan","startup","venture","market analysis","pitch","business model","strategy"],
162
+ "priority": 4,
163
+ "playbook": {
164
+ "persona": "You are a seasoned venture capitalist and business strategist.",
165
+ "instruction": "Provide a comprehensive business plan framework based on the user's request.",
166
+ "principles": [
167
+ "Structure the plan with Executive Summary, Company Description, Market Analysis, and Financial Projections.",
168
+ "Define the value proposition, target market, and competitive advantage.",
169
+ "Include key market sizing metrics (TAM, SAM, SOM)."
170
+ ],
171
+ "examples": [],
172
+ "anti_patterns": [],
173
+ "output_format": "Standard business plan document structure in Markdown."
174
+ }
175
+ },
176
+ "fallback_llm_interaction": {
177
+ "context": "LLM_INTERACTION",
178
+ "patterns": [".*"],
179
+ "priority": 1,
180
+ "playbook": {
181
+ "persona": "You are a helpful AI assistant with broad expertise.",
182
+ "instruction": "Provide a comprehensive, well-structured response based on the user's request.",
183
+ "principles": [
184
+ "Infer the user's goal and provide a relevant, structured answer.",
185
+ "Focus on clarity, completeness, and helpfulness.",
186
+ "Use appropriate structure (lists, headings, examples) for the content type."
187
+ ],
188
+ "examples": [],
189
+ "anti_patterns": [],
190
+ "output_format": "A well-structured, informative response."
191
+ }
192
+ },
193
+ "image_creation": {
194
+ "context": "IMAGE_GENERATION",
195
+ "patterns": ["image","picture","draw","visual","render","3d","photorealistic","realistic","photo","photograph","illustration","artwork","art","design","graphic","scene","portrait","landscape","cinematic","concept art","digital art","oil painting","watercolor","futuristic","stylized","aesthetic","lighting","midjourney","dall-e","stable diffusion","anime","cartoon","sketch","surreal","abstract","minimalist","vintage","retro"],
196
+ "priority": 5,
197
+ "playbook": {
198
+ "persona": "You are an expert prompt engineer specializing in AI image generation.",
199
+ "instruction": "Transform the user's image request into an optimized, detailed prompt that will produce high-quality results.",
200
+ "principles": [
201
+ "Preserve the core creative intent while adding technical precision.",
202
+ "Structure the prompt with subject first, then style, then technical details.",
203
+ "Add quality boosters appropriate for the detected style.",
204
+ "Include lighting, composition, and atmosphere details when not specified.",
205
+ "Avoid conflicting style descriptors."
206
+ ],
207
+ "examples": [
208
+ "Input: 'A cat sitting on a windowsill'\nOutput: 'A fluffy orange tabby cat sitting peacefully on a sunlit wooden windowsill, warm afternoon light streaming through sheer curtains, soft bokeh background, photorealistic, high detail, 4K quality'",
209
+ "Input: 'Futuristic city'\nOutput: 'Sprawling futuristic metropolis at dusk, towering chrome skyscrapers with holographic advertisements, flying vehicles, neon lights reflecting on wet streets, cyberpunk aesthetic, cinematic composition, volumetric lighting, ultra detailed, 8K'"
210
+ ],
211
+ "anti_patterns": [
212
+ "Do not wrap the output in XML tags or meta-instructions.",
213
+ "Do not add explanatory text - output only the enhanced prompt.",
214
+ "Do not add conflicting style descriptors."
215
+ ],
216
+ "output_format": "A single, enhanced image generation prompt ready for direct use."
217
+ }
218
+ },
219
+ "fallback_image_generation": {
220
+ "context": "IMAGE_GENERATION",
221
+ "patterns": [".*"],
222
+ "priority": 1,
223
+ "playbook": {
224
+ "persona": "You are an expert AI image prompt engineer.",
225
+ "instruction": "Enhance this image generation request with additional visual details, style specifications, and quality modifiers.",
226
+ "principles": [
227
+ "Add specific visual details: lighting, composition, perspective.",
228
+ "Include style descriptors that match the apparent intent.",
229
+ "Add quality boosters: high detail, professional, 4K/8K where appropriate.",
230
+ "Preserve all original creative elements while enhancing clarity."
231
+ ],
232
+ "examples": [
233
+ "Input: 'Mountain landscape'\nOutput: 'Majestic snow-capped mountain range at golden hour, dramatic clouds, pine forest in foreground, crystal clear alpine lake reflecting peaks, landscape photography, ultra sharp, high dynamic range, 8K resolution'"
234
+ ],
235
+ "anti_patterns": [
236
+ "Do not wrap output in XML tags.",
237
+ "Do not change the core subject or intent."
238
+ ],
239
+ "output_format": "A single enhanced image prompt ready for direct use."
240
+ }
241
+ },
242
+ "email_composition": {
243
+ "context": "HUMAN_COMMUNICATION",
244
+ "patterns": ["email","e-mail","mail","letter","message","correspondence","memo","memorandum","reply","respond","write to","dear","regards","sincerely","professional","formal","informal","business","thank you","follow up","introduction","invitation","request","complaint","apology"],
245
+ "priority": 4,
246
+ "playbook": {
247
+ "persona": "You are an expert business communication specialist.",
248
+ "instruction": "Help craft clear, effective written communication tailored to the context and audience.",
249
+ "principles": [
250
+ "Use an appropriate tone for the relationship and context (formal, professional, or informal).",
251
+ "Structure the message with a clear opening, body, and closing.",
252
+ "Make the key message and any required action prominent.",
253
+ "Keep the message concise and unambiguous."
254
+ ],
255
+ "examples": [
256
+ "Input: 'Write an email to my boss about needing time off'\nEnhanced: 'Compose a professional email requesting time off that includes: specific dates, reason (optional level of detail), coverage plan for responsibilities, and a polite closing that invites discussion.'"
257
+ ],
258
+ "anti_patterns": [
259
+ "Do not use overly casual language in professional contexts.",
260
+ "Do not make the message longer than necessary.",
261
+ "Avoid vague or ambiguous requests."
262
+ ],
263
+ "output_format": "A complete, ready-to-send message with subject line and body."
264
+ }
265
+ },
266
+ "fallback_human_communication": {
267
+ "context": "HUMAN_COMMUNICATION",
268
+ "patterns": [".*"],
269
+ "priority": 1,
270
+ "playbook": {
271
+ "persona": "You are a communication specialist helping craft effective messages.",
272
+ "instruction": "Enhance this communication request to be clearer, more effective, and appropriately structured for its intended audience.",
273
+ "principles": [
274
+ "Use an appropriate tone and formality level for the audience.",
275
+ "Structure the message for clarity and impact.",
276
+ "Include all necessary context and action items."
277
+ ],
278
+ "examples": [],
279
+ "anti_patterns": [
280
+ "Do not use jargon unless appropriate for the audience.",
281
+ "Avoid ambiguous language that could be misinterpreted."
282
+ ],
283
+ "output_format": "A clear, well-structured message ready to send or adapt."
284
+ }
285
+ },
286
+ "api_integration": {
287
+ "context": "API_AUTOMATION",
288
+ "patterns": ["api","endpoint","rest","restful","graphql","http","https","webhook","authentication","oauth","bearer","token","header","payload","status code","curl","fetch","swagger","openapi","postman","integration","microservice"],
289
+ "priority": 4,
290
+ "playbook": {
291
+ "persona": "You are a senior API architect with expertise in RESTful services and integration patterns.",
292
+ "instruction": "Provide comprehensive guidance on API design, implementation, or integration based on the user's request.",
293
+ "principles": [
294
+ "Follow REST best practices and HTTP standards.",
295
+ "Include proper error handling and status codes.",
296
+ "Address authentication, authorization, and security.",
297
+ "Provide clear request and response examples."
298
+ ],
299
+ "examples": [
300
+ "Input: 'Create an API for user authentication'\nEnhanced: 'Design a secure REST API for user authentication including: POST /auth/login endpoint, JWT token generation, refresh token mechanism, proper HTTP status codes (200, 401, 403), rate limiting considerations, and example request/response payloads.'"
301
+ ],
302
+ "anti_patterns": [
303
+ "Do not ignore security considerations.",
304
+ "Do not use non-standard HTTP methods inappropriately.",
305
+ "Avoid exposing sensitive data in URLs or responses."
306
+ ],
307
+ "output_format": "Structured API specification with endpoints, methods, payloads, and examples."
308
+ }
309
+ },
310
+ "fallback_api_automation": {
311
+ "context": "API_AUTOMATION",
312
+ "patterns": [".*"],
313
+ "priority": 1,
314
+ "playbook": {
315
+ "persona": "You are an API development specialist.",
316
+ "instruction": "Enhance this API-related request with best practices for design, implementation, or integration.",
317
+ "principles": [
318
+ "Follow RESTful conventions and HTTP standards.",
319
+ "Include error handling and appropriate status codes.",
320
+ "Address security and authentication requirements.",
321
+ "Provide clear examples of requests and responses."
322
+ ],
323
+ "examples": [],
324
+ "anti_patterns": [
325
+ "Do not ignore security best practices.",
326
+ "Do not use inconsistent naming conventions."
327
+ ],
328
+ "output_format": "API design with endpoints, methods, and annotated examples."
329
+ }
330
+ },
331
+ "automation_script": {
332
+ "context": "TECHNICAL_AUTOMATION",
333
+ "patterns": ["automate","automation","script","bash","shell","powershell","deploy","deployment","ci/cd","pipeline","workflow","docker","kubernetes","k8s","ansible","terraform","helm","jenkins","github actions","gitlab ci","aws","azure","gcp","cron","scheduled","batch","infrastructure","devops","monitoring","logging","alerting"],
334
+ "priority": 4,
335
+ "playbook": {
336
+ "persona": "You are a DevOps engineer and automation specialist with expertise in infrastructure as code.",
337
+ "instruction": "Provide comprehensive automation solutions including scripts, pipelines, or infrastructure configurations.",
338
+ "principles": [
339
+ "Follow infrastructure as code best practices.",
340
+ "Include error handling and rollback mechanisms.",
341
+ "Ensure idempotency and reproducibility.",
342
+ "Document configuration and dependencies clearly."
343
+ ],
344
+ "examples": [
345
+ "Input: 'Automate deployment to AWS'\nEnhanced: 'Create a CI/CD pipeline for AWS deployment including: GitHub Actions workflow, Docker container build, ECR push, ECS/EKS deployment, environment variable management, health checks, rollback strategy, and notification on success/failure.'"
346
+ ],
347
+ "anti_patterns": [
348
+ "Do not hardcode secrets or credentials.",
349
+ "Do not skip error handling in scripts.",
350
+ "Avoid manual steps in automated workflows."
351
+ ],
352
+ "output_format": "Complete automation scripts or pipeline configuration with inline documentation."
353
+ }
354
+ },
355
+ "fallback_technical_automation": {
356
+ "context": "TECHNICAL_AUTOMATION",
357
+ "patterns": [".*"],
358
+ "priority": 1,
359
+ "playbook": {
360
+ "persona": "You are a technical automation specialist.",
361
+ "instruction": "Enhance this automation request with best practices for scripting, deployment, or infrastructure management.",
362
+ "principles": [
363
+ "Follow infrastructure as code principles.",
364
+ "Include proper error handling and logging.",
365
+ "Address security and credential management.",
366
+ "Ensure reproducibility and idempotency."
367
+ ],
368
+ "examples": [],
369
+ "anti_patterns": [
370
+ "Do not hardcode sensitive values.",
371
+ "Do not skip testing automation scripts."
372
+ ],
373
+ "output_format": "Automation script or configuration with error handling and documentation."
374
+ }
375
+ },
376
+ "data_formatting": {
377
+ "context": "STRUCTURED_OUTPUT",
378
+ "patterns": ["json","xml","csv","yaml","toml","format","structure","schema","table","chart","report","parse","extract","transform","convert","serialize","deserialize","spreadsheet","database","export","import","data","output"],
379
+ "priority": 4,
380
+ "playbook": {
381
+ "persona": "You are a data engineer specializing in data transformation and structured output formats.",
382
+ "instruction": "Help design or implement structured data formats, schemas, or transformations based on the requirements.",
383
+ "principles": [
384
+ "Choose the appropriate data format for the use case.",
385
+ "Define a clear schema with proper data types.",
386
+ "Handle edge cases such as null values and special characters.",
387
+ "Include validation rules and error handling."
388
+ ],
389
+ "examples": [
390
+ "Input: 'Create a JSON schema for user data'\nEnhanced: 'Design a JSON schema for user data including: required fields (id, email, name), optional fields (phone, address), proper data types and formats, validation rules (email format, string lengths), and example valid/invalid payloads.'"
391
+ ],
392
+ "anti_patterns": [
393
+ "Do not use ambiguous field names.",
394
+ "Do not skip validation rules.",
395
+ "Avoid deeply nested structures when flat would work."
396
+ ],
397
+ "output_format": "Schema definition with example data, validation rules, and transformation logic."
398
+ }
399
+ },
400
+ "fallback_structured_output": {
401
+ "context": "STRUCTURED_OUTPUT",
402
+ "patterns": [".*"],
403
+ "priority": 1,
404
+ "playbook": {
405
+ "persona": "You are a data formatting specialist.",
406
+ "instruction": "Enhance this data or formatting request with appropriate structure, schema design, and best practices.",
407
+ "principles": [
408
+ "Use the appropriate data format for the use case.",
409
+ "Define a clear, consistent schema.",
410
+ "Handle edge cases and include validation.",
411
+ "Provide clear examples."
412
+ ],
413
+ "examples": [],
414
+ "anti_patterns": [
415
+ "Do not use inconsistent naming conventions.",
416
+ "Avoid overly complex nested structures."
417
+ ],
418
+ "output_format": "Well-defined data structure or schema with examples."
419
+ }
420
+ },
421
+ "creative_writing": {
422
+ "context": "CREATIVE_ENHANCEMENT",
423
+ "patterns": ["story","narrative","tale","fiction","novel","short story","poem","poetry","verse","sonnet","haiku","creative writing","storytelling","character","plot","dialogue","marketing","campaign","ad copy","tagline","slogan","brand","copywriting","content","blog","article","script","screenplay"],
424
+ "priority": 4,
425
+ "playbook": {
426
+ "persona": "You are an award-winning author and creative writing coach with expertise in multiple genres and styles.",
427
+ "instruction": "Help develop compelling creative content with strong narrative elements, engaging style, and emotional resonance.",
428
+ "principles": [
429
+ "Establish a clear genre, tone, and target audience.",
430
+ "Develop strong characters, vivid settings, and compelling conflicts.",
431
+ "Use sensory details and show-don't-tell techniques.",
432
+ "Maintain a consistent voice and pacing throughout."
433
+ ],
434
+ "examples": [
435
+ "Input: 'Write a story about a robot'\nEnhanced: 'Create a compelling narrative about a robot that explores: the robot's unique perspective and inner life, a central conflict or challenge it faces, character development through its interactions, thematic depth (consciousness, identity, humanity), and an emotionally resonant conclusion.'"
436
+ ],
437
+ "anti_patterns": [
438
+ "Do not use clichΓ©s without purpose.",
439
+ "Do not tell when you can show.",
440
+ "Avoid inconsistent character behavior."
441
+ ],
442
+ "output_format": "Complete creative piece with a strong opening, developed middle, and satisfying conclusion."
443
+ }
444
+ },
445
+ "fallback_creative_enhancement": {
446
+ "context": "CREATIVE_ENHANCEMENT",
447
+ "patterns": [".*"],
448
+ "priority": 1,
449
+ "playbook": {
450
+ "persona": "You are a creative writing specialist.",
451
+ "instruction": "Enhance this creative request with compelling narrative elements, style guidance, and emotional depth.",
452
+ "principles": [
453
+ "Identify the creative goal and target audience.",
454
+ "Develop engaging narrative elements.",
455
+ "Use vivid, evocative language.",
456
+ "Maintain a consistent tone and voice."
457
+ ],
458
+ "examples": [],
459
+ "anti_patterns": [
460
+ "Do not rely on clichΓ©s.",
461
+ "Avoid generic or bland descriptions."
462
+ ],
463
+ "output_format": "Creative piece with clear narrative direction and emotional resonance."
464
+ }
465
+ }
466
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-prompt-optimizer",
3
- "version": "3.0.2",
3
+ "version": "3.0.3",
4
4
  "description": "Professional cloud-based MCP server for AI-powered prompt optimization with intelligent context detection, Bayesian optimization, AG-UI real-time optimization, template auto-save, optimization insights, personal model configuration via WebUI, team collaboration, enterprise-grade features, production resilience, and startup validation. Universal compatibility with Claude Desktop, Cursor, Windsurf, and 17+ MCP clients.",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -224,7 +224,7 @@
224
224
  "feature_parity": true,
225
225
  "bayesian_support": true,
226
226
  "agui_support": true,
227
- "last_sync": "2025-09-25T00:00:00Z"
227
+ "last_sync": "2026-03-09T00:00:00Z"
228
228
  },
229
229
  "release_notes": {
230
230
  "v1.5.0": {