mcp-prompt-optimizer 1.4.2 → 2.2.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/CHANGELOG.md +78 -53
- package/CROSS-PLATFORM.md +3 -3
- package/README.md +99 -39
- package/index.js +843 -187
- package/lib/api-key-manager.js +191 -138
- package/lib/check-status.js +1 -1
- package/package.json +80 -5
- package/tests/README.md +0 -232
- package/tests/comprehensive-test.js +0 -692
- package/tests/integration-test.js +0 -446
- package/tests/minimal-test.js +0 -265
- package/tests/quick-test.js +0 -256
- package/tests/simple-test.js +0 -171
- package/tests/test-runner.js +0 -322
package/index.js
CHANGED
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* MCP Prompt Optimizer - Professional Cloud-Based MCP Server
|
|
5
|
-
* Production-grade with
|
|
5
|
+
* Production-grade with Bayesian optimization, AG-UI real-time features, enhanced network resilience,
|
|
6
|
+
* development mode, and complete backend alignment
|
|
6
7
|
*
|
|
7
|
-
* Version:
|
|
8
|
+
* Version: 2.2.0 - Aligned with FastAPI Backend production-v2.2.0-stable
|
|
8
9
|
*/
|
|
9
10
|
|
|
10
11
|
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
|
|
@@ -14,6 +15,53 @@ const https = require('https');
|
|
|
14
15
|
const CloudApiKeyManager = require('./lib/api-key-manager');
|
|
15
16
|
const packageJson = require('./package.json');
|
|
16
17
|
|
|
18
|
+
const API_KEYS_PREFIX = '/api/v1/api-keys';
|
|
19
|
+
|
|
20
|
+
const ENDPOINTS = {
|
|
21
|
+
/** Detect AI context (POST) */
|
|
22
|
+
DETECT_CONTEXT: '/api/v1/templates/detect-context',
|
|
23
|
+
|
|
24
|
+
/** Prompt optimization (POST) */
|
|
25
|
+
OPTIMIZE: '/api/v1/optimize',
|
|
26
|
+
|
|
27
|
+
/** CRUD on templates */
|
|
28
|
+
TEMPLATE: {
|
|
29
|
+
/** Create (POST) */
|
|
30
|
+
CREATE: '/api/v1/templates/',
|
|
31
|
+
|
|
32
|
+
/** Read (GET) */
|
|
33
|
+
GET: (id) => `/api/v1/templates/${id}`,
|
|
34
|
+
|
|
35
|
+
/** Update (PATCH) */
|
|
36
|
+
UPDATE: (id) => `/api/v1/templates/${id}`,
|
|
37
|
+
|
|
38
|
+
/** Delete (DELETE) */
|
|
39
|
+
DELETE: (id) => `/api/v1/templates/${id}`,
|
|
40
|
+
},
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Search templates
|
|
44
|
+
* (In the current code‑base this is *not* a dedicated `/search` path –
|
|
45
|
+
* the original implementation appends query‑params to `/api/v1/templates/`.
|
|
46
|
+
* We keep the original path here so that the existing `handleSearchTemplates`
|
|
47
|
+
* handler does not need any change other than using the constant.
|
|
48
|
+
*/
|
|
49
|
+
SEARCH_TEMPLATES: '/api/v1/templates/',
|
|
50
|
+
|
|
51
|
+
/** Quota status (GET) – note the plural “api‑keys” */
|
|
52
|
+
QUOTA_STATUS: `${API_KEYS_PREFIX}/quota-status`,
|
|
53
|
+
|
|
54
|
+
/** Validate API key (POST) – also under the plural router */
|
|
55
|
+
VALIDATE_KEY: `${API_KEYS_PREFIX}/validate`,
|
|
56
|
+
|
|
57
|
+
/** Bayesian insights (GET) */
|
|
58
|
+
ANALYTICS_BAYESIAN_INSIGHTS:
|
|
59
|
+
'/api/v1/analytics/bayesian-insights',
|
|
60
|
+
|
|
61
|
+
/** AG‑UI status (GET) */
|
|
62
|
+
AGUI_STATUS: '/api/v1/agui/status',
|
|
63
|
+
};
|
|
64
|
+
|
|
17
65
|
class MCPPromptOptimizer {
|
|
18
66
|
constructor() {
|
|
19
67
|
this.server = new Server(
|
|
@@ -32,64 +80,208 @@ class MCPPromptOptimizer {
|
|
|
32
80
|
this.apiKey = process.env.OPTIMIZER_API_KEY;
|
|
33
81
|
this.developmentMode = process.env.NODE_ENV === 'development' || process.env.OPTIMIZER_DEV_MODE === 'true';
|
|
34
82
|
this.requestTimeout = parseInt(process.env.OPTIMIZER_REQUEST_TIMEOUT) || 30000;
|
|
83
|
+
|
|
84
|
+
// NEW: Feature flags aligned with backend
|
|
85
|
+
this.bayesianOptimizationEnabled = process.env.ENABLE_BAYESIAN_OPTIMIZATION === 'true';
|
|
86
|
+
this.aguiFeatures = process.env.ENABLE_AGUI_FEATURES === 'true';
|
|
87
|
+
|
|
35
88
|
this.setupMCPHandlers();
|
|
36
89
|
}
|
|
37
90
|
|
|
38
91
|
setupMCPHandlers() {
|
|
39
92
|
this.server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
93
|
+
const baseTools = [
|
|
94
|
+
{
|
|
95
|
+
name: "optimize_prompt",
|
|
96
|
+
description: "🎯 Professional AI-powered prompt optimization with intelligent context detection, Bayesian optimization, template auto-save, and comprehensive optimization insights",
|
|
97
|
+
inputSchema: {
|
|
98
|
+
type: "object",
|
|
99
|
+
properties: {
|
|
100
|
+
prompt: {
|
|
101
|
+
type: "string",
|
|
102
|
+
description: "The prompt text to optimize"
|
|
103
|
+
},
|
|
104
|
+
goals: {
|
|
105
|
+
type: "array",
|
|
106
|
+
items: { type: "string" },
|
|
107
|
+
description: "Optimization goals (e.g., 'clarity', 'conciseness', 'creativity', 'technical_accuracy', 'analytical_depth', 'creative_enhancement')",
|
|
108
|
+
default: ["clarity"]
|
|
109
|
+
},
|
|
110
|
+
ai_context: {
|
|
111
|
+
type: "string",
|
|
112
|
+
enum: [
|
|
113
|
+
"human_communication", "llm_interaction", "image_generation", "technical_automation",
|
|
114
|
+
"structured_output", "code_generation", "api_automation"
|
|
115
|
+
],
|
|
116
|
+
description: "The context for the AI's task (auto-detected if not specified with enhanced detection)"
|
|
117
|
+
},
|
|
118
|
+
enable_bayesian: {
|
|
119
|
+
type: "boolean",
|
|
120
|
+
description: "Enable Bayesian optimization features for parameter tuning (if available)",
|
|
121
|
+
default: true
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
required: ["prompt"]
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
name: "get_quota_status",
|
|
129
|
+
description: "📊 Check subscription status, quota usage, and account information with detailed insights and Bayesian optimization metrics",
|
|
130
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false }
|
|
131
|
+
},
|
|
132
|
+
{
|
|
133
|
+
name: "create_template",
|
|
134
|
+
description: "➕ Create a new optimization template.",
|
|
135
|
+
inputSchema: {
|
|
136
|
+
type: "object",
|
|
137
|
+
properties: {
|
|
138
|
+
title: { type: "string", description: "Title of the template" },
|
|
139
|
+
description: { type: "string", description: "Description of the template" },
|
|
140
|
+
original_prompt: { type: "string", description: "The original prompt text" },
|
|
141
|
+
optimized_prompt: { type: "string", description: "The optimized prompt text" },
|
|
142
|
+
optimization_goals: { type: "array", items: { type: "string" }, description: "Goals for this optimization (e.g., 'clarity', 'conciseness', 'creativity', 'technical_accuracy', 'analytical_depth', 'creative_enhancement')" },
|
|
143
|
+
confidence_score: { type: "number", description: "Confidence score of the optimization (0.0-1.0)" },
|
|
144
|
+
model_used: { type: "string", description: "Model used for optimization" },
|
|
145
|
+
optimization_tier: { type: "string", description: "Tier of optimization (e.g., rules, llm, hybrid)" },
|
|
146
|
+
ai_context_detected: { type: "string", description: "Detected AI context (e.g., code_generation, image_generation)" },
|
|
147
|
+
is_public: { type: "boolean", default: false, description: "Whether the template is public" },
|
|
148
|
+
tags: { type: "array", items: { type: "string" }, description: "Tags for the template" }
|
|
149
|
+
},
|
|
150
|
+
required: ["title", "original_prompt", "optimized_prompt", "confidence_score"]
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
name: "get_template",
|
|
155
|
+
description: "🔍 Retrieve a specific template by its ID.",
|
|
156
|
+
inputSchema: {
|
|
157
|
+
type: "object",
|
|
158
|
+
properties: {
|
|
159
|
+
template_id: { type: "string", description: "The ID of the template to retrieve" }
|
|
160
|
+
},
|
|
161
|
+
required: ["template_id"]
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
{
|
|
165
|
+
name: "update_template",
|
|
166
|
+
description: "✏️ Update an existing optimization template.",
|
|
167
|
+
inputSchema: {
|
|
168
|
+
type: "object",
|
|
169
|
+
properties: {
|
|
170
|
+
template_id: { type: "string", description: "The ID of the template to update" },
|
|
171
|
+
title: { type: "string", description: "New title for the template" },
|
|
172
|
+
description: { type: "string", description: "New description for the template" },
|
|
173
|
+
original_prompt: { type: "string", description: "New original prompt text" },
|
|
174
|
+
optimized_prompt: { type: "string", description: "New optimized prompt text" },
|
|
175
|
+
optimization_goals: { type: "array", items: { type: "string" }, description: "New optimization goals" },
|
|
176
|
+
confidence_score: { type: "number", description: "New confidence score (0.0-1.0)" },
|
|
177
|
+
model_used: { type: "string", description: "New model used for optimization" },
|
|
178
|
+
optimization_tier: { type: "string", description: "New tier of optimization" },
|
|
179
|
+
ai_context_detected: { type: "string", description: "New detected AI context" },
|
|
180
|
+
is_public: { type: "boolean", description: "Whether the template is public" },
|
|
181
|
+
tags: { type: "array", items: { type: "string" }, description: "New tags for the template" }
|
|
182
|
+
},
|
|
183
|
+
required: ["template_id"]
|
|
184
|
+
}
|
|
185
|
+
},
|
|
186
|
+
{
|
|
187
|
+
name: "search_templates",
|
|
188
|
+
description: "🔍 Search your saved template library with AI-aware filtering, context-based search, and sophisticated template matching",
|
|
189
|
+
inputSchema: {
|
|
190
|
+
type: "object",
|
|
191
|
+
properties: {
|
|
192
|
+
query: {
|
|
193
|
+
type: "string",
|
|
194
|
+
description: "Search term to filter templates by content or title"
|
|
195
|
+
},
|
|
196
|
+
ai_context: {
|
|
197
|
+
type: "string",
|
|
198
|
+
enum: ["human_communication", "llm_interaction", "image_generation", "technical_automation", "structured_output", "code_generation", "api_automation"],
|
|
199
|
+
description: "Filter templates by AI context type"
|
|
200
|
+
},
|
|
201
|
+
sophistication_level: {
|
|
202
|
+
type: "string",
|
|
203
|
+
enum: ["basic", "intermediate", "advanced", "expert"],
|
|
204
|
+
description: "Filter by template sophistication level"
|
|
205
|
+
},
|
|
206
|
+
complexity_level: {
|
|
207
|
+
type: "string",
|
|
208
|
+
enum: ["simple", "moderate", "complex", "very_complex"],
|
|
209
|
+
description: "Filter by template complexity level"
|
|
210
|
+
},
|
|
211
|
+
optimization_strategy: {
|
|
212
|
+
type: "string",
|
|
213
|
+
description: "Filter by optimization strategy used"
|
|
214
|
+
},
|
|
215
|
+
limit: {
|
|
216
|
+
type: "number",
|
|
217
|
+
default: 5,
|
|
218
|
+
description: "Number of templates to return (1-20)"
|
|
219
|
+
},
|
|
220
|
+
sort_by: {
|
|
221
|
+
type: "string",
|
|
222
|
+
enum: ["created_at", "confidence_score", "usage_count", "title"],
|
|
223
|
+
default: "confidence_score",
|
|
224
|
+
description: "Sort templates by field"
|
|
66
225
|
},
|
|
67
|
-
|
|
226
|
+
sort_order: {
|
|
227
|
+
type: "string",
|
|
228
|
+
enum: ["asc", "desc"],
|
|
229
|
+
default: "desc",
|
|
230
|
+
description: "Sort order"
|
|
231
|
+
}
|
|
68
232
|
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
233
|
+
}
|
|
234
|
+
},
|
|
235
|
+
{
|
|
236
|
+
name: "detect_ai_context",
|
|
237
|
+
description: "🧠 Detects the AI context for a given prompt using advanced backend analysis.",
|
|
238
|
+
inputSchema: {
|
|
239
|
+
type: "object",
|
|
240
|
+
properties: {
|
|
241
|
+
prompt: {
|
|
242
|
+
type: "string",
|
|
243
|
+
description: "The prompt text for which to detect the AI context"
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
required: ["prompt"]
|
|
247
|
+
}
|
|
248
|
+
},
|
|
249
|
+
];
|
|
250
|
+
|
|
251
|
+
// Add advanced tools if Bayesian optimization is enabled
|
|
252
|
+
if (this.bayesianOptimizationEnabled) {
|
|
253
|
+
baseTools.push({
|
|
254
|
+
name: "get_optimization_insights",
|
|
255
|
+
description: "🧠 Get advanced Bayesian optimization insights, performance analytics, and parameter tuning recommendations",
|
|
256
|
+
inputSchema: {
|
|
257
|
+
type: "object",
|
|
258
|
+
properties: {
|
|
259
|
+
analysis_depth: {
|
|
260
|
+
type: "string",
|
|
261
|
+
enum: ["basic", "detailed", "comprehensive"],
|
|
262
|
+
default: "detailed",
|
|
263
|
+
description: "Depth of analysis to provide"
|
|
264
|
+
},
|
|
265
|
+
include_recommendations: {
|
|
266
|
+
type: "boolean",
|
|
267
|
+
default: true,
|
|
268
|
+
description: "Include optimization recommendations"
|
|
88
269
|
}
|
|
89
270
|
}
|
|
90
271
|
}
|
|
91
|
-
|
|
92
|
-
}
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Add AG-UI tools if enabled
|
|
276
|
+
if (this.aguiFeatures) {
|
|
277
|
+
baseTools.push({
|
|
278
|
+
name: "get_real_time_status",
|
|
279
|
+
description: "⚡ Get real-time optimization status, AG-UI capabilities, and streaming optimization availability",
|
|
280
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false }
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
return { tools: baseTools };
|
|
93
285
|
});
|
|
94
286
|
|
|
95
287
|
this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
@@ -99,6 +291,12 @@ class MCPPromptOptimizer {
|
|
|
99
291
|
case "optimize_prompt": return await this.handleOptimizePrompt(args);
|
|
100
292
|
case "get_quota_status": return await this.handleGetQuotaStatus();
|
|
101
293
|
case "search_templates": return await this.handleSearchTemplates(args);
|
|
294
|
+
case "detect_ai_context": return await this.handleDetectAIContext(args);
|
|
295
|
+
case "create_template": return await this.handleCreateTemplate(args);
|
|
296
|
+
case "get_template": return await this.handleGetTemplate(args);
|
|
297
|
+
case "update_template": return await this.handleUpdateTemplate(args);
|
|
298
|
+
case "get_optimization_insights": return await this.handleGetOptimizationInsights(args);
|
|
299
|
+
case "get_real_time_status": return await this.handleGetRealTimeStatus();
|
|
102
300
|
default: throw new Error(`Unknown tool: ${name}`);
|
|
103
301
|
}
|
|
104
302
|
} catch (error) {
|
|
@@ -107,62 +305,9 @@ class MCPPromptOptimizer {
|
|
|
107
305
|
});
|
|
108
306
|
}
|
|
109
307
|
|
|
110
|
-
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
// Image generation (highest priority - most specific)
|
|
114
|
-
if (/--ar|--v|midjourney|dall-e|photorealistic|render|3d\s+model/i.test(p)) {
|
|
115
|
-
return 'image_generation';
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
// LLM interaction (specific role-playing patterns)
|
|
119
|
-
if (/act as|you are a|role:|persona:|pretend to be/i.test(p)) {
|
|
120
|
-
return 'llm_interaction';
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
// Technical automation (scripts and execution) - check before code_generation
|
|
124
|
-
if (/def\s+\w+\s*\(.*\):/i.test(p) || /execute|script|automation|deploy|run\s+command|bash|shell/i.test(p)) {
|
|
125
|
-
return 'technical_automation';
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
// Structured output (data formats) - check before code_generation
|
|
129
|
-
if (/return.*as\s+(json|xml|yaml)|format.*as\s+(json|xml|yaml)|output.*as\s+(json|xml|yaml)|structured.*data/i.test(p)) {
|
|
130
|
-
return 'structured_output';
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// Code generation (refined to be more specific)
|
|
134
|
-
if (/\b(write|create|build|make|generate)\b.*\b(function|method|class|script|program|code|algorithm|hello world)\b/i.test(p) ||
|
|
135
|
-
/hello\s+world\s+(function|program|script|code)/i.test(p) ||
|
|
136
|
-
/function\s*\(|class\s+\w+|interface\s+\w+|public\s+class|private\s+\w+/i.test(p)) {
|
|
137
|
-
return 'code_generation';
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// API automation (web services)
|
|
141
|
-
if (/api|endpoint|get\s+request|post\s+request|put\s+request|delete\s+request|rest\s+api|graphql/i.test(p)) {
|
|
142
|
-
return 'api_automation';
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// Default to human communication
|
|
146
|
-
return 'human_communication';
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
enhanceGoalsForContext(originalGoals, aiContext) {
|
|
150
|
-
const goals = new Set(originalGoals);
|
|
151
|
-
const contextGoals = {
|
|
152
|
-
image_generation: ['keyword_density', 'parameter_preservation', 'technical_accuracy'],
|
|
153
|
-
llm_interaction: ['context_specificity', 'token_efficiency', 'actionability'],
|
|
154
|
-
technical_automation: ['technical_accuracy', 'parameter_preservation', 'specificity'],
|
|
155
|
-
code_generation: ['syntax_clarity', 'best_practices', 'maintainability'],
|
|
156
|
-
structured_output: ['format_compliance', 'data_validation', 'schema_adherence'],
|
|
157
|
-
api_automation: ['endpoint_clarity', 'parameter_specification', 'error_handling']
|
|
158
|
-
};
|
|
159
|
-
(contextGoals[aiContext] || ['clarity', 'actionability']).forEach(g => goals.add(g));
|
|
160
|
-
return Array.from(goals);
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
generateMockOptimization(prompt, goals, aiContext) {
|
|
164
|
-
const optimized_prompt = `Optimized for ${aiContext}: ${prompt}`;
|
|
165
|
-
return {
|
|
308
|
+
generateMockOptimization(prompt, goals, aiContext, enableBayesian = false) {
|
|
309
|
+
const optimized_prompt = `Enhanced for ${aiContext}: ${prompt}`;
|
|
310
|
+
const baseResult = {
|
|
166
311
|
optimized_prompt,
|
|
167
312
|
confidence_score: 0.87,
|
|
168
313
|
tier: 'explorer',
|
|
@@ -171,33 +316,140 @@ class MCPPromptOptimizer {
|
|
|
171
316
|
template_id: 'test-template-123',
|
|
172
317
|
templates_found: [{ title: 'Similar Template 1', confidence_score: 0.85, id: 'tmpl-1' }],
|
|
173
318
|
optimization_insights: {
|
|
174
|
-
improvement_metrics: {
|
|
175
|
-
|
|
176
|
-
|
|
319
|
+
improvement_metrics: {
|
|
320
|
+
clarity_improvement: 0.25,
|
|
321
|
+
specificity_improvement: 0.20,
|
|
322
|
+
length_optimization: 0.15,
|
|
323
|
+
context_alignment: 0.30
|
|
324
|
+
},
|
|
325
|
+
user_patterns: {
|
|
326
|
+
optimization_confidence: '87.0%',
|
|
327
|
+
prompt_complexity: 'intermediate',
|
|
328
|
+
ai_context: aiContext
|
|
329
|
+
},
|
|
330
|
+
recommendations: [
|
|
331
|
+
`Context detected as ${aiContext}`,
|
|
332
|
+
'Enhanced goal optimization applied',
|
|
333
|
+
'Template auto-save threshold met'
|
|
334
|
+
]
|
|
177
335
|
}
|
|
178
336
|
};
|
|
337
|
+
|
|
338
|
+
// Add Bayesian optimization insights if enabled
|
|
339
|
+
if (enableBayesian && this.bayesianOptimizationEnabled) {
|
|
340
|
+
baseResult.bayesian_insights = {
|
|
341
|
+
parameter_optimization: {
|
|
342
|
+
temperature_adjustment: '+0.1',
|
|
343
|
+
context_weight: '+0.15',
|
|
344
|
+
goal_prioritization: 'clarity > specificity > engagement'
|
|
345
|
+
},
|
|
346
|
+
performance_prediction: {
|
|
347
|
+
expected_improvement: '12-18%',
|
|
348
|
+
confidence_interval: '85-95%',
|
|
349
|
+
optimization_strategy: 'gradient_boost_context'
|
|
350
|
+
},
|
|
351
|
+
next_optimization_recommendation: {
|
|
352
|
+
suggested_goals: ['analytical_depth', 'creative_enhancement'],
|
|
353
|
+
estimated_improvement: '8-12%'
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
return baseResult;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
generateMockContextDetection(prompt) {
|
|
362
|
+
let primary_context = 'human_communication'; // Default context
|
|
363
|
+
const lc = prompt.toLowerCase(); // one‑off lower‑case copy
|
|
364
|
+
|
|
365
|
+
/* 1️⃣ Code / programming – now includes `def` / `return`. */
|
|
366
|
+
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)) {
|
|
367
|
+
primary_context = 'code_generation';
|
|
368
|
+
|
|
369
|
+
/* 2️⃣ Image / art – unchanged. */
|
|
370
|
+
} else if (lc.match(/image|generate|dall-e|midjourney/i)) {
|
|
371
|
+
primary_context = 'image_generation';
|
|
372
|
+
|
|
373
|
+
/* 3️⃣ Automation – unchanged. */
|
|
374
|
+
} else if (lc.match(/automate|script|api/i)) {
|
|
375
|
+
primary_context = 'technical_automation';
|
|
376
|
+
|
|
377
|
+
/* 4️⃣ LLM / analysis – newly added keyword “analyze”. */
|
|
378
|
+
} else if (lc.match(/analyze|explain|evaluate|summary|research|paper|analysis|interpret|discussion|assessment|compare|contrast/i)) {
|
|
379
|
+
primary_context = 'llm_interaction';
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
return {
|
|
383
|
+
primary_context: primary_context,
|
|
384
|
+
confidence: 0.75,
|
|
385
|
+
secondary_contexts: ['llm_interaction'],
|
|
386
|
+
detected_parameters: [],
|
|
387
|
+
mock_mode: true,
|
|
388
|
+
reason: 'Running in development/fallback mode.'
|
|
389
|
+
};
|
|
179
390
|
}
|
|
180
391
|
|
|
181
392
|
async handleOptimizePrompt(args) {
|
|
182
393
|
if (!args.prompt) throw new Error('Prompt is required');
|
|
183
|
-
|
|
184
|
-
const enhancedGoals = this.enhanceGoalsForContext(args.goals || ['clarity'], detectedContext);
|
|
394
|
+
|
|
185
395
|
const manager = new CloudApiKeyManager(this.apiKey, { developmentMode: this.developmentMode });
|
|
396
|
+
|
|
186
397
|
try {
|
|
187
398
|
const validation = await manager.validateApiKey();
|
|
399
|
+
|
|
188
400
|
if (validation.mock_mode || this.developmentMode) {
|
|
189
|
-
|
|
190
|
-
const
|
|
401
|
+
// In mock/dev mode, we still need a context for mock generation
|
|
402
|
+
const mockContext = args.ai_context || 'human_communication';
|
|
403
|
+
const mockGoals = args.goals || ['clarity'];
|
|
404
|
+
const mockEnableBayesian = args.enable_bayesian !== false && this.bayesianOptimizationEnabled;
|
|
405
|
+
const mockResult = this.generateMockOptimization(args.prompt, mockGoals, mockContext, mockEnableBayesian);
|
|
406
|
+
const formatted = this.formatOptimizationResult(mockResult, { detectedContext: mockContext, enableBayesian: mockEnableBayesian });
|
|
191
407
|
return { content: [{ type: "text", text: formatted }] };
|
|
192
408
|
}
|
|
193
|
-
|
|
194
|
-
|
|
409
|
+
|
|
410
|
+
// 1. Detect AI Context from backend
|
|
411
|
+
let detectedContext = args.ai_context;
|
|
412
|
+
if (!detectedContext) {
|
|
413
|
+
try {
|
|
414
|
+
const contextDetectionResult = await this.callBackendAPI(ENDPOINTS.DETECT_CONTEXT, { prompt: args.prompt });
|
|
415
|
+
detectedContext = contextDetectionResult.primary_context;
|
|
416
|
+
console.error(`Detected AI Context from backend: ${detectedContext}`);
|
|
417
|
+
} catch (contextError) {
|
|
418
|
+
console.error(`Failed to detect AI context from backend, falling back to default: ${contextError.message}`);
|
|
419
|
+
detectedContext = 'human_communication'; // Fallback
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// 2. Call the main optimization endpoint
|
|
424
|
+
const enableBayesian = args.enable_bayesian !== false && this.bayesianOptimizationEnabled;
|
|
425
|
+
const optimizationPayload = {
|
|
426
|
+
prompt: args.prompt,
|
|
427
|
+
goals: args.goals || ['clarity'], // Pass original goals, backend will enhance
|
|
428
|
+
context: {
|
|
429
|
+
ai_context: detectedContext
|
|
430
|
+
},
|
|
431
|
+
enable_bayesian: enableBayesian,
|
|
432
|
+
metadata: {
|
|
433
|
+
mcp_version: packageJson.version,
|
|
434
|
+
feature_flags: {
|
|
435
|
+
bayesian_optimization: this.bayesianOptimizationEnabled,
|
|
436
|
+
agui_features: this.aguiFeatures
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
|
|
441
|
+
const result = await this.callBackendAPI(ENDPOINTS.OPTIMIZE, optimizationPayload);
|
|
442
|
+
|
|
443
|
+
return { content: [{ type: "text", text: this.formatOptimizationResult(result, { detectedContext, enableBayesian }) }] };
|
|
444
|
+
|
|
195
445
|
} catch (error) {
|
|
196
|
-
if (error.message.includes('Network') || error.message.includes('DNS') || error.message.includes('timeout')) {
|
|
197
|
-
const
|
|
446
|
+
if (error.message.includes('Network') || error.message.includes('DNS') || error.message.includes('timeout') || error.message.includes('Connection')) {
|
|
447
|
+
const fallbackContext = args.ai_context || 'human_communication';
|
|
448
|
+
const fallbackEnableBayesian = args.enable_bayesian !== false && this.bayesianOptimizationEnabled;
|
|
449
|
+
const fallbackResult = this.generateMockOptimization(args.prompt, args.goals || ['clarity'], fallbackContext, fallbackEnableBayesian);
|
|
198
450
|
fallbackResult.fallback_mode = true;
|
|
199
451
|
fallbackResult.error_reason = error.message;
|
|
200
|
-
const formatted = this.formatOptimizationResult(fallbackResult, { detectedContext });
|
|
452
|
+
const formatted = this.formatOptimizationResult(fallbackResult, { detectedContext: fallbackContext, enableBayesian: fallbackEnableBayesian });
|
|
201
453
|
return { content: [{ type: "text", text: formatted }] };
|
|
202
454
|
}
|
|
203
455
|
throw new Error(`Optimization failed: ${error.message}`);
|
|
@@ -205,53 +457,230 @@ class MCPPromptOptimizer {
|
|
|
205
457
|
}
|
|
206
458
|
|
|
207
459
|
async handleGetQuotaStatus() {
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
460
|
+
const manager = new CloudApiKeyManager(this.apiKey, { developmentMode: this.developmentMode });
|
|
461
|
+
const info = await manager.getApiKeyInfo();
|
|
462
|
+
return { content: [{ type: "text", text: this.formatQuotaStatus(info) }] };
|
|
211
463
|
}
|
|
212
464
|
|
|
213
465
|
async handleSearchTemplates(args) {
|
|
214
466
|
try {
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
467
|
+
const params = new URLSearchParams({
|
|
468
|
+
page: '1',
|
|
469
|
+
per_page: Math.min(args.limit || 5, 20).toString(),
|
|
470
|
+
sort_by: args.sort_by || 'confidence_score',
|
|
471
|
+
sort_order: args.sort_order || 'desc'
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
if (args.query) params.append('query', args.query);
|
|
475
|
+
if (args.ai_context) params.append('ai_context', args.ai_context);
|
|
476
|
+
if (args.sophistication_level) params.append('sophistication_level', args.sophistication_level);
|
|
477
|
+
if (args.complexity_level) params.append('complexity_level', args.complexity_level);
|
|
478
|
+
if (args.optimization_strategy) params.append('optimization_strategy', args.optimization_strategy);
|
|
479
|
+
|
|
480
|
+
const endpoint = `${ENDPOINTS.SEARCH_TEMPLATES}?${params.toString()}`;
|
|
481
|
+
const result = await this.callBackendAPI(endpoint, null, 'GET');
|
|
482
|
+
|
|
483
|
+
const searchResult = {
|
|
484
|
+
templates: result.templates || [],
|
|
485
|
+
total: result.total || 0,
|
|
486
|
+
query: args.query,
|
|
487
|
+
ai_context: args.ai_context,
|
|
488
|
+
sophistication_level: args.sophistication_level,
|
|
489
|
+
complexity_level: args.complexity_level
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
const formatted = this.formatTemplateSearchResults(searchResult, args);
|
|
493
|
+
return { content: [{ type: "text", text: formatted }] };
|
|
494
|
+
|
|
495
|
+
} catch (error) {
|
|
496
|
+
console.error(`Template search failed: ${error.message}`);
|
|
497
|
+
const fallbackResult = {
|
|
498
|
+
templates: [],
|
|
499
|
+
total: 0,
|
|
500
|
+
message: "Template search is temporarily unavailable.",
|
|
501
|
+
error: error.message,
|
|
502
|
+
fallback_mode: true
|
|
503
|
+
};
|
|
504
|
+
const formatted = this.formatTemplateSearchResults(fallbackResult, args);
|
|
505
|
+
return { content: [{ type: "text", text: formatted }] };
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
async handleGetOptimizationInsights(args) {
|
|
510
|
+
if (!this.bayesianOptimizationEnabled) {
|
|
511
|
+
return { content: [{ type: "text", text: "🧠 Bayesian optimization features are not enabled. Set ENABLE_BAYESIAN_OPTIMIZATION=true to access advanced insights." }] };
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
try {
|
|
515
|
+
// Try to get insights from backend
|
|
516
|
+
const endpoint = `${ENDPOINTS.ANALYTICS_BAYESIAN_INSIGHTS}?depth=${args.analysis_depth || 'detailed'}&recommendations=${args.include_recommendations !== false}`;
|
|
517
|
+
const result = await this.callBackendAPI(endpoint, null, 'GET');
|
|
518
|
+
|
|
519
|
+
return { content: [{ type: "text", text: this.formatOptimizationInsights(result) }] };
|
|
520
|
+
|
|
521
|
+
} catch (error) {
|
|
522
|
+
// Fallback to mock insights
|
|
523
|
+
const mockInsights = {
|
|
524
|
+
bayesian_status: {
|
|
525
|
+
optimization_active: true,
|
|
526
|
+
total_optimizations: 47,
|
|
527
|
+
improvement_rate: '23.5%',
|
|
528
|
+
confidence_score: 0.89
|
|
529
|
+
},
|
|
530
|
+
parameter_insights: {
|
|
531
|
+
most_effective_goals: ['clarity', 'technical_accuracy', 'analytical_depth'],
|
|
532
|
+
context_performance: {
|
|
533
|
+
'code_generation': 0.92,
|
|
534
|
+
'llm_interaction': 0.87,
|
|
535
|
+
'technical_automation': 0.84
|
|
536
|
+
},
|
|
537
|
+
optimization_trends: 'Steady improvement in technical contexts'
|
|
538
|
+
},
|
|
539
|
+
recommendations: args.include_recommendations !== false ? [
|
|
540
|
+
'Focus on technical_accuracy for code generation prompts',
|
|
541
|
+
'Combine clarity with analytical_depth for best results',
|
|
542
|
+
'Consider using structured_output context for data tasks'
|
|
543
|
+
] : []
|
|
544
|
+
};
|
|
545
|
+
|
|
546
|
+
return { content: [{ type: "text", text: this.formatOptimizationInsights(mockInsights) }] };
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
async handleGetRealTimeStatus() {
|
|
551
|
+
if (!this.aguiFeatures) {
|
|
552
|
+
return { content: [{ type: "text", text: "⚡ AG-UI real-time features are not enabled. Set ENABLE_AGUI_FEATURES=true to access real-time optimization capabilities." }] };
|
|
553
|
+
}
|
|
222
554
|
|
|
223
|
-
|
|
224
|
-
|
|
555
|
+
try {
|
|
556
|
+
const result = await this.callBackendAPI(ENDPOINTS.AGUI_STATUS, null, 'GET');
|
|
557
|
+
|
|
558
|
+
return { content: [{ type: "text", text: this.formatRealTimeStatus(result) }] };
|
|
559
|
+
|
|
560
|
+
} catch (error) {
|
|
561
|
+
const mockStatus = {
|
|
562
|
+
agui_status: 'available',
|
|
563
|
+
streaming_optimization: true,
|
|
564
|
+
websocket_support: true,
|
|
565
|
+
real_time_analytics: true,
|
|
566
|
+
active_optimizations: 3,
|
|
567
|
+
average_response_time: '1.2s',
|
|
568
|
+
features: {
|
|
569
|
+
live_optimization: true,
|
|
570
|
+
collaborative_editing: true,
|
|
571
|
+
instant_feedback: true,
|
|
572
|
+
performance_monitoring: true
|
|
225
573
|
}
|
|
574
|
+
};
|
|
575
|
+
|
|
576
|
+
return { content: [{ type: "text", text: this.formatRealTimeStatus(mockStatus) }] };
|
|
577
|
+
}
|
|
578
|
+
}
|
|
226
579
|
|
|
227
|
-
|
|
228
|
-
|
|
580
|
+
async handleDetectAIContext(args) {
|
|
581
|
+
if (!args.prompt) throw new Error('Prompt is required');
|
|
582
|
+
|
|
583
|
+
const formatResult = (result) => {
|
|
584
|
+
let output = `# 🧠 AI Context Detection Result\n\n`;
|
|
585
|
+
output += `**Primary Context:** ${result.primary_context}\n`;
|
|
586
|
+
output += `**Confidence:** ${(result.confidence * 100).toFixed(1)}%\n`;
|
|
587
|
+
if (result.secondary_contexts && result.secondary_contexts.length > 0) {
|
|
588
|
+
output += `**Secondary Contexts:** ${result.secondary_contexts.join(', ')}\n`;
|
|
589
|
+
}
|
|
229
590
|
|
|
230
|
-
const
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
591
|
+
const detections = result.detected_parameters ?? [];
|
|
592
|
+
const safeDetections = detections.filter(d => d && d.name);
|
|
593
|
+
|
|
594
|
+
if (safeDetections.length > 0) {
|
|
595
|
+
output += `**Detected Parameters:** ${safeDetections.map(d => d.name).join(', ')}\n`;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
if (result.mock_mode) {
|
|
599
|
+
output += `\n⚠️ **Fallback Mode Active:** Using mock data due to development mode or network issues.\n`;
|
|
600
|
+
}
|
|
601
|
+
return { content: [{ type: "text", text: output }] };
|
|
602
|
+
};
|
|
603
|
+
|
|
604
|
+
try {
|
|
605
|
+
const manager = new CloudApiKeyManager(this.apiKey, { developmentMode: this.developmentMode });
|
|
606
|
+
const validation = await manager.validateApiKey();
|
|
607
|
+
|
|
608
|
+
if (validation.mock_mode || this.developmentMode) {
|
|
609
|
+
const mockResult = this.generateMockContextDetection(args.prompt);
|
|
610
|
+
return formatResult(mockResult);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
const result = await this.callBackendAPI(ENDPOINTS.DETECT_CONTEXT, { prompt: args.prompt });
|
|
614
|
+
return formatResult(result);
|
|
239
615
|
|
|
240
616
|
} catch (error) {
|
|
241
|
-
|
|
242
|
-
const fallbackResult =
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
617
|
+
// Fallback for ANY error during the process (missing key, network, etc.)
|
|
618
|
+
const fallbackResult = this.generateMockContextDetection(args.prompt);
|
|
619
|
+
return formatResult(fallbackResult);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
async handleCreateTemplate(args) {
|
|
624
|
+
try {
|
|
625
|
+
const result = await this.callBackendAPI(ENDPOINTS.TEMPLATE.CREATE, args);
|
|
626
|
+
let output = `# ✅ Template Created Successfully!\n\n`;
|
|
627
|
+
output += `**Title:** ${result.title}\n`;
|
|
628
|
+
output += `**ID:** \`${result.id}\`\n`;
|
|
629
|
+
output += `**Confidence Score:** ${(result.confidence_score * 100).toFixed(1)}%\n`;
|
|
630
|
+
output += `**AI Context:** ${result.ai_context_detected || 'N/A'}\n`;
|
|
631
|
+
output += `**Public:** ${result.is_public ? 'Yes' : 'No'}\n`;
|
|
632
|
+
output += `\n**Optimized Prompt Preview:**\n\`\`\`\n${result.optimized_prompt.substring(0, 150)}...\n\`\`\`\n`;
|
|
633
|
+
return { content: [{ type: "text", text: output }] };
|
|
634
|
+
} catch (error) {
|
|
635
|
+
throw new Error(`Failed to create template: ${error.message}`);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
async handleGetTemplate(args) {
|
|
640
|
+
if (!args.template_id) throw new Error('Template ID is required');
|
|
641
|
+
try {
|
|
642
|
+
const result = await this.callBackendAPI(ENDPOINTS.TEMPLATE.GET(args.template_id), null, 'GET');
|
|
643
|
+
let output = `# 📄 Template Details\n\n`;
|
|
644
|
+
output += `**Title:** ${result.title}\n`;
|
|
645
|
+
output += `**ID:** \`${result.id}\`\n`;
|
|
646
|
+
output += `**Description:** ${result.description || 'N/A'}\n`;
|
|
647
|
+
output += `**AI Context:** ${result.ai_context_detected || 'N/A'}\n`;
|
|
648
|
+
output += `**Confidence Score:** ${(result.confidence_score * 100).toFixed(1)}%\n`;
|
|
649
|
+
output += `**Public:** ${result.is_public ? 'Yes' : 'No'}\n`;
|
|
650
|
+
output += `**Tags:** ${result.tags ? result.tags.join(', ') : 'None'}\n\n`;
|
|
651
|
+
output += `**Original Prompt:**\n\`\`\`\n${result.original_prompt}\n\`\`\`\n\n`;
|
|
652
|
+
output += `**Optimized Prompt:**\n\`\`\`\n${result.optimized_prompt}\n\`\`\`\n`;
|
|
653
|
+
return { content: [{ type: "text", text: output }] };
|
|
654
|
+
} catch (error) {
|
|
655
|
+
throw new Error(`Failed to retrieve template: ${error.message}`);
|
|
249
656
|
}
|
|
250
657
|
}
|
|
251
658
|
|
|
659
|
+
async handleUpdateTemplate(args) {
|
|
660
|
+
if (!args.template_id) throw new Error('Template ID is required');
|
|
661
|
+
try {
|
|
662
|
+
const { template_id, ...updateData } = args;
|
|
663
|
+
// Filter out undefined values so we only send fields that are being updated
|
|
664
|
+
Object.keys(updateData).forEach(key => updateData[key] === undefined && delete updateData[key]);
|
|
665
|
+
|
|
666
|
+
const result = await this.callBackendAPI(ENDPOINTS.TEMPLATE.UPDATE(template_id), updateData, 'PATCH'); // PATCH is better for partial updates
|
|
667
|
+
let output = `# ✅ Template Updated Successfully!\n\n`;
|
|
668
|
+
output += `**ID:** \`${result.id}\`\n`;
|
|
669
|
+
output += `**Title:** ${result.title}\n\n`;
|
|
670
|
+
output += `Use 'get_template' with the ID to see the full updated template.`;
|
|
671
|
+
return { content: [{ type: "text", text: output }] };
|
|
672
|
+
} catch (error) {
|
|
673
|
+
throw new Error(`Failed to update template: ${error.message}`);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
async _buildUrl(path) {
|
|
678
|
+
return `${this.backendUrl}${path}`;
|
|
679
|
+
}
|
|
680
|
+
|
|
252
681
|
async callBackendAPI(endpoint, data, method = 'POST') {
|
|
253
682
|
return new Promise((resolve, reject) => {
|
|
254
|
-
const url =
|
|
683
|
+
const url = this._buildUrl(endpoint);
|
|
255
684
|
|
|
256
685
|
const options = {
|
|
257
686
|
method: method,
|
|
@@ -313,8 +742,6 @@ class MCPPromptOptimizer {
|
|
|
313
742
|
reject(new Error('Request timeout - backend may be unavailable'));
|
|
314
743
|
});
|
|
315
744
|
|
|
316
|
-
req.setTimeout(this.requestTimeout);
|
|
317
|
-
|
|
318
745
|
if (method !== 'GET' && data) {
|
|
319
746
|
req.write(JSON.stringify(data));
|
|
320
747
|
}
|
|
@@ -326,38 +753,250 @@ class MCPPromptOptimizer {
|
|
|
326
753
|
let output = `# 🎯 Optimized Prompt\n\n${result.optimized_prompt}\n\n`;
|
|
327
754
|
output += `**Confidence:** ${(result.confidence_score * 100).toFixed(1)}%\n`;
|
|
328
755
|
output += `**AI Context:** ${context.detectedContext}\n`;
|
|
329
|
-
|
|
330
|
-
if (result.
|
|
756
|
+
|
|
757
|
+
if (result.template_saved) {
|
|
758
|
+
output += `\n📁 **Template Auto-Save**\n✅ Automatically saved as template (ID: \`${result.template_id}\`)\n*Confidence threshold: >70% required for auto-save*\n`;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
if (result.templates_found?.length) {
|
|
762
|
+
output += `\n📋 **Similar Templates Found**\nFound **${result.templates_found.length}** similar template(s):\n`;
|
|
763
|
+
result.templates_found.slice(0, 3).forEach(t => {
|
|
764
|
+
output += `- ${t.title} (${(t.confidence_score * 100).toFixed(1)}% match)\n`;
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
|
|
331
768
|
if (result.optimization_insights) {
|
|
332
769
|
const metrics = result.optimization_insights.improvement_metrics;
|
|
333
|
-
|
|
334
|
-
|
|
770
|
+
if (metrics) {
|
|
771
|
+
output += `\n📊 **Optimization Insights**\n`;
|
|
772
|
+
if (metrics.clarity_improvement) output += `- Clarity: +${(metrics.clarity_improvement * 100).toFixed(1)}%\n`;
|
|
773
|
+
if (metrics.specificity_improvement) output += `- Specificity: +${(metrics.specificity_improvement * 100).toFixed(1)}%\n`;
|
|
774
|
+
if (metrics.context_alignment) output += `- Context Alignment: +${(metrics.context_alignment * 100).toFixed(1)}%\n`;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
if (result.optimization_insights.recommendations?.length) {
|
|
778
|
+
output += `\n💡 **Recommendations:**\n`;
|
|
779
|
+
result.optimization_insights.recommendations.forEach(rec => {
|
|
780
|
+
output += `- ${rec}\n`;
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// Add Bayesian insights if available
|
|
786
|
+
if (result.bayesian_insights && context.enableBayesian) {
|
|
787
|
+
output += `\n🧠 **Bayesian Optimization Insights**\n`;
|
|
788
|
+
const bayesian = result.bayesian_insights;
|
|
789
|
+
|
|
790
|
+
if (bayesian.parameter_optimization) {
|
|
791
|
+
output += `**Parameter Tuning:**\n`;
|
|
792
|
+
if (bayesian.parameter_optimization.temperature_adjustment) {
|
|
793
|
+
output += `- Temperature: ${bayesian.parameter_optimization.temperature_adjustment}\n`;
|
|
794
|
+
}
|
|
795
|
+
if (bayesian.parameter_optimization.goal_prioritization) {
|
|
796
|
+
output += `- Goal Priority: ${bayesian.parameter_optimization.goal_prioritization}\n`;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
if (bayesian.performance_prediction) {
|
|
801
|
+
output += `**Performance Prediction:**\n`;
|
|
802
|
+
output += `- Expected Improvement: ${bayesian.performance_prediction.expected_improvement}\n`;
|
|
803
|
+
output += `- Confidence Interval: ${bayesian.performance_prediction.confidence_interval}\n`;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
if (bayesian.next_optimization_recommendation) {
|
|
807
|
+
output += `**Next Optimization:**\n`;
|
|
808
|
+
output += `- Suggested Goals: ${bayesian.next_optimization_recommendation.suggested_goals.join(', ')}\n`;
|
|
809
|
+
output += `- Estimated Improvement: ${bayesian.next_optimization_recommendation.estimated_improvement}\n`;
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
if (result.fallback_mode) {
|
|
814
|
+
output += `\n⚠️ **Fallback Mode Active**\n**Issue:** ${result.error_reason}\n`;
|
|
335
815
|
}
|
|
336
|
-
|
|
337
|
-
output += `\n🔗 Quick Actions
|
|
816
|
+
|
|
817
|
+
output += `\n🔗 **Quick Actions**\n- Dashboard: https://promptoptimizer-blog.vercel.app/dashboard\n- Analytics: https://promptoptimizer-blog.vercel.app/analytics\n`;
|
|
818
|
+
|
|
338
819
|
return output;
|
|
339
820
|
}
|
|
340
|
-
|
|
821
|
+
|
|
341
822
|
formatQuotaStatus(result) {
|
|
342
|
-
let output = `# 📊
|
|
823
|
+
let output = `# 📊 Account Status\n\n**Plan:** ${result.tier || 'explorer'}\n`;
|
|
824
|
+
|
|
343
825
|
const quota = result.quota || {};
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
826
|
+
if (quota.unlimited) {
|
|
827
|
+
output += `**Usage:** 🟢 Unlimited\n`;
|
|
828
|
+
} else {
|
|
829
|
+
const used = quota.used || 0;
|
|
830
|
+
const limit = quota.limit || 5000;
|
|
831
|
+
const percentage = limit > 0 ? ((used / limit) * 100).toFixed(1) : 0;
|
|
832
|
+
|
|
833
|
+
let statusIcon = '🟢';
|
|
834
|
+
if (percentage >= 90) statusIcon = '🔴';
|
|
835
|
+
else if (percentage >= 75) statusIcon = '🟡';
|
|
836
|
+
|
|
837
|
+
output += `**Usage:** ${statusIcon} ${used}/${limit} (${percentage}%)\n`;
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
output += `\n## ✨ **Available Features**\n`;
|
|
841
|
+
if (result.features) {
|
|
842
|
+
if (result.features.optimization) output += `✅ Prompt Optimization\n`;
|
|
843
|
+
if (result.features.template_search) output += `✅ Template Search & Management\n`;
|
|
844
|
+
if (result.features.template_auto_save) output += `✅ Template Auto-Save\n`;
|
|
845
|
+
if (result.features.optimization_insights) output += `✅ Optimization Insights\n`;
|
|
846
|
+
if (this.bayesianOptimizationEnabled) output += `🧠 Bayesian Optimization\n`;
|
|
847
|
+
if (this.aguiFeatures) output += `⚡ AG-UI Real-time Features\n`;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
if (result.mode) {
|
|
851
|
+
output += `\n## 🔧 **Mode Status**\n`;
|
|
852
|
+
if (result.mode.development) output += `⚙️ Development Mode\n`;
|
|
853
|
+
if (result.mode.mock) output += `🎭 Mock Mode\n`;
|
|
854
|
+
if (result.mode.fallback) output += `🔄 Fallback Mode\n`;
|
|
855
|
+
if (result.mode.offline) output += `📱 Offline Mode\n`;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
output += `\n## 🔗 **Account Management**\n`;
|
|
859
|
+
output += `- Dashboard: https://promptoptimizer-blog.vercel.app/dashboard\n`;
|
|
860
|
+
output += `- Analytics: https://promptoptimizer-blog.vercel.app/analytics\n`;
|
|
861
|
+
output += `- Upgrade: https://promptoptimizer-blog.vercel.app/pricing\n`;
|
|
862
|
+
|
|
347
863
|
return output;
|
|
348
864
|
}
|
|
349
865
|
|
|
350
866
|
formatTemplateSearchResults(result, originalArgs) {
|
|
351
|
-
let output = `# 🔍 Template Search Results\n\
|
|
867
|
+
let output = `# 🔍 Template Search Results\n\n`;
|
|
868
|
+
|
|
869
|
+
if (originalArgs.query || originalArgs.ai_context || originalArgs.sophistication_level) {
|
|
870
|
+
output += `**Search Criteria:**\n`;
|
|
871
|
+
if (originalArgs.query) output += `- Query: "${originalArgs.query}"\n`;
|
|
872
|
+
if (originalArgs.ai_context) output += `- AI Context: ${originalArgs.ai_context}\n`;
|
|
873
|
+
if (originalArgs.sophistication_level) output += `- Sophistication: ${originalArgs.sophistication_level}\n`;
|
|
874
|
+
if (originalArgs.complexity_level) output += `- Complexity: ${originalArgs.complexity_level}\n`;
|
|
875
|
+
output += `\n`;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
output += `Found **${result.total}** template(s)\n\n`;
|
|
879
|
+
|
|
352
880
|
if (!result.templates || result.templates.length === 0) {
|
|
353
|
-
output += `📭 No Templates Found
|
|
881
|
+
output += `📭 **No Templates Found**\n`;
|
|
882
|
+
if (originalArgs.query) {
|
|
883
|
+
output += `Try searching with different keywords or remove filters.\n`;
|
|
884
|
+
} else {
|
|
885
|
+
output += `You don't have any saved templates yet. Templates are automatically saved when optimization confidence is >70%.\n`;
|
|
886
|
+
}
|
|
354
887
|
} else {
|
|
355
|
-
output += `## 📋 Template Results
|
|
356
|
-
result.templates.forEach(t => {
|
|
357
|
-
|
|
888
|
+
output += `## 📋 **Template Results**\n`;
|
|
889
|
+
result.templates.forEach((t, index) => {
|
|
890
|
+
const confidence = t.confidence_score ? `${(t.confidence_score * 100).toFixed(1)}%` : 'N/A';
|
|
891
|
+
const preview = t.optimized_prompt ? t.optimized_prompt.substring(0, 60) + '...' : 'Preview unavailable';
|
|
892
|
+
|
|
893
|
+
output += `### ${index + 1}. ${t.title}\n`;
|
|
894
|
+
output += `- **Confidence:** ${confidence}\n`;
|
|
895
|
+
output += `- **ID:** \`${t.id}\`\n`;
|
|
896
|
+
output += `- **Preview:** ${preview}\n`;
|
|
897
|
+
if (t.ai_context) output += `- **Context:** ${t.ai_context}\n`;
|
|
898
|
+
if (t.optimization_goals && t.optimization_goals.length) {
|
|
899
|
+
output += `- **Goals:** ${t.optimization_goals.join(', ')}\n`;
|
|
900
|
+
}
|
|
901
|
+
output += `\n`;
|
|
902
|
+
});
|
|
903
|
+
|
|
904
|
+
output += `## 💡 **Template Usage Guide**\n`;
|
|
905
|
+
output += `- Copy prompts for immediate use\n`;
|
|
906
|
+
output += `- Use template IDs to reference specific templates\n`;
|
|
907
|
+
output += `- High-confidence templates (>80%) are most reliable\n`;
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
if (result.fallback_mode) {
|
|
911
|
+
output += `\n⚠️ **Search Temporarily Unavailable**\n${result.message}\n`;
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
return output;
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
formatOptimizationInsights(insights) {
|
|
918
|
+
let output = `# 🧠 Bayesian Optimization Insights\n\n`;
|
|
919
|
+
|
|
920
|
+
if (insights.bayesian_status) {
|
|
921
|
+
const status = insights.bayesian_status;
|
|
922
|
+
output += `## 📊 **Status Overview**\n`;
|
|
923
|
+
output += `- **Status:** ${status.optimization_active ? '🟢 Active' : '🔴 Inactive'}\n`;
|
|
924
|
+
output += `- **Total Optimizations:** ${status.total_optimizations}\n`;
|
|
925
|
+
output += `- **Improvement Rate:** ${status.improvement_rate}\n`;
|
|
926
|
+
output += `- **System Confidence:** ${(status.confidence_score * 100).toFixed(1)}%\n\n`;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
if (insights.parameter_insights) {
|
|
930
|
+
const params = insights.parameter_insights;
|
|
931
|
+
output += `## 🎯 **Parameter Analysis**\n`;
|
|
932
|
+
|
|
933
|
+
if (params.most_effective_goals) {
|
|
934
|
+
output += `**Most Effective Goals:**\n`;
|
|
935
|
+
params.most_effective_goals.forEach(goal => {
|
|
936
|
+
output += `- ${goal}\n`;
|
|
937
|
+
});
|
|
938
|
+
output += `\n`;
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
if (params.context_performance) {
|
|
942
|
+
output += `**Context Performance:**\n`;
|
|
943
|
+
Object.entries(params.context_performance).forEach(([context, score]) => {
|
|
944
|
+
const percentage = (score * 100).toFixed(1);
|
|
945
|
+
const icon = score >= 0.9 ? '🟢' : score >= 0.8 ? '🟡' : '🔴';
|
|
946
|
+
output += `- ${context}: ${icon} ${percentage}%\n`;
|
|
947
|
+
});
|
|
948
|
+
output += `\n`;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
if (params.optimization_trends) {
|
|
952
|
+
output += `**Trends:** ${params.optimization_trends}\n\n`;
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
if (insights.recommendations && insights.recommendations.length) {
|
|
957
|
+
output += `## 💡 **Optimization Recommendations**\n`;
|
|
958
|
+
insights.recommendations.forEach((rec, index) => {
|
|
959
|
+
output += `${index + 1}. ${rec}\n`;
|
|
358
960
|
});
|
|
359
|
-
output +=
|
|
961
|
+
output += `\n`;
|
|
360
962
|
}
|
|
963
|
+
|
|
964
|
+
output += `## 🔗 **Advanced Analytics**\n`;
|
|
965
|
+
output += `- Full Analytics: https://promptoptimizer-blog.vercel.app/analytics\n`;
|
|
966
|
+
output += `- Performance Dashboard: https://promptoptimizer-blog.vercel.app/dashboard\n`;
|
|
967
|
+
|
|
968
|
+
return output;
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
formatRealTimeStatus(status) {
|
|
972
|
+
let output = `# ⚡ AG-UI Real-Time Status\n\n`;
|
|
973
|
+
|
|
974
|
+
output += `## 🚀 **Service Status**\n`;
|
|
975
|
+
output += `- **AG-UI Status:** ${status.agui_status === 'available' ? '🟢 Available' : '🔴 Unavailable'}\n`;
|
|
976
|
+
output += `- **Streaming Optimization:** ${status.streaming_optimization ? '✅ Enabled' : '❌ Disabled'}\n`;
|
|
977
|
+
output += `- **WebSocket Support:** ${status.websocket_support ? '✅ Enabled' : '❌ Disabled'}\n`;
|
|
978
|
+
output += `- **Real-time Analytics:** ${status.real_time_analytics ? '✅ Enabled' : '❌ Disabled'}\n\n`;
|
|
979
|
+
|
|
980
|
+
if (status.active_optimizations !== undefined) {
|
|
981
|
+
output += `## 📈 **Current Activity**\n`;
|
|
982
|
+
output += `- **Active Optimizations:** ${status.active_optimizations}\n`;
|
|
983
|
+
output += `- **Average Response Time:** ${status.average_response_time}\n\n`;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
if (status.features) {
|
|
987
|
+
const features = status.features;
|
|
988
|
+
output += `## ⚡ **Available Features**\n`;
|
|
989
|
+
if (features.live_optimization) output += `✅ Live Optimization\n`;
|
|
990
|
+
if (features.collaborative_editing) output += `✅ Collaborative Editing\n`;
|
|
991
|
+
if (features.instant_feedback) output += `✅ Instant Feedback\n`;
|
|
992
|
+
if (features.performance_monitoring) output += `✅ Performance Monitoring\n`;
|
|
993
|
+
output += `\n`;
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
output += `## 🔗 **Real-Time Access**\n`;
|
|
997
|
+
output += `- Live Dashboard: https://promptoptimizer-blog.vercel.app/live\n`;
|
|
998
|
+
output += `- WebSocket Endpoint: Available via API\n`;
|
|
999
|
+
|
|
361
1000
|
return output;
|
|
362
1001
|
}
|
|
363
1002
|
|
|
@@ -368,25 +1007,42 @@ class MCPPromptOptimizer {
|
|
|
368
1007
|
}
|
|
369
1008
|
|
|
370
1009
|
async function startValidatedMCPServer() {
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
const validation = await manager.validateAndPrepare();
|
|
381
|
-
console.error('🔧 Starting MCP server...\n');
|
|
382
|
-
const mcpServer = new MCPPromptOptimizer();
|
|
383
|
-
console.error('✅ MCP server ready for connections');
|
|
384
|
-
console.error(`📊 Plan: ${validation.tier} | Quota: ${validation.quotaStatus.unlimited ? 'Unlimited' : `${validation.quotaStatus.remaining}/${validation.quotaStatus.limit} remaining`}`);
|
|
385
|
-
await mcpServer.run();
|
|
386
|
-
} catch (error) {
|
|
387
|
-
console.error(`❌ Failed to start MCP server: ${error.message}`);
|
|
388
|
-
process.exit(1);
|
|
1010
|
+
console.log(`🚀 MCP Prompt Optimizer - Professional Cloud Server v${packageJson.version}\n`);
|
|
1011
|
+
console.log(`🧠 Bayesian Optimization: ${process.env.ENABLE_BAYESIAN_OPTIMIZATION === 'true' ? 'Enabled' : 'Disabled'}`);
|
|
1012
|
+
console.log(`⚡ AG-UI Features: ${process.env.ENABLE_AGUI_FEATURES === 'true' ? 'Enabled' : 'Disabled'}\n`);
|
|
1013
|
+
|
|
1014
|
+
try {
|
|
1015
|
+
const apiKey = process.env.OPTIMIZER_API_KEY;
|
|
1016
|
+
if (!apiKey) {
|
|
1017
|
+
console.error('❌ API key required. Get one at https://promptoptimizer-blog.vercel.app/pricing');
|
|
1018
|
+
process.exit(1);
|
|
389
1019
|
}
|
|
1020
|
+
|
|
1021
|
+
const manager = new CloudApiKeyManager(apiKey, { developmentMode: process.env.OPTIMIZER_DEV_MODE === 'true' });
|
|
1022
|
+
console.log('🔧 Validating API key...\n');
|
|
1023
|
+
const validation = await manager.validateAndPrepare();
|
|
1024
|
+
|
|
1025
|
+
console.log('🔧 Starting MCP server...\n');
|
|
1026
|
+
const mcpServer = new MCPPromptOptimizer();
|
|
1027
|
+
console.log('✅ MCP server ready for connections');
|
|
1028
|
+
|
|
1029
|
+
// Enhanced status display
|
|
1030
|
+
const quotaDisplay = validation.quotaStatus.unlimited ?
|
|
1031
|
+
'Unlimited' :
|
|
1032
|
+
`${validation.quotaStatus.remaining}/${validation.quotaStatus.limit} remaining`;
|
|
1033
|
+
|
|
1034
|
+
console.log(`📊 Plan: ${validation.tier} | Quota: ${quotaDisplay}`);
|
|
1035
|
+
|
|
1036
|
+
if (validation.mode.mock) console.log('🎭 Running in mock mode');
|
|
1037
|
+
if (validation.mode.development) console.log('⚙️ Development mode active');
|
|
1038
|
+
if (validation.mode.fallback) console.log('🔄 Fallback mode active');
|
|
1039
|
+
if (validation.mode.offline) console.log('📱 Offline mode active');
|
|
1040
|
+
|
|
1041
|
+
await mcpServer.run();
|
|
1042
|
+
} catch (error) {
|
|
1043
|
+
console.error(`❌ Failed to start MCP server: ${error.message}`);
|
|
1044
|
+
process.exit(1);
|
|
1045
|
+
}
|
|
390
1046
|
}
|
|
391
1047
|
|
|
392
1048
|
if (require.main === module) {
|