mcp-prompt-optimizer
Version:
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 collabo
1,094 lines (1,002 loc) • 103 kB
JavaScript
#!/usr/bin/env node
/**
* MCP Prompt Optimizer - Professional Cloud-Based MCP Server
* Production-grade with Bayesian optimization, AG-UI real-time features, enhanced network resilience,
* development mode, and complete backend alignment
*
* Version: 3.2.0 - add delete_template tool (15 tools total)
*/
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
const { CallToolRequestSchema, ListToolsRequestSchema } = require('@modelcontextprotocol/sdk/types.js');
const https = require('https');
const CloudApiKeyManager = require('./lib/api-key-manager');
const packageJson = require('./package.json');
const OPTIMIZATION_TEMPLATES = require('./lib/optimization-templates.json');
const API_KEYS_PREFIX = '/api/v1/api-keys';
const MCP_PREFIX = '/api/v1/mcp';
const ENDPOINTS = {
/** Detect AI context (POST) — MCP endpoint, API-key auth */
DETECT_CONTEXT: `${MCP_PREFIX}/detect-context`,
/** Prompt optimization (POST) — MCP endpoint, API-key auth */
OPTIMIZE: `${MCP_PREFIX}/optimize`,
/** CRUD on templates — MCP endpoints, API-key auth */
TEMPLATE: {
/** Create (POST) */
CREATE: `${MCP_PREFIX}/templates`,
/** Read (GET) */
GET: (id) => `${MCP_PREFIX}/templates/${id}`,
/** Update (PATCH) */
UPDATE: (id) => `${MCP_PREFIX}/templates/${id}`,
/** Delete (DELETE) */
DELETE: (id) => `${MCP_PREFIX}/templates/${id}`,
},
/** Search templates (GET) — MCP endpoint, API-key auth */
SEARCH_TEMPLATES: `${MCP_PREFIX}/templates`,
/** Quota status (GET) — MCP endpoint, API-key auth */
QUOTA_STATUS: `${MCP_PREFIX}/quota-status`,
/** Validate API key (POST) — standard api-keys router */
VALIDATE_KEY: `${API_KEYS_PREFIX}/validate`,
/** Bayesian insights (GET) */
ANALYTICS_BAYESIAN_INSIGHTS:
'/api/v1/analytics/bayesian-insights',
/** AG‑UI status (GET) */
AGUI_STATUS: '/api/status',
/** Prompt delivery by slug */
GET_PROMPT_BY_SLUG: (slug) => `/api/v1/prompts/${slug}`,
COMPILE_PROMPT: (slug) => `/api/v1/prompts/${slug}/compiled`,
/** Template governance (versioning, publish) */
TEMPLATE_VERSIONS: (id) => `/api/v1/templates/${id}/versions`,
ROLLBACK_TEMPLATE: (id, n) => `/api/v1/templates/${id}/rollback/${n}`,
PUBLISH_TEMPLATE: (id) => `/api/v1/templates/${id}/publish`,
/** Quick evaluation (stateless) */
QUICK_EVALUATE: '/api/v1/evaluations/quick-evaluate',
/** Context Engineer (CE) endpoints */
CE: {
SOP: '/api/v1/context-engineer/sop',
GENERATE_SKILL_PACKAGE: '/api/v1/context-engineer/generate-skill-package',
SESSION: (id) => `/api/v1/context-engineer/sessions/${id}`,
TRANSFORM: '/api/v1/context-engineer/transform',
QUOTA: '/api/v1/context-engineer/quota',
HARNESS_BUNDLE: '/api/v1/context-engineer/harness-bundle',
SOP_EXPLORE: '/api/v1/context-engineer/sop-explore',
SOP_BLEND: '/api/v1/context-engineer/sop-blend',
},
};
const DEPLOY_TARGET_ENUM = [
"claude_code", "claude_desktop", "cursor", "copilot",
"windsurf", "cline", "zed", "replit", "openai_agents", "ollama",
"amazon_q", "aider", "continue_dev", "crewai",
"codex_cli",
];
class MCPPromptOptimizer {
constructor() {
this.server = new Server(
{
name: "mcp-prompt-optimizer",
version: packageJson.version,
},
{
capabilities: {
tools: {},
},
}
);
this.backendUrl = process.env.OPTIMIZER_BACKEND_URL || 'https://p01--project-optimizer--fvmrdk8m9k9j.code.run';
this.apiKey = process.env.OPTIMIZER_API_KEY;
// SECURITY: Development mode removed - all environments require backend validation
this.developmentMode = false;
this.requestTimeout = parseInt(process.env.OPTIMIZER_REQUEST_TIMEOUT) || 30000;
// Feature flags: enabled by default, set to 'false' to disable
this.bayesianOptimizationEnabled = process.env.ENABLE_BAYESIAN_OPTIMIZATION !== 'false';
this.aguiFeatures = process.env.ENABLE_AGUI_FEATURES !== 'false';
this.setupMCPHandlers();
}
setupMCPHandlers() {
this.server.setRequestHandler(ListToolsRequestSchema, async () => {
const baseTools = [
{
name: "optimize_prompt",
description: "🎯 Professional AI-powered prompt optimization with intelligent context detection, Bayesian optimization, template auto-save, and comprehensive optimization insights",
inputSchema: {
type: "object",
properties: {
prompt: {
type: "string",
description: "The prompt text to optimize"
},
goals: {
type: "array",
items: { type: "string" },
description: "Optimization goals (e.g., 'clarity', 'conciseness', 'creativity', 'technical_accuracy', 'analytical_depth', 'creative_enhancement')",
default: ["clarity"]
},
ai_context: {
type: "string",
enum: [
"human_communication", "llm_interaction", "image_generation", "technical_automation",
"structured_output", "code_generation", "api_automation", "data_analysis",
"creative_writing", "business_strategy", "technical_strategy", "academic_research",
"legal_compliance", "medical_healthcare", "educational_content"
],
description: "The context for the AI's task (auto-detected if not specified with enhanced detection)"
},
enable_bayesian: {
type: "boolean",
description: "Enable Bayesian optimization features for parameter tuning (if available)",
default: true
},
value_hierarchy: {
type: "array",
description: "Ordered list of values/constraints the optimizer must respect. NON_NEGOTIABLE entries force LLM-tier routing and inject hard constraints into the system prompt. Example: [{label:'NON_NEGOTIABLE',description:'Never suggest removing error handling'},{label:'HIGH',description:'Preserve technical terminology'}]",
items: {
type: "object",
properties: {
label: {
type: "string",
enum: ["NON_NEGOTIABLE", "HIGH", "MEDIUM", "LOW"],
description: "Priority level for this constraint"
},
description: {
type: "string",
description: "The value or constraint to enforce during optimization"
}
},
required: ["label", "description"]
}
},
intent_frame: {
type: "object",
description: "Question Method intent framing — steers optimization toward a specific angle, excludes off-topic territory, and defines what success looks like. Any non-null field floors routing to HYBRID tier minimum.",
properties: {
perspective: {
type: "string",
description: "The angle or thesis to optimize from (e.g. 'growth is a retention problem, not an acquisition problem'). Gives the optimizer a north-star direction."
},
out_of_scope: {
type: "array",
items: { type: "string" },
description: "Topics, approaches, or angles to explicitly exclude from optimization (e.g. ['pricing strategy', 'acquisition channels'])."
},
success_definition: {
type: "string",
description: "Narrative description of what a successful optimized output achieves (e.g. 'reader understands why churn drives flat revenue even with user growth')."
}
}
},
reasoning_effort: {
type: "string",
enum: ["minimal", "standard", "deep"],
description: "How much reasoning to apply: 'minimal' biases toward faster/cheaper routing, 'standard' is the default, 'deep' biases toward the LLM tier for maximum analysis. Most useful when calling this tool programmatically in a loop or pipeline, where there's no human watching each call to decide whether it's worth paying for more depth."
},
execution_shape: {
type: "string",
enum: ["direct", "hybrid", "multi_agent"],
description: "Execution style, independent of the tier the prompt would normally route to: 'direct' is single-pass, 'hybrid' adds rules+LLM verification, 'multi_agent' forces plan-and-execute with sub-agents regardless of the prompt's complexity. 'multi_agent' is downgraded to 'direct' on tiers without repair access — the response echoes back whichever one actually ran, so you can detect a downgrade."
}
},
required: ["prompt"]
}
},
{
name: "get_quota_status",
description: "📊 Check subscription status, quota usage, and account information with detailed insights and Bayesian optimization metrics",
inputSchema: { type: "object", properties: {}, additionalProperties: false }
},
{
name: "create_template",
description: "➕ Create a new optimization template.",
inputSchema: {
type: "object",
properties: {
title: { type: "string", description: "Title of the template" },
description: { type: "string", description: "Description of the template" },
original_prompt: { type: "string", description: "The original prompt text" },
optimized_prompt: { type: "string", description: "The optimized prompt text" },
optimization_goals: { type: "array", items: { type: "string" }, description: "Goals for this optimization (e.g., 'clarity', 'conciseness', 'creativity', 'technical_accuracy', 'analytical_depth', 'creative_enhancement')" },
confidence_score: { type: "number", description: "Confidence score of the optimization (0.0-1.0)" },
model_used: { type: "string", description: "Model used for optimization" },
optimization_tier: { type: "string", description: "Tier of optimization (e.g., rules, llm, hybrid)" },
ai_context_detected: { type: "string", description: "Detected AI context (e.g., code_generation, image_generation)" },
is_public: { type: "boolean", default: false, description: "Whether the template is public" },
tags: { type: "array", items: { type: "string" }, description: "Tags for the template" }
},
required: ["title", "original_prompt", "optimized_prompt", "confidence_score"]
}
},
{
name: "get_template",
description: "🔍 Retrieve a specific template by its ID.",
inputSchema: {
type: "object",
properties: {
template_id: { type: "string", description: "The ID of the template to retrieve" }
},
required: ["template_id"]
}
},
{
name: "update_template",
description: "✏️ Update an existing optimization template.",
inputSchema: {
type: "object",
properties: {
template_id: { type: "string", description: "The ID of the template to update" },
title: { type: "string", description: "New title for the template" },
description: { type: "string", description: "New description for the template" },
original_prompt: { type: "string", description: "New original prompt text" },
optimized_prompt: { type: "string", description: "New optimized prompt text" },
optimization_goals: { type: "array", items: { type: "string" }, description: "New optimization goals" },
confidence_score: { type: "number", description: "New confidence score (0.0-1.0)" },
model_used: { type: "string", description: "New model used for optimization" },
optimization_tier: { type: "string", description: "New tier of optimization" },
ai_context_detected: { type: "string", description: "New detected AI context" },
is_public: { type: "boolean", description: "Whether the template is public" },
tags: { type: "array", items: { type: "string" }, description: "New tags for the template" }
},
required: ["template_id"]
}
},
{
name: "delete_template",
description: "🗑️ Delete a saved optimization template by ID.",
inputSchema: {
type: "object",
properties: {
template_id: { type: "string", description: "The ID of the template to delete" }
},
required: ["template_id"]
}
},
{
name: "search_templates",
description: "🔍 Search your saved template library with AI-aware filtering, context-based search, and sophisticated template matching",
inputSchema: {
type: "object",
properties: {
query: {
type: "string",
description: "Search term to filter templates by content or title"
},
ai_context: {
type: "string",
enum: ["human_communication", "llm_interaction", "image_generation", "technical_automation", "structured_output", "code_generation", "api_automation"],
description: "Filter templates by AI context type"
},
sophistication_level: {
type: "string",
enum: ["basic", "intermediate", "advanced", "expert"],
description: "Filter by template sophistication level"
},
complexity_level: {
type: "string",
enum: ["simple", "moderate", "complex", "very_complex"],
description: "Filter by template complexity level"
},
optimization_strategy: {
type: "string",
description: "Filter by optimization strategy used"
},
limit: {
type: "number",
default: 5,
description: "Number of templates to return (1-20)"
},
page: {
type: "number",
default: 1,
description: "Page number for pagination (use with limit to access results beyond the first page)"
},
sort_by: {
type: "string",
enum: ["created_at", "confidence_score", "usage_count", "title"],
default: "confidence_score",
description: "Sort templates by field"
},
sort_order: {
type: "string",
enum: ["asc", "desc"],
default: "desc",
description: "Sort order"
}
}
}
},
{
name: "list_recent_templates",
description: "📋 List your most recently saved optimization templates, sorted by creation date.",
inputSchema: {
type: "object",
properties: {
limit: {
type: "number",
default: 10,
description: "Number of recent templates to return (1-20)"
}
}
}
},
{
name: "detect_ai_context",
description: "🧠 Detects the AI context for a given prompt using advanced backend analysis.",
inputSchema: {
type: "object",
properties: {
prompt: {
type: "string",
description: "The prompt text for which to detect the AI context"
}
},
required: ["prompt"]
}
},
{
name: "generate_agent_sop",
description: "Generate a structured SOP document for an AI agent from a goal description.",
inputSchema: {
type: "object",
properties: {
goal: { type: "string", description: "What the agent should accomplish" },
context: { type: "string", description: "Additional context (optional)" },
model_id: { type: "string", description: "Model to use (optional)" },
intent_frame: {
type: "object",
description: "Optional IntentFrame to sharpen SOP scope and success criteria.",
properties: {
perspective: { type: "string", description: "The agent role or viewpoint (e.g. DevOps engineer)." },
out_of_scope: { type: "string", description: "What is explicitly excluded from this workflow." },
success_definition: { type: "string", description: "Measurable criteria that define success." }
},
additionalProperties: false
}
},
required: ["goal"]
}
},
{
name: "generate_skill_package",
description: "Generate a complete skill package (SOP + SKILL.md + examples + helper.py) for an AI agent. Takes 30-120 seconds (async).",
inputSchema: {
type: "object",
properties: {
goal: { type: "string", description: "What the agent should accomplish" },
format: { type: "string", enum: ["knowledge_doc", "agent_spec"], description: "Output format" },
model_id: { type: "string", description: "Model to use (optional)" }
},
required: ["goal"]
}
},
{
name: "transform_for_framework",
description: "Transform a SOP into native code for LangChain, AutoGen, or Claude Code.",
inputSchema: {
type: "object",
properties: {
sop_content: { type: "string", description: "SOP content to transform" },
goal: { type: "string", description: "What the agent should accomplish" },
framework: { type: "string", enum: ["langchain_tool", "autogen_agent", "claude_skill"], description: "Target framework" }
},
required: ["sop_content", "goal", "framework"]
}
},
{
name: "get_ce_quota_status",
description: "Check your Context Engineer credit balance and available workflow types.",
inputSchema: { type: "object", properties: {}, additionalProperties: false }
},
{
name: "generate_harness_bundle",
description: (
"Generate a deployment-ready Agentic Harness ZIP bundle for a specific platform. "
+ "Returns a confirmation message when the bundle is queued. "
+ "Explorer+ required for non-default deploy targets."
),
inputSchema: {
type: "object",
properties: {
goal: {
type: "string",
description: "The workflow goal the harness is built for."
},
deploy_target: {
oneOf: [
{
type: "string",
enum: DEPLOY_TARGET_ENUM,
description: "Single deploy target."
},
{
type: "array",
minItems: 1,
items: {
type: "string",
enum: DEPLOY_TARGET_ENUM
},
description: "Multiple deploy targets simultaneously (Creator+ required)."
}
],
description: (
"Target deployment platform(s). Single string (Explorer+) or array (Creator+). "
+ "amazon_q, aider, continue_dev, crewai require Creator+. "
+ "Default: claude_code."
)
},
session_id: {
type: "string",
description: "Optional: session ID from a prior generate_skill_package call to reuse SOP."
},
sop_content: {
type: "string",
description: "The SOP content to base the harness on (required if no session_id)."
},
agent_read_only: {
type: "boolean",
description: (
"Narrow the generated Claude Code subagent's tools to Read/Grep/Glob only. "
+ "Set this for audit/review workflows that should never edit or execute anything. "
+ "Default: false (full capability)."
)
},
agent_harness: {
type: "string",
enum: ["claude-sdk", "codex", "pi"],
description: (
"Execution backend for the generated agent.yaml: 'claude-sdk' (needs ANTHROPIC_API_KEY), "
+ "'codex' (needs OPENROUTER_API_KEY or OPENAI_API_KEY), or 'pi' (needs PI_API_KEY). "
+ "Set this to match the API key available wherever the bundle will actually run — "
+ "the default is per-deploy-target (usually claude-sdk) and won't know which key you have."
)
}
},
required: ["goal"]
}
},
{
name: "explore_sop_approaches",
description: (
"Generate 3 parallel SOP variants (process-oriented, decision-tree, role-based) for comparison before committing. " +
"Returns exploration_html (self-contained comparison grid), variants array, and a recommended variant. " +
"Innovator tier required. " +
"Optionally provide blend_description to skip comparison and receive a single blended SOP instead."
),
inputSchema: {
type: "object",
properties: {
goal: {
type: "string",
description: "The workflow goal to generate SOP variants for"
},
context: {
type: "string",
description: "Optional background context or documentation excerpt"
},
blend_description: {
type: "string",
description: "Optional: if provided, skips variant comparison and blends all 3 into one SOP using this description"
},
perspective: { type: "string", description: "Agent role or viewpoint (IntentFrame)" },
out_of_scope: { type: "string", description: "What is explicitly excluded (IntentFrame)" },
success_definition: { type: "string", description: "Measurable success criteria (IntentFrame)" },
},
required: ["goal"],
additionalProperties: false
}
},
{
name: "get_prompt_by_slug",
description: "Fetch your latest published prompt template by slug for runtime use — decouple prompts from deploys.",
inputSchema: {
type: "object",
properties: {
slug: { type: "string", description: "The URL-safe slug of the prompt template (e.g., product-writer-a3f9c21b)" }
},
required: ["slug"]
}
},
{
name: "compile_prompt",
description: "Compile a prompt template with variable interpolation for runtime delivery — returns the fully interpolated prompt string ready for use.",
inputSchema: {
type: "object",
properties: {
slug: { type: "string", description: "The URL-safe slug of the prompt template" },
variables: {
type: "object",
description: "Variable values to interpolate (e.g. {\"user_name\": \"Alex\", \"plan\": \"Pro\"})",
additionalProperties: { type: "string" }
}
},
required: ["slug"]
}
},
{
name: "list_template_versions",
description: "List all version snapshots of a saved template — every update creates a snapshot you can inspect or restore.",
inputSchema: {
type: "object",
properties: {
template_id: { type: "string", description: "The ID of the template" }
},
required: ["template_id"]
}
},
{
name: "rollback_template",
description: "Restore a template to a previous version snapshot — undo unwanted changes instantly.",
inputSchema: {
type: "object",
properties: {
template_id: { type: "string", description: "The ID of the template" },
version_number: { type: "number", description: "The version number to roll back to (use list_template_versions to find available versions)" }
},
required: ["template_id", "version_number"]
}
},
{
name: "publish_template",
description: "Publish a template — makes it available for runtime delivery via get_prompt_by_slug.",
inputSchema: {
type: "object",
properties: {
template_id: { type: "string", description: "The ID of the template to publish" }
},
required: ["template_id"]
}
},
{
name: "run_quick_evaluation",
description: "Run a stateless one-shot evaluation of an optimized prompt using LLM judges — get actionable quality scoring without creating a dataset.",
inputSchema: {
type: "object",
properties: {
prompt: { type: "string", description: "The optimized prompt to evaluate" },
original_prompt: { type: "string", description: "The original prompt for comparison scoring" }
},
required: ["prompt", "original_prompt"]
}
},
];
// Add advanced tools if Bayesian optimization is enabled
if (this.bayesianOptimizationEnabled) {
baseTools.push({
name: "get_optimization_insights",
description: "🧠 Get advanced Bayesian optimization insights, performance analytics, and parameter tuning recommendations",
inputSchema: {
type: "object",
properties: {
analysis_depth: {
type: "string",
enum: ["basic", "detailed", "comprehensive"],
default: "detailed",
description: "Depth of analysis to provide"
},
include_recommendations: {
type: "boolean",
default: true,
description: "Include optimization recommendations"
}
}
}
});
}
// Add AG-UI tools if enabled
if (this.aguiFeatures) {
baseTools.push({
name: "get_real_time_status",
description: "⚡ Get real-time optimization status, AG-UI capabilities, and streaming optimization availability",
inputSchema: { type: "object", properties: {}, additionalProperties: false }
});
}
return { tools: baseTools };
});
this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
try {
switch (name) {
case "optimize_prompt": return await this.handleOptimizePrompt(args);
case "get_quota_status": return await this.handleGetQuotaStatus();
case "search_templates": return await this.handleSearchTemplates(args);
case "list_recent_templates": return await this.handleListRecentTemplates(args);
case "detect_ai_context": return await this.handleDetectAIContext(args);
case "create_template": return await this.handleCreateTemplate(args);
case "get_template": return await this.handleGetTemplate(args);
case "update_template": return await this.handleUpdateTemplate(args);
case "delete_template": return await this.handleDeleteTemplate(args);
case "get_optimization_insights": return await this.handleGetOptimizationInsights(args);
case "get_real_time_status": return await this.handleGetRealTimeStatus();
case "generate_agent_sop": return await this.handleGenerateAgentSop(args);
case "generate_skill_package": return await this.handleGenerateSkillPackage(args);
case "transform_for_framework": return await this.handleTransformForFramework(args);
case "get_ce_quota_status": return await this.handleGetCEQuotaStatus();
case "generate_harness_bundle": return await this.handleGenerateHarnessBundle(args);
case "explore_sop_approaches": return await this.handleExploreSopApproaches(args);
case "get_prompt_by_slug": return await this.handleGetPromptBySlug(args);
case "compile_prompt": return await this.handleCompilePrompt(args);
case "list_template_versions": return await this.handleListTemplateVersions(args);
case "rollback_template": return await this.handleRollbackTemplate(args);
case "publish_template": return await this.handlePublishTemplate(args);
case "run_quick_evaluation": return await this.handleRunQuickEvaluation(args);
default: throw new Error(`Unknown tool: ${name}`);
}
} catch (error) {
throw new Error(`Tool execution failed: ${error.message}`);
}
});
}
// ─── Rules-Based Optimization (offline / fallback tier) ─────────────────────
/**
* Select the best-matching template for a prompt using pattern scoring.
* Mirrors the backend's pattern-based fallback (no LLM required).
*/
_matchTemplate(prompt, backendContext) {
const lc = prompt.toLowerCase();
let bestTemplate = null;
let bestScore = 0;
let fallbackName = null;
for (const [name, template] of Object.entries(OPTIMIZATION_TEMPLATES)) {
if (template.context !== backendContext) continue;
if (name.startsWith('fallback_')) { fallbackName = name; continue; }
let hits = 0;
for (const pattern of template.patterns) {
if (pattern === '.*') continue;
if (lc.includes(pattern.toLowerCase())) hits++;
}
if (hits === 0) continue;
// Confidence: 1 hit → 0.6, 2 hits → 0.75, 3+ hits → 0.9 (mirrors backend)
const patternConf = hits === 1 ? 0.6 : hits === 2 ? 0.75 : 0.9;
const score = patternConf + (template.priority || 1) / 100;
if (score > bestScore) { bestScore = score; bestTemplate = name; }
}
if (!bestTemplate) {
return { templateName: fallbackName || `fallback_${backendContext.toLowerCase()}`, matchConfidence: 0.3 };
}
return { templateName: bestTemplate, matchConfidence: bestScore };
}
/** Extract a user-defined role from the start of a prompt (e.g. "As a doctor, …"). */
_extractUserRole(request) {
const rolePatterns = [
/^['"]?(?:As a|You are a|My role is)\s+([a-zA-Z0-9\s\-/()]+?)(?:,|(?=\s*\.))/i,
/^['"]?(?:I am a|I'm a)\s+([a-zA-Z0-9\s\-/()]+?)(?:,|(?=\s*\.))/i,
];
for (const re of rolePatterns) {
const m = request.match(re);
if (m) return m[1].trim();
}
return null;
}
/**
* Compile a template playbook into a user-facing prose prompt.
* Produces readable output instead of XML scaffolding, matching the
* result a backend LLM pass would generate from the same playbook.
*/
_compilePlaybook(playbook, originalRequest) {
const parts = [];
parts.push(originalRequest.trim());
parts.push('');
const userFacingPrinciples = (playbook.principles || []).filter(p => {
const lc = p.toLowerCase();
return !lc.includes('scratchpad') &&
!lc.startsWith('first, think') &&
!/<[a-z]/i.test(p);
});
if (userFacingPrinciples.length > 0) {
parts.push('To address this effectively:');
for (const p of userFacingPrinciples) parts.push(`- ${p}`);
parts.push('');
}
if (playbook.output_format) {
parts.push(`*Response format: ${playbook.output_format}*`);
}
return parts.join('\n');
}
/**
* Enhance an image generation prompt by appending style-appropriate
* quality/composition boosters (mirrors backend _compile_image_prompt_fallback).
*/
_compileImagePrompt(originalRequest) {
const text = originalRequest.trim();
const lc = text.toLowerCase();
const styles = {
photorealistic: ['photorealistic','realistic','photo','photograph','photography'],
'3d_render': ['3d','render','octane','unreal engine','blender','cinema 4d','ray tracing'],
cinematic: ['cinematic','movie','film','dramatic','epic'],
digital_art: ['digital art','concept art','digital illustration','cg','cgi'],
artistic: ['artistic','painting','watercolor','oil painting','impressionist'],
anime: ['anime','manga'],
vintage: ['vintage','retro','nostalgic'],
minimalist: ['minimalist','minimal','simple','clean'],
};
let detectedStyle = null;
for (const [style, kws] of Object.entries(styles)) {
if (kws.some(kw => lc.includes(kw))) { detectedStyle = style; break; }
}
const enhancements = [];
const hasQuality = ['high quality','8k','4k','hd','highly detailed','detailed'].some(t => lc.includes(t));
const hasLighting = ['lighting','light','shadow','illuminated','lit'].some(t => lc.includes(t));
const hasComposition = ['composition','rule of thirds','centered','framed'].some(t => lc.includes(t));
if (detectedStyle === 'photorealistic' && !hasQuality) {
enhancements.push('ultra realistic, sharp focus, professional photography');
} else if (detectedStyle === '3d_render' && !['octane','render'].some(t => lc.includes(t))) {
enhancements.push('high quality 3D render, volumetric lighting, ray traced shadows');
} else if (detectedStyle === 'cinematic' && !hasLighting) {
enhancements.push('cinematic lighting, dramatic atmosphere, film grain');
} else if (detectedStyle === 'digital_art' && !hasQuality) {
enhancements.push('highly detailed digital art, professional illustration');
} else if (detectedStyle === 'artistic' && !lc.includes('masterpiece')) {
enhancements.push('masterful technique, rich colors, artistic composition');
}
if (!hasLighting && detectedStyle !== 'minimalist') enhancements.push('dynamic lighting');
if (!hasComposition) enhancements.push('balanced composition');
if (!hasQuality) enhancements.push('high quality, 4K');
return enhancements.length > 0 ? `${text}, ${enhancements.join(', ')}` : text;
}
/**
* Core rules-based optimizer — no network, no LLM.
* Selects the best template by pattern matching, then compiles
* the playbook into a structured prompt. Confidence range: 0.35–0.55.
*/
rulesBasedOptimize(prompt, aiContext, goals = []) {
const contextMap = {
code_generation: 'CODE_GENERATION',
llm_interaction: 'LLM_INTERACTION',
image_generation: 'IMAGE_GENERATION',
human_communication: 'HUMAN_COMMUNICATION',
api_automation: 'API_AUTOMATION',
technical_automation: 'TECHNICAL_AUTOMATION',
structured_output: 'STRUCTURED_OUTPUT',
creative_enhancement: 'CREATIVE_ENHANCEMENT',
creative_writing: 'CREATIVE_ENHANCEMENT',
general_assistant: 'LLM_INTERACTION',
};
const backendContext = contextMap[aiContext] || 'LLM_INTERACTION';
const { templateName, matchConfidence } = this._matchTemplate(prompt, backendContext);
const template = OPTIMIZATION_TEMPLATES[templateName];
const optimizedPrompt = backendContext === 'IMAGE_GENERATION'
? this._compileImagePrompt(prompt)
: this._compilePlaybook(template.playbook, prompt);
// Honest confidence: rules-based tops out around 0.55
const confidence = parseFloat(Math.min(0.35 + matchConfidence * 0.2, 0.55).toFixed(2));
return {
optimized_prompt: optimizedPrompt,
confidence_score: confidence,
tier: 'rules',
template_used: templateName,
rules_based: true,
template_saved: false,
templates_found: [],
optimization_insights: null,
bayesian_insights: null,
};
}
// ─── End Rules-Based Optimization ────────────────────────────────────────────
generateMockOptimization(prompt, goals, aiContext, enableBayesian = false) {
// Use real rules-based optimization instead of fake placeholder output
const rulesResult = this.rulesBasedOptimize(prompt, aiContext, goals);
const baseResult = {
...rulesResult,
rules_based: false, // Show as normal optimized output in mock mode
tier: 'free',
mock_mode: true,
template_saved: true,
template_id: 'test-template-123',
templates_found: [{ title: 'Similar Template 1', confidence_score: 0.85, id: 'tmpl-1' }],
optimization_insights: {
improvement_metrics: {
clarity_improvement: 0.25,
specificity_improvement: 0.20,
length_optimization: 0.15,
context_alignment: 0.30
},
user_patterns: {
optimization_confidence: '87.0%',
prompt_complexity: 'intermediate',
ai_context: aiContext
},
recommendations: [
`Context detected as ${aiContext}`,
'Enhanced goal optimization applied',
'Template auto-save threshold met'
]
}
};
// Add Bayesian optimization insights if enabled
if (enableBayesian && this.bayesianOptimizationEnabled) {
baseResult.bayesian_insights = {
parameter_optimization: {
temperature_adjustment: '+0.1',
context_weight: '+0.15',
goal_prioritization: 'clarity > specificity > engagement'
},
performance_prediction: {
expected_improvement: '12-18%',
confidence_interval: '85-95%',
optimization_strategy: 'gradient_boost_context'
},
next_optimization_recommendation: {
suggested_goals: ['analytical_depth', 'creative_enhancement'],
estimated_improvement: '8-12%'
}
};
}
return baseResult;
}
generateMockContextDetection(prompt) {
let primary_context = 'human_communication'; // Default context
const lc = prompt.toLowerCase(); // one‑off lower‑case copy
/* 1️⃣ Code / programming – now includes `def` / `return`. */
if (lc.match(/def\b|return\b|import\b|class\b|for\b|while\b|if\b|else\b|elif\b|function\b|code\b|python|javascript|java|c\+\+/i)) {
primary_context = 'code_generation';
/* 2️⃣ Image / art – unchanged. */
} else if (lc.match(/image|generate|dall-e|midjourney/i)) {
primary_context = 'image_generation';
/* 3️⃣ Automation – unchanged. */
} else if (lc.match(/automate|script|api/i)) {
primary_context = 'technical_automation';
/* 4️⃣ LLM / analysis – newly added keyword “analyze”. */
} else if (lc.match(/analyze|explain|evaluate|summary|research|paper|analysis|interpret|discussion|assessment|compare|contrast/i)) {
primary_context = 'llm_interaction';
}
return {
primary_context: primary_context,
confidence: 0.75,
secondary_contexts: ['llm_interaction'],
detected_parameters: [],
mock_mode: true,
reason: 'Backend unavailable — using local pattern matching as fallback.'
};
}
async handleOptimizePrompt(args) {
if (!args.prompt) throw new Error('Prompt is required');
const manager = new CloudApiKeyManager(this.apiKey);
try {
const validation = await manager.validateApiKey();
if (validation.mock_mode || this.developmentMode) {
// In mock/dev mode, we still need a context for mock generation
const mockContext = args.ai_context || 'human_communication';
const mockGoals = args.goals || ['clarity'];
const mockEnableBayesian = args.enable_bayesian !== false && this.bayesianOptimizationEnabled;
const mockResult = this.generateMockOptimization(args.prompt, mockGoals, mockContext, mockEnableBayesian);
const formatted = this.formatOptimizationResult(mockResult, { detectedContext: mockContext, enableBayesian: mockEnableBayesian });
return { content: [{ type: "text", text: formatted }] };
}
// 1. Detect AI Context from backend
let detectedContext = args.ai_context;
if (!detectedContext) {
try {
const contextDetectionResult = await this.callBackendAPI(ENDPOINTS.DETECT_CONTEXT, { prompt: args.prompt });
detectedContext = contextDetectionResult.primary_context;
console.error(`Detected AI Context from backend: ${detectedContext}`);
} catch (contextError) {
console.error(`Failed to detect AI context from backend, falling back to default: ${contextError.message}`);
detectedContext = 'human_communication'; // Fallback
}
}
// 2. Call the main optimization endpoint
const optimizationPayload = {
prompt: args.prompt,
goals: args.goals || ['clarity'],
ai_context: detectedContext,
};
if (args.value_hierarchy && args.value_hierarchy.length > 0) {
optimizationPayload.value_hierarchy = args.value_hierarchy;
}
if (args.intent_frame && typeof args.intent_frame === 'object') {
const { perspective, out_of_scope, success_definition } = args.intent_frame;
if (perspective || (out_of_scope && out_of_scope.length > 0) || success_definition) {
optimizationPayload.intent_frame = args.intent_frame;
}
}
if (args.reasoning_effort) {
optimizationPayload.reasoning_effort = args.reasoning_effort;
}
if (args.execution_shape) {
optimizationPayload.execution_shape = args.execution_shape;
}
const result = await this.callBackendAPI(ENDPOINTS.OPTIMIZE, optimizationPayload);
const enableBayesian = args.enable_bayesian !== false && this.bayesianOptimizationEnabled;
return { content: [{ type: "text", text: this.formatOptimizationResult(result, { detectedContext, enableBayesian, requestedExecutionShape: args.execution_shape }) }] };
} catch (error) {
if (error.message.includes('Network') || error.message.includes('DNS') || error.message.includes('timeout') || error.message.includes('Connection')) {
const fallbackContext = args.ai_context || 'human_communication';
const fallbackEnableBayesian = args.enable_bayesian !== false && this.bayesianOptimizationEnabled;
const fallbackResult = this.rulesBasedOptimize(args.prompt, fallbackContext, args.goals || ['clarity']);
fallbackResult.fallback_mode = true;
fallbackResult.error_reason = error.message;
const formatted = this.formatOptimizationResult(fallbackResult, { detectedContext: fallbackContext, enableBayesian: fallbackEnableBayesian });
return { content: [{ type: "text", text: formatted }] };
}
throw new Error(`Optimization failed: ${error.message}`);
}
}
async handleGetQuotaStatus() {
const manager = new CloudApiKeyManager(this.apiKey);
const info = await manager.getApiKeyInfo();
return { content: [{ type: "text", text: this.formatQuotaStatus(info) }] };
}
async handleSearchTemplates(args) {
try {
const params = new URLSearchParams({
page: (args.page || 1).toString(),
per_page: Math.min(args.limit || 5, 20).toString(),
sort_by: args.sort_by || 'confidence_score',
sort_order: args.sort_order || 'desc'
});
if (args.query) params.append('query', args.query);
if (args.ai_context) params.append('ai_context', args.ai_context);
if (args.sophistication_level) params.append('sophistication_level', args.sophistication_level);
if (args.complexity_level) params.append('complexity_level', args.complexity_level);
if (args.optimization_strategy) params.append('optimization_strategy', args.optimization_strategy);
const endpoint = `${ENDPOINTS.SEARCH_TEMPLATES}?${params.toString()}`;
const result = await this.callBackendAPI(endpoint, null, 'GET');
const searchResult = {
templates: result.templates || [],
total: result.total || 0,
query: args.query,
ai_context: args.ai_context,
sophistication_level: args.sophistication_level,
complexity_level: args.complexity_level
};
const formatted = this.formatTemplateSearchResults(searchResult, args);
return { content: [{ type: "text", text: formatted }] };
} catch (error) {
console.error(`Template search failed: ${error.message}`);
const fallbackResult = {
templates: [],
total: 0,
message: "Template search is temporarily unavailable.",
error: error.message,
fallback_mode: true
};
const formatted = this.formatTemplateSearchResults(fallbackResult, args);
return { content: [{ type: "text", text: formatted }] };
}
}
async handleListRecentTemplates(args) {
try {
const limit = Math.min(Math.max(args.limit || 10, 1), 20);
const params = new URLSearchParams({
page: '1',
per_page: limit.toString(),
sort_by: 'created_at',
sort_order: 'desc'
});
const endpoint = `${ENDPOINTS.SEARCH_TEMPLATES}?${params.toString()}`;
const result = await this.callBackendAPI(endpoint, null, 'GET');
const templates = result.templates || [];
let output = `# 📋 Recent Templates\n\n`;
output += `Showing **${templates.length}** most recently saved template(s).\n\n`;
if (templates.length === 0) {
output += `📭 No templates found yet.\nRun \`optimize_prompt\` to start building your template library.\n`;
} else {
output += `## 📋 **Template Results**\n`;
templates.forEach((t, index) => {
const confidence = t.confidence_score ? `${(t.confidence_score * 100).toFixed(1)}%` : 'N/A';
const preview = t.optimized_prompt ? t.optimized_prompt.substring(0, 60) + '...' : 'Preview unavailable';
output += `### ${index + 1}. ${t.title}\n`;
output += `- **Confidence:** ${confidence}\n`;
output += `- **ID:** \`${t.id}\`\n`;
output += `- **Preview:** ${preview}\n`;
if (t.ai_context) output += `- **Context:** ${t.ai_context}\n`;
if (t.optimization_goals && t.optimization_goals.length) {
output += `- **Goals:** ${t.optimization_goals.join(', ')}\n`;
}
output += `\n`;
});
output += `💡 Use \`get_template\` with an ID above to view the full optimized prompt.\n`;
}
return { content: [{ type: "text", text: output }] };
} catch (error) {
return { content: [{ type: "text", text: `❌ Could not retrieve recent templates: ${error.message}` }] };
}
}
async handleGetOptimizationInsights(args) {
if (!this.bayesianOptimizationEnabled) {
return { content: [{ type: "text", text: "🧠 Bayesian optimization features are not enabled. Set ENABLE_BAYESIAN_OPTIMIZATION=true to access advanced insights." }] };
}
try {
// Try to get insights from backend
const endpoint = `${ENDPOINTS.ANALYTICS_BAYESIAN_INSIGHTS}?depth=${args.analysis_depth || 'detailed'}&recommendations=${args.include_recommendations !== false}`;
const result = await this.callBackendAPI(endpoint, null, 'GET');
return { content: [{ type: "text", text: this.formatOptimizationInsights(result) }] };
} catch (error) {
return { content: [{ type: "text", text: `🧠 Optimization insights are unavailable right now (${error.message}). This is not your data — no insights were g