-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·521 lines (459 loc) · 14.9 KB
/
cli.js
File metadata and controls
executable file
·521 lines (459 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
#!/usr/bin/env bun
/**
* CLI interface for moidvk tools
* Allows direct command-line access to all analysis tools
*/
import { promises as fs } from 'node:fs';
import { stdin as input, stdout as _output } from 'node:process';
import { createInterface } from 'node:readline/promises';
import path from 'path';
import { spawn } from 'child_process';
// Import tool handlers
import { handleCodePractices } from './lib/tools/code-practices.js';
import { handleCodeFormatter } from './lib/tools/code-formatter.js';
import { handleSafetyChecker } from './lib/tools/safety-checker.js';
import { handleSecurityScanner } from './lib/tools/security-scanner.js';
import { handleProductionReadiness } from './lib/tools/production-readiness.js';
import { handleAccessibilityChecker } from './lib/tools/accessibility-checker.js';
import { handleGraphqlSchemaCheck } from './lib/tools/graphql-schema-checker.js';
import { handleGraphqlQueryCheck } from './lib/tools/graphql-query-checker.js';
import { handleReduxPatternsCheck } from './lib/tools/redux-patterns-checker.js';
import {
handleIntelligentDevelopmentAnalysis,
handleDevelopmentSessionManager,
handleSemanticDevelopmentSearch,
} from './lib/tools/intelligent-tools.js';
// Tool mapping
const TOOLS = {
serve: {
handler: null, // Special handler for serve command
name: 'serve',
description: 'Start the MCP server',
requiresCode: false,
requiresFile: false,
isServerCommand: true,
},
'check-code': {
handler: handleCodePractices,
name: 'check_code_practices',
description: 'Check code for best practices and common issues',
requiresCode: true,
requiresFile: false,
},
format: {
handler: handleCodeFormatter,
name: 'format_code',
description: 'Format code with consistent style',
requiresCode: true,
requiresFile: false,
},
'check-safety': {
handler: handleSafetyChecker,
name: 'check_safety_rules',
description: 'Check code against NASA JPL safety rules',
requiresCode: true,
requiresFile: false,
},
'scan-security': {
handler: handleSecurityScanner,
name: 'scan_security_vulnerabilities',
description: 'Scan project for security vulnerabilities',
requiresCode: false,
requiresFile: false,
requiresPath: true,
},
'check-production': {
handler: handleProductionReadiness,
name: 'check_production_readiness',
description: 'Check if code is ready for production deployment',
requiresCode: true,
requiresFile: false,
},
'check-accessibility': {
handler: handleAccessibilityChecker,
name: 'check_accessibility',
description: 'Check web content for accessibility issues',
requiresCode: true,
requiresFile: false,
},
'check-graphql-schema': {
handler: handleGraphqlSchemaCheck,
name: 'check_graphql_schema',
description: 'Validate GraphQL schema definitions',
requiresCode: true,
requiresFile: false,
},
'check-graphql-query': {
handler: handleGraphqlQueryCheck,
name: 'check_graphql_query',
description: 'Validate GraphQL queries and mutations',
requiresCode: true,
requiresFile: false,
},
'check-redux': {
handler: handleReduxPatternsCheck,
name: 'check_redux_patterns',
description: 'Check Redux patterns and best practices',
requiresCode: true,
requiresFile: false,
},
'analyze-dev': {
handler: handleIntelligentDevelopmentAnalysis,
name: 'intelligent_development_analysis',
description: 'Analyze development workflow and suggest optimal tool sequences',
requiresCode: false,
requiresFile: false,
requiresPath: true,
},
session: {
handler: handleDevelopmentSessionManager,
name: 'development_session_manager',
description: 'Manage development sessions across MCP clients',
requiresCode: false,
requiresFile: false,
},
'search-semantic': {
handler: handleSemanticDevelopmentSearch,
name: 'semantic_development_search',
description: 'Context-aware semantic search for development',
requiresCode: false,
requiresFile: false,
requiresPath: true,
},
};
/**
* Start the MCP server
*/
async function startServer(_options) {
// Check if we're in MCP mode (no TTY means we're being called by an MCP client)
const isMCPMode = !process.stdin.isTTY;
if (isMCPMode) {
// In MCP mode, directly run the server without spawning
// This maintains stdio communication with the MCP client
try {
await import('./server.js');
} catch (error) {
// Log to stderr so it doesn't interfere with stdio protocol
console.error('Failed to start MCP server:', error.message); // eslint-disable-line no-console
process.exit(1);
}
} else {
// In interactive mode, show helpful information
/* eslint-disable no-console */
console.log('🚀 Starting moidvk MCP server...');
console.log('📡 Server will be available via MCP protocol');
console.log('🔧 Available tools:');
// List available tools
Object.entries(TOOLS).forEach(([, tool]) => {
if (!tool.isServerCommand) {
console.log(` • ${tool.name}: ${tool.description}`);
}
});
console.log('\n⏹️ Press Ctrl+C to stop the server\n');
/* eslint-enable no-console */
// Start the server process
const serverProcess = spawn('bun', ['server.js'], {
stdio: 'inherit',
cwd: process.cwd(),
});
// Handle process events
serverProcess.on('error', (error) => {
console.error('❌ Failed to start server:', error.message); // eslint-disable-line no-console
process.exit(1);
});
serverProcess.on('exit', (code) => {
if (code !== 0) {
console.error(`❌ Server exited with code ${code}`); // eslint-disable-line no-console
process.exit(code);
}
});
// Handle graceful shutdown
process.on('SIGINT', () => {
console.log('\n🛑 Shutting down server...'); // eslint-disable-line no-console
serverProcess.kill('SIGINT');
});
process.on('SIGTERM', () => {
console.log('\n🛑 Shutting down server...'); // eslint-disable-line no-console
serverProcess.kill('SIGTERM');
});
}
}
/**
* Start the test MCP server
*/
async function _startTestServer(_options) {
/* eslint-disable no-console */
console.log('🧪 Starting moidvk test server...');
console.log('📡 Test server will be available via MCP protocol');
console.log('🔧 Available tools:');
console.log(' • test_tool: A simple test tool');
console.log('\n⏹️ Press Ctrl+C to stop the server\n');
/* eslint-enable no-console */
// Start the test server process
const serverProcess = spawn('bun', ['test-server.js'], {
stdio: 'inherit',
cwd: process.cwd(),
});
// Handle process events
serverProcess.on('error', (error) => {
console.error('❌ Failed to start test server:', error.message); // eslint-disable-line no-console
process.exit(1);
});
serverProcess.on('exit', (code) => {
if (code !== 0) {
console.error(`❌ Test server exited with code ${code}`); // eslint-disable-line no-console
process.exit(code);
}
});
// Handle graceful shutdown
process.on('SIGINT', () => {
console.log('\n🛑 Shutting down test server...'); // eslint-disable-line no-console
serverProcess.kill('SIGINT');
});
process.on('SIGTERM', () => {
console.log('\n🛑 Shutting down server...'); // eslint-disable-line no-console
serverProcess.kill('SIGTERM');
});
}
/**
* Display help information
*/
function showHelp() {
console.log(`
moidvk CLI - Code analysis and quality tools
Usage:
moidvk <command> [options]
Commands:
${Object.entries(TOOLS)
.map(([cmd, tool]) => ` ${cmd.padEnd(20)} ${tool.description}`)
.join('\n')}
Options:
-f, --file <path> Read code from file instead of stdin
-o, --output <path> Write output to file instead of stdout
-p, --path <path> Project path (for scan-security, analyze-dev, search-semantic)
--production Enable production mode (stricter checks)
--strict Enable strict mode
--format <format> Output format (text, json, detailed)
--goals <goals> Comma-separated list of development goals
--client <type> Client type (cli, vscode, cursor, etc.)
--action <action> Session action (create, list, get, update, complete)
--session-id <id> Session ID for session operations
--query <text> Search query for semantic search
--search-type <type> Search type (similar_code, related_patterns, etc.)
--max-results <n> Maximum number of search results
-h, --help Show this help message
Examples:
# Start the MCP server
moidvk serve
# Check code from stdin
echo "const x = 1" | moidvk check-code
# Check file directly
moidvk check-code -f src/index.js
# Format code and save to file
moidvk format -f src/messy.js -o src/clean.js
# Scan project for vulnerabilities
moidvk scan-security -p /path/to/project
# Check production readiness with strict mode
moidvk check-production -f server.js --strict --production
# Check accessibility of HTML file
moidvk check-accessibility -f index.html
# Analyze development workflow
moidvk analyze-dev -p /path/to/project
# Manage development sessions
moidvk session --action create --goals "Fix authentication bug"
# Semantic search in codebase
moidvk search-semantic -p /path/to/project --query "authentication logic"
`);
}
/**
* Parse command line arguments
*/
function parseArgs(args) {
const options = {
command: null,
file: null,
output: null,
path: null,
production: false,
strict: false,
format: 'text',
help: false,
// Intelligent tool options
goals: null,
client: null,
action: null,
sessionId: null,
query: null,
searchType: null,
maxResults: null,
};
let i = 0;
while (i < args.length) {
const arg = args[i];
if (arg === '-h' || arg === '--help') {
options.help = true;
break;
} else if (arg === '-f' || arg === '--file') {
options.file = args[++i];
} else if (arg === '-o' || arg === '--output') {
options.output = args[++i];
} else if (arg === '-p' || arg === '--path') {
options.path = args[++i];
} else if (arg === '--production') {
options.production = true;
} else if (arg === '--strict') {
options.strict = true;
} else if (arg === '--format') {
options.format = args[++i];
} else if (arg === '--goals') {
options.goals = args[++i];
} else if (arg === '--client') {
options.client = args[++i];
} else if (arg === '--action') {
options.action = args[++i];
} else if (arg === '--session-id') {
options.sessionId = args[++i];
} else if (arg === '--query') {
options.query = args[++i];
} else if (arg === '--search-type') {
options.searchType = args[++i];
} else if (arg === '--max-results') {
options.maxResults = parseInt(args[++i], 10);
} else if (!arg.startsWith('-') && !options.command) {
options.command = arg;
}
i++;
}
return options;
}
/**
* Read code from stdin or file
*/
async function readCode(options) {
if (options.file) {
return await fs.readFile(options.file, 'utf-8');
}
// Read from stdin
if (process.stdin.isTTY) {
console.error('Error: No input provided. Use -f to specify a file or pipe input via stdin.'); // eslint-disable-line no-console
process.exit(1);
}
const rl = createInterface({ input, output: null });
const lines = [];
for await (const line of rl) {
lines.push(line);
}
return lines.join('\n');
}
/**
* Format output based on response
*/
function formatOutput(response, format) {
if (format === 'json') {
// Extract JSON data if available
const content = response.content?.[0]?.text || '';
const jsonMatch = content.match(/```json\n([\s\S]*?)\n```/);
if (jsonMatch) {
return jsonMatch[1];
}
// Try to find JSON object in the content
const jsonStart = content.indexOf('{');
if (jsonStart !== -1) {
try {
const jsonStr = content.substring(jsonStart);
JSON.parse(jsonStr); // Validate it's JSON
return jsonStr;
} catch {
// Fall through to text output
}
}
}
// Default text output
return response.content?.[0]?.text || 'No output';
}
/**
* Main CLI function
*/
async function main() {
const args = process.argv.slice(2);
const options = parseArgs(args);
if (options.help || !options.command) {
showHelp();
process.exit(0);
}
const tool = TOOLS[options.command];
if (!tool) {
console.error(`Error: Unknown command '${options.command}'`); // eslint-disable-line no-console
showHelp();
process.exit(1);
}
try {
// Handle serve command specially
if (tool.isServerCommand) {
await startServer(options);
return; // Don't exit, let the server run
}
let toolArgs = {};
// Get code input if required
if (tool.requiresCode) {
const code = await readCode(options);
toolArgs.code = code;
// Set filename if provided or infer from file path
if (options.file) {
toolArgs.filename = path.basename(options.file);
}
}
// Add project path for security scanner
if (tool.requiresPath) {
toolArgs.projectPath = options.path || process.cwd();
}
// Add additional options
if (options.production) {
toolArgs.production = true;
}
if (options.strict) {
toolArgs.strict = true;
}
if (options.format && tool.name === 'scan_security_vulnerabilities') {
toolArgs.format = options.format;
}
// Handle intelligent tool arguments
if (tool.name === 'intelligent_development_analysis') {
toolArgs.goals = options.goals?.split(',') || [];
toolArgs.client_type = options.client || 'cli';
}
if (tool.name === 'development_session_manager') {
toolArgs.action = options.action || 'list';
if (options.goals) {
toolArgs.goals = options.goals.split(',');
}
if (options.sessionId) {
toolArgs.session_id = options.sessionId;
}
}
if (tool.name === 'semantic_development_search') {
toolArgs.query = options.query || '';
toolArgs.type = options.searchType || 'similar_code';
toolArgs.max_results = options.maxResults || 10;
}
// Call the tool handler
const response = await tool.handler(toolArgs);
// Format and output results
const output = formatOutput(response, options.format);
if (options.output) {
await fs.writeFile(options.output, output);
console.log(`Output written to ${options.output}`); // eslint-disable-line no-console
} else {
console.log(output); // eslint-disable-line no-console
}
process.exit(0);
} catch (error) {
console.error('Error:', error.message); // eslint-disable-line no-console
process.exit(1);
}
}
// Run CLI
main().catch((error) => {
console.error('Fatal error:', error); // eslint-disable-line no-console
process.exit(1);
});