mcp-prompt-optimizer 1.3.2 โ†’ 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,100 +1,134 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * Clear Cache Utility for MCP Prompt Optimizer
5
- * Clears validation cache and provides fresh start
4
+ * Clear Cache Command for MCP Prompt Optimizer
5
+ * Enhanced with network health data clearing and development mode support
6
6
  */
7
7
 
8
8
  const CloudApiKeyManager = require('./api-key-manager');
9
- const fs = require('fs').promises;
10
- const path = require('path');
11
- const os = require('os');
9
+ const packageJson = require('../package.json');
12
10
 
13
11
  async function clearCache() {
14
- console.log('๐Ÿ—‘๏ธ MCP Prompt Optimizer - Clear Cache\n');
15
-
16
- const cacheFile = path.join(os.homedir(), '.mcp-cloud-api-cache.json');
17
- let cacheCleared = false;
18
-
12
+ const developmentMode = process.env.NODE_ENV === 'development' || process.env.OPTIMIZER_DEV_MODE === 'true';
13
+ const modeText = developmentMode ? ' (Development Mode)' : '';
14
+
15
+ console.log(`๐Ÿงน MCP Prompt Optimizer v${packageJson.version} - Clear Cache${modeText}\n`);
16
+
19
17
  try {
20
- // Check if cache file exists
21
- await fs.access(cacheFile);
22
-
23
- // Read cache info before clearing
24
- try {
25
- const cacheContent = await fs.readFile(cacheFile, 'utf8');
26
- const cacheData = JSON.parse(cacheContent);
27
- const cacheAge = Date.now() - cacheData.timestamp;
28
- const ageHours = Math.floor(cacheAge / (1000 * 60 * 60));
29
- const ageMinutes = Math.floor((cacheAge % (1000 * 60 * 60)) / (1000 * 60));
30
-
31
- console.log('๐Ÿ“„ Found cache file:');
32
- console.log(` Location: ${cacheFile}`);
33
- console.log(` Age: ${ageHours}h ${ageMinutes}m`);
34
- if (cacheData.data && cacheData.data.tier) {
35
- console.log(` Cached tier: ${cacheData.data.tier}`);
36
- }
37
- } catch (parseError) {
38
- console.log('๐Ÿ“„ Found cache file (invalid format)');
18
+ const apiKey = process.env.OPTIMIZER_API_KEY;
19
+
20
+ if (!apiKey) {
21
+ console.log('โš ๏ธ No API key found, clearing system caches only');
39
22
  }
40
23
 
41
- // Clear the cache
42
- await fs.unlink(cacheFile);
43
- cacheCleared = true;
44
- console.log('\nโœ… Cache cleared successfully');
45
-
46
- } catch (error) {
47
- if (error.code === 'ENOENT') {
48
- console.log('๐Ÿ“„ No cache file found - nothing to clear');
49
- } else {
50
- console.warn(`โš ๏ธ Error accessing cache: ${error.message}`);
24
+ // Create manager instance for cache operations
25
+ const manager = new CloudApiKeyManager(apiKey || 'dummy-key-for-cache-clear', {
26
+ developmentMode
27
+ });
28
+
29
+ console.log('๐Ÿ” Analyzing cache status...');
30
+
31
+ // Check what caches exist before clearing
32
+ const diagnostic = await manager.getDiagnosticInfo();
33
+
34
+ let cachesFound = 0;
35
+ let healthDataFound = false;
36
+
37
+ if (diagnostic.cache.exists) {
38
+ cachesFound++;
39
+ console.log(`๐Ÿ“„ Found validation cache (${diagnostic.cache.age} minutes old)`);
51
40
  }
52
- }
53
-
54
- // Also try to clear any additional cache files
55
- const additionalCaches = [
56
- path.join(os.homedir(), '.mcp-prompt-optimizer-cache.json'),
57
- path.join(os.homedir(), '.optimizer-cache.json'),
58
- path.join(os.homedir(), '.mcp-cache.json')
59
- ];
60
-
61
- for (const cacheFile of additionalCaches) {
62
- try {
63
- await fs.access(cacheFile);
64
- await fs.unlink(cacheFile);
65
- console.log(`โœ… Cleared additional cache: ${path.basename(cacheFile)}`);
66
- cacheCleared = true;
67
- } catch (error) {
68
- // File doesn't exist, that's fine
41
+
42
+ if (diagnostic.networkHealth.lastSuccessful || diagnostic.networkHealth.consecutiveFailures > 0) {
43
+ healthDataFound = true;
44
+ console.log(`๐Ÿฅ Found network health data (${diagnostic.networkHealth.consecutiveFailures} failures recorded)`);
69
45
  }
70
- }
71
-
72
- if (cacheCleared) {
73
- console.log('\n๐Ÿš€ Cache cleared - next validation will be fresh');
74
- console.log('\n๐Ÿ“ What this means:');
75
- console.log(' - API key will be re-validated with backend');
76
- console.log(' - Fresh quota information will be fetched');
77
- console.log(' - Any cached errors will be cleared');
78
-
79
- console.log('\n๐Ÿ”ง Next Steps:');
80
- console.log(' 1. Test your API key: mcp-prompt-optimizer validate-key');
46
+
47
+ if (cachesFound === 0 && !healthDataFound) {
48
+ console.log('โœจ No caches found - system is already clean!');
49
+ console.log('\n๐Ÿ“Š Cache Status: Clean');
50
+ console.log('๐Ÿฅ Network Health: Clean');
51
+ return;
52
+ }
53
+
54
+ console.log('\n๐Ÿงน Clearing caches...');
55
+
56
+ // Clear all caches
57
+ await manager.clearCache();
58
+
59
+ console.log('โœ… Cache clearing completed successfully!\n');
60
+
61
+ // Report what was cleared
62
+ console.log('๐Ÿ“Š Cleared Items:');
63
+ if (cachesFound > 0) {
64
+ console.log(' โœ… API key validation cache');
65
+ console.log(' โœ… Subscription status cache');
66
+ console.log(' โœ… Backend response cache');
67
+ }
68
+
69
+ if (healthDataFound) {
70
+ console.log(' โœ… Network health metrics');
71
+ console.log(' โœ… Connection failure history');
72
+ console.log(' โœ… Response time statistics');
73
+ }
74
+
75
+ console.log('\n๐ŸŽฏ Benefits of Cache Clearing:');
76
+ console.log(' ๐Ÿ”„ Forces fresh API key validation');
77
+ console.log(' ๐Ÿ“ก Tests current backend connectivity');
78
+ console.log(' ๐Ÿงน Removes stale network health data');
79
+ console.log(' ๐Ÿ” Enables accurate diagnostic information');
80
+ console.log(' โšก May resolve authentication issues');
81
+
82
+ if (developmentMode) {
83
+ console.log('\n๐Ÿงช Development Mode Notes:');
84
+ console.log(' ๐Ÿ”„ Mock cache data cleared');
85
+ console.log(' ๐Ÿ“ด Ready for fresh offline testing');
86
+ console.log(' ๐Ÿงช Development flags reset');
87
+ }
88
+
89
+ console.log('\n๐Ÿ“ Next Steps:');
90
+ console.log(' 1. Run validation: mcp-prompt-optimizer validate-key');
81
91
  console.log(' 2. Check status: mcp-prompt-optimizer check-status');
82
- console.log(' 3. Start using: Configure in Claude Desktop');
83
- } else {
84
- console.log('\nโœจ No cache found - your setup is already clean');
92
+ console.log(' 3. Test integration: mcp-prompt-optimizer test');
93
+ console.log(' 4. Run diagnostic: mcp-prompt-optimizer diagnose');
94
+
95
+ console.log('\n๐Ÿ’ก When to Clear Cache:');
96
+ console.log(' ๐Ÿ”‘ After updating API key');
97
+ console.log(' ๐ŸŒ When experiencing connection issues');
98
+ console.log(' ๐Ÿ”„ After changing backend URL');
99
+ console.log(' ๐Ÿงช Before switching between dev/production modes');
100
+ console.log(' ๐Ÿ› ๏ธ When troubleshooting authentication problems');
101
+
102
+ } catch (error) {
103
+ console.error(`โŒ Cache clearing failed: ${error.message}\n`);
104
+
105
+ if (error.message.includes('ENOENT')) {
106
+ console.log('โ„น๏ธ Cache files not found - nothing to clear');
107
+ console.log('โœจ System is already clean!');
108
+ } else if (error.message.includes('EACCES') || error.message.includes('permission')) {
109
+ console.log('๐Ÿ”’ Permission Issue:');
110
+ console.log(' - Cache files may be locked by another process');
111
+ console.log(' - Try running with elevated permissions');
112
+ console.log(' - Ensure no other MCP processes are running');
113
+ } else {
114
+ console.log('๐Ÿ› ๏ธ Troubleshooting:');
115
+ console.log(' 1. Check file system permissions');
116
+ console.log(' 2. Ensure no processes are using cache files');
117
+ console.log(' 3. Try restarting terminal/command prompt');
118
+ console.log(' 4. Contact support if issue persists');
119
+ }
120
+
121
+ console.log('\n๐Ÿ“ Manual Cache Locations:');
122
+ console.log(` Validation: ${diagnostic?.cacheFile || '~/.mcp-cloud-api-cache.json'}`);
123
+ console.log(` Health: ${diagnostic?.healthFile || '~/.mcp-cloud-health.json'}`);
124
+ console.log(' You can manually delete these files if needed');
125
+
126
+ process.exit(1);
85
127
  }
86
-
87
- // Offer to validate immediately
88
- console.log('\n๐Ÿ’ก Want to validate your API key now?');
89
- console.log(' Run: mcp-prompt-optimizer validate-key');
90
128
  }
91
129
 
92
- // Run if called directly
93
130
  if (require.main === module) {
94
- clearCache().catch(error => {
95
- console.error(`โŒ Error clearing cache: ${error.message}`);
96
- process.exit(1);
97
- });
131
+ clearCache();
98
132
  }
99
133
 
100
134
  module.exports = clearCache;
@@ -0,0 +1,252 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Diagnostic Command for MCP Prompt Optimizer
5
+ * Enhanced with comprehensive network analysis and development mode support
6
+ */
7
+
8
+ const CloudApiKeyManager = require('./api-key-manager');
9
+ const packageJson = require('../package.json');
10
+
11
+ async function runDiagnostic() {
12
+ const developmentMode = process.env.NODE_ENV === 'development' || process.env.OPTIMIZER_DEV_MODE === 'true';
13
+ const modeText = developmentMode ? ' (Development Mode)' : '';
14
+
15
+ console.log(`๐Ÿ”ฌ MCP Prompt Optimizer v${packageJson.version} - Comprehensive Diagnostic${modeText}\n`);
16
+
17
+ try {
18
+ const apiKey = process.env.OPTIMIZER_API_KEY;
19
+
20
+ if (!apiKey) {
21
+ console.log('โš ๏ธ No API key found, running partial diagnostic');
22
+ console.log('Set OPTIMIZER_API_KEY for complete analysis\n');
23
+ }
24
+
25
+ const manager = new CloudApiKeyManager(apiKey || 'dummy-key-for-diagnostic', {
26
+ developmentMode
27
+ });
28
+ const diagnostic = await manager.getDiagnosticInfo();
29
+
30
+ console.log('๐Ÿ“‹ Diagnostic Information:');
31
+ console.log('=' .repeat(60));
32
+
33
+ // Basic system information
34
+ console.log(`๐Ÿ”‘ API Key: ${diagnostic.apiKey}`);
35
+ console.log(`๐ŸŒ Backend URL: ${diagnostic.backendUrl}`);
36
+ console.log(`๐Ÿ’พ Cache File: ${diagnostic.cacheFile}`);
37
+ console.log(`๐Ÿฅ Health File: ${diagnostic.healthFile}`);
38
+ console.log(`โฐ Cache Expiry: ${diagnostic.cacheExpiry / 1000 / 60} minutes`);
39
+ console.log(`โฐ Fallback Cache Expiry: ${diagnostic.fallbackCacheExpiry / 1000 / 60 / 60} hours`);
40
+ console.log(`๐Ÿ“ฑ Offline Mode: ${diagnostic.offlineMode}`);
41
+ console.log(`๐Ÿงช Development Mode: ${diagnostic.developmentMode}`);
42
+ console.log(`๐Ÿ”„ Max Retries: ${diagnostic.maxRetries}`);
43
+ console.log(`โฑ๏ธ Request Timeout: ${diagnostic.requestTimeout}ms`);
44
+ console.log(`๐Ÿ”ง Node Environment: ${diagnostic.nodeEnv || 'not set'}`);
45
+ console.log(`๐Ÿ“ฆ Package Version: ${diagnostic.packageVersion}`);
46
+
47
+ // Network health section
48
+ console.log('\n๐ŸŒ Network Health:');
49
+ const health = diagnostic.networkHealth;
50
+ console.log(` ๐Ÿ“Š Consecutive Failures: ${health.consecutiveFailures}`);
51
+ console.log(` โœ… Last Successful: ${health.lastSuccessful ? new Date(health.lastSuccessful).toLocaleString() : 'Never'}`);
52
+ console.log(` โšก Avg Response Time: ${health.avgResponseTime ? health.avgResponseTime + 'ms' : 'Unknown'}`);
53
+ console.log(` โŒ Last Error Type: ${health.lastErrorType || 'None'}`);
54
+
55
+ // Cache status
56
+ console.log('\n๐Ÿ“„ Cache Status:');
57
+ if (diagnostic.cache.error) {
58
+ console.log(` โŒ Error: ${diagnostic.cache.error}`);
59
+ } else {
60
+ console.log(` ๐Ÿ“ Exists: ${diagnostic.cache.exists}`);
61
+ console.log(` โณ Normal Cache Expired: ${diagnostic.cache.expired}`);
62
+ console.log(` ๐Ÿ”„ Fallback Cache Expired: ${diagnostic.cache.fallbackExpired}`);
63
+ console.log(` ๐Ÿ“… Age: ${diagnostic.cache.age} minutes`);
64
+
65
+ if (diagnostic.cache.backendUrl) {
66
+ console.log(` ๐ŸŒ Cached Backend: ${diagnostic.cache.backendUrl}`);
67
+ }
68
+ if (diagnostic.cache.packageVersion) {
69
+ console.log(` ๐Ÿ“ฆ Cached Version: ${diagnostic.cache.packageVersion}`);
70
+ }
71
+ }
72
+
73
+ // API key format check
74
+ console.log('\n๐Ÿ” API Key Format Check:');
75
+ if (diagnostic.keyFormat.valid) {
76
+ console.log(` โœ… Valid: ${diagnostic.keyFormat.keyType}`);
77
+ } else {
78
+ console.log(` โŒ Invalid: ${diagnostic.keyFormat.error}`);
79
+ }
80
+
81
+ // Backend connectivity analysis
82
+ console.log('\n๐ŸŒ Backend Connectivity Analysis:');
83
+ const connectivity = diagnostic.backendConnectivity;
84
+ if (connectivity.status === 'success') {
85
+ console.log(' โœ… Connection successful');
86
+ if (connectivity.responseTime) {
87
+ console.log(` โšก Response time: ${connectivity.responseTime}ms`);
88
+ }
89
+ } else {
90
+ console.log(` โŒ Connection failed: ${connectivity.error}`);
91
+
92
+ // Enhanced error analysis
93
+ if (connectivity.dns) {
94
+ console.log(' ๐Ÿ” Issue Type: DNS Resolution Failure');
95
+ console.log(' ๐Ÿ’ก Likely Causes:');
96
+ console.log(' - Internet connection issues');
97
+ console.log(' - DNS server problems');
98
+ console.log(' - Corporate firewall blocking DNS');
99
+ console.log(' - VPN/proxy configuration issues');
100
+ } else if (connectivity.connection) {
101
+ console.log(' ๐Ÿ” Issue Type: Connection Refused/Reset');
102
+ console.log(' ๐Ÿ’ก Likely Causes:');
103
+ console.log(' - Backend server is down');
104
+ console.log(' - Port blocking by firewall');
105
+ console.log(' - Network routing issues');
106
+ console.log(' - Load balancer problems');
107
+ } else if (connectivity.timeout) {
108
+ console.log(' ๐Ÿ” Issue Type: Connection Timeout');
109
+ console.log(' ๐Ÿ’ก Likely Causes:');
110
+ console.log(' - Slow network connection');
111
+ console.log(' - Backend server overload');
112
+ console.log(' - Proxy/firewall delays');
113
+ console.log(' - Geographic distance');
114
+ } else if (connectivity.network) {
115
+ console.log(' ๐Ÿ” Issue Type: General Network Error');
116
+ console.log(' ๐Ÿ’ก Likely Causes:');
117
+ console.log(' - Network instability');
118
+ console.log(' - ISP issues');
119
+ console.log(' - WiFi connectivity problems');
120
+ console.log(' - Mobile data limitations');
121
+ }
122
+ }
123
+
124
+ // Development mode specific information
125
+ if (developmentMode) {
126
+ console.log('\n๐Ÿงช Development Mode Analysis:');
127
+ console.log(' โœ… Development mode active');
128
+ console.log(' ๐Ÿ”„ Mock responses available');
129
+ console.log(' ๐Ÿ“ด Offline operation supported');
130
+ console.log(' ๐Ÿงช No backend dependency required');
131
+
132
+ if (apiKey && (apiKey.startsWith('sk-dev-') || apiKey.startsWith('sk-local-'))) {
133
+ console.log(' โœ… Development API key detected');
134
+ } else {
135
+ console.log(' โš ๏ธ Consider using development API key (sk-dev-* or sk-local-*)');
136
+ }
137
+ }
138
+
139
+ // Recommendations section
140
+ console.log('\n๐Ÿ’ก Recommendations:');
141
+
142
+ if (!apiKey) {
143
+ console.log(' ๐Ÿ”‘ Set API key: export OPTIMIZER_API_KEY=sk-opt-your-key');
144
+ console.log(' ๐Ÿ†“ Get free trial: https://promptoptimizer-blog.vercel.app/pricing');
145
+ }
146
+
147
+ if (health.consecutiveFailures > 0) {
148
+ console.log(` ๐Ÿ”„ ${health.consecutiveFailures} consecutive network failures detected`);
149
+ console.log(' ๐Ÿงช Consider development mode: export OPTIMIZER_DEV_MODE=true');
150
+ console.log(' ๐Ÿ“ก Check network connectivity and firewall settings');
151
+ }
152
+
153
+ if (diagnostic.cache.exists && diagnostic.cache.expired && !diagnostic.cache.fallbackExpired) {
154
+ console.log(' ๐Ÿ’พ Cache available for fallback mode');
155
+ console.log(' ๐Ÿ”„ Package can operate with reduced functionality');
156
+ }
157
+
158
+ if (!developmentMode && connectivity.status === 'failed') {
159
+ console.log(' ๐Ÿงช Try development mode for offline testing:');
160
+ console.log(' export OPTIMIZER_DEV_MODE=true');
161
+ console.log(' export OPTIMIZER_API_KEY=sk-dev-test-key');
162
+ }
163
+
164
+ if (connectivity.status === 'success' && health.avgResponseTime > 5000) {
165
+ console.log(' โšก Network latency is high (>5s)');
166
+ console.log(' ๐ŸŒ Consider checking network quality or VPN settings');
167
+ }
168
+
169
+ // Action items
170
+ console.log('\n๐ŸŽฏ Suggested Actions:');
171
+
172
+ if (connectivity.status === 'failed') {
173
+ console.log(' 1. ๐ŸŒ Test basic internet: ping google.com');
174
+ console.log(' 2. ๐Ÿ” Check DNS: nslookup p01--project-optimizer--fvrdk8m9k9j.code.run');
175
+ console.log(' 3. ๐Ÿ›ก๏ธ Verify firewall allows HTTPS traffic');
176
+ console.log(' 4. ๐Ÿ”„ Try again in a few minutes');
177
+ console.log(' 5. ๐Ÿงช Use development mode for immediate testing');
178
+ } else {
179
+ console.log(' 1. โœ… Network connectivity is working well');
180
+ console.log(' 2. ๐Ÿš€ Ready for production use');
181
+
182
+ if (!apiKey || !diagnostic.keyFormat.valid) {
183
+ console.log(' 3. ๐Ÿ”‘ Set up proper API key for full functionality');
184
+ } else {
185
+ console.log(' 3. ๐ŸŽฏ All systems operational');
186
+ }
187
+ }
188
+
189
+ // Network environment detection
190
+ console.log('\n๐ŸŒ Network Environment:');
191
+ const userAgent = `mcp-prompt-optimizer/${diagnostic.packageVersion}`;
192
+ console.log(` ๐Ÿ“ฑ User Agent: ${userAgent}`);
193
+ console.log(` ๐Ÿข Corporate Network: ${connectivity.timeout || connectivity.dns ? 'Likely' : 'Unlikely'}`);
194
+ console.log(` ๐Ÿ”’ Firewall/Proxy: ${connectivity.timeout ? 'Possible' : 'Unlikely'}`);
195
+ console.log(` ๐Ÿ“ถ Connection Quality: ${health.avgResponseTime ?
196
+ (health.avgResponseTime < 1000 ? 'Excellent' :
197
+ health.avgResponseTime < 3000 ? 'Good' :
198
+ health.avgResponseTime < 5000 ? 'Fair' : 'Poor') : 'Unknown'}`);
199
+
200
+ console.log(`\n๐Ÿ• Generated: ${diagnostic.timestamp}`);
201
+
202
+ // Final status summary
203
+ console.log('\n' + '='.repeat(60));
204
+ console.log('๐Ÿ“Š DIAGNOSTIC SUMMARY:');
205
+
206
+ const issues = [];
207
+ const working = [];
208
+
209
+ if (!apiKey) issues.push('No API key configured');
210
+ else working.push('API key present');
211
+
212
+ if (!diagnostic.keyFormat.valid) issues.push('Invalid API key format');
213
+ else working.push('API key format valid');
214
+
215
+ if (connectivity.status === 'failed') issues.push('Backend connectivity failed');
216
+ else working.push('Backend connectivity working');
217
+
218
+ if (diagnostic.cache.error) issues.push('Cache system error');
219
+ else working.push('Cache system working');
220
+
221
+ if (health.consecutiveFailures > 3) issues.push('Multiple network failures');
222
+ else working.push('Network stability good');
223
+
224
+ console.log(`โœ… Working (${working.length}): ${working.join(', ')}`);
225
+ if (issues.length > 0) {
226
+ console.log(`โš ๏ธ Issues (${issues.length}): ${issues.join(', ')}`);
227
+ }
228
+
229
+ const overallStatus = issues.length === 0 ? 'EXCELLENT' :
230
+ issues.length <= 2 ? 'GOOD' : 'NEEDS ATTENTION';
231
+ console.log(`\n๐ŸŽฏ Overall Status: ${overallStatus}`);
232
+
233
+ if (developmentMode) {
234
+ console.log('๐Ÿงช Development mode provides full offline functionality');
235
+ }
236
+
237
+ } catch (error) {
238
+ console.error('โŒ Diagnostic failed:', error.message);
239
+ console.log('\n๐Ÿ†˜ Emergency Diagnostic:');
240
+ console.log(' - Package installation may be corrupted');
241
+ console.log(' - Try: npm install --force');
242
+ console.log(' - Ensure Node.js version >= 16.0.0');
243
+ console.log(' - Contact support: support@promptoptimizer.help');
244
+ process.exit(1);
245
+ }
246
+ }
247
+
248
+ if (require.main === module) {
249
+ runDiagnostic();
250
+ }
251
+
252
+ module.exports = runDiagnostic;