@nerviq/cli 0.9.3 → 0.9.5

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.
@@ -0,0 +1,373 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Nerviq MCP Server
4
+ *
5
+ * Exposes Nerviq capabilities as an MCP (Model Context Protocol) server
6
+ * using stdio transport (stdin/stdout JSON-RPC 2.0).
7
+ *
8
+ * Tools:
9
+ * nerviq_audit — run audit for any platform, return JSON results
10
+ * nerviq_harmony — run harmony-audit, return cross-platform scores
11
+ * nerviq_setup — run setup for a platform, return written files list
12
+ * nerviq_drift — detect configuration drift between platforms
13
+ *
14
+ * Usage:
15
+ * node src/mcp-server.js
16
+ * (or via nerviq-mcp binary)
17
+ *
18
+ * Register in an MCP host config:
19
+ * {
20
+ * "mcpServers": {
21
+ * "nerviq": {
22
+ * "command": "npx",
23
+ * "args": ["nerviq-mcp"],
24
+ * "env": {}
25
+ * }
26
+ * }
27
+ * }
28
+ */
29
+
30
+ 'use strict';
31
+
32
+ const { version } = require('../package.json');
33
+
34
+ // ─── Tool definitions ────────────────────────────────────────────────────────
35
+
36
+ const TOOLS = [
37
+ {
38
+ name: 'nerviq_audit',
39
+ description: 'Run a Nerviq audit on a project directory for a given platform. Returns JSON with score, passed/failed checks, and recommendations.',
40
+ inputSchema: {
41
+ type: 'object',
42
+ properties: {
43
+ dir: {
44
+ type: 'string',
45
+ description: 'Absolute path to the project directory to audit. Defaults to current working directory.',
46
+ },
47
+ platform: {
48
+ type: 'string',
49
+ description: 'Platform to audit. One of: claude, codex, cursor, copilot, gemini, windsurf, aider, opencode.',
50
+ enum: ['claude', 'codex', 'cursor', 'copilot', 'gemini', 'windsurf', 'aider', 'opencode'],
51
+ default: 'claude',
52
+ },
53
+ verbose: {
54
+ type: 'boolean',
55
+ description: 'Include all checks in output, not just failures.',
56
+ default: false,
57
+ },
58
+ },
59
+ required: [],
60
+ },
61
+ },
62
+ {
63
+ name: 'nerviq_harmony',
64
+ description: 'Run a harmony audit across all detected AI platforms in a project. Returns cross-platform alignment scores, drift analysis, and recommendations.',
65
+ inputSchema: {
66
+ type: 'object',
67
+ properties: {
68
+ dir: {
69
+ type: 'string',
70
+ description: 'Absolute path to the project directory. Defaults to current working directory.',
71
+ },
72
+ verbose: {
73
+ type: 'boolean',
74
+ description: 'Include detailed per-platform results.',
75
+ default: false,
76
+ },
77
+ },
78
+ required: [],
79
+ },
80
+ },
81
+ {
82
+ name: 'nerviq_setup',
83
+ description: 'Generate and write baseline configuration files for a platform in a project directory. Returns the list of files written.',
84
+ inputSchema: {
85
+ type: 'object',
86
+ properties: {
87
+ dir: {
88
+ type: 'string',
89
+ description: 'Absolute path to the project directory. Defaults to current working directory.',
90
+ },
91
+ platform: {
92
+ type: 'string',
93
+ description: 'Platform to set up. One of: claude, codex, cursor, copilot, gemini, windsurf, aider, opencode.',
94
+ enum: ['claude', 'codex', 'cursor', 'copilot', 'gemini', 'windsurf', 'aider', 'opencode'],
95
+ default: 'claude',
96
+ },
97
+ dryRun: {
98
+ type: 'boolean',
99
+ description: 'Preview files that would be written without actually writing them.',
100
+ default: false,
101
+ },
102
+ },
103
+ required: [],
104
+ },
105
+ },
106
+ {
107
+ name: 'nerviq_drift',
108
+ description: 'Detect configuration drift between AI platforms in a project. Returns drift items with severity, type, and recommendations.',
109
+ inputSchema: {
110
+ type: 'object',
111
+ properties: {
112
+ dir: {
113
+ type: 'string',
114
+ description: 'Absolute path to the project directory. Defaults to current working directory.',
115
+ },
116
+ platforms: {
117
+ type: 'array',
118
+ items: { type: 'string' },
119
+ description: 'Specific platforms to compare. Defaults to all detected platforms.',
120
+ },
121
+ minSeverity: {
122
+ type: 'string',
123
+ description: 'Minimum severity to include. One of: critical, high, medium, low.',
124
+ enum: ['critical', 'high', 'medium', 'low'],
125
+ default: 'low',
126
+ },
127
+ },
128
+ required: [],
129
+ },
130
+ },
131
+ ];
132
+
133
+ // ─── Tool handlers ───────────────────────────────────────────────────────────
134
+
135
+ async function handleAudit(input) {
136
+ const { audit } = require('./audit');
137
+ const dir = input.dir || process.cwd();
138
+ const platform = input.platform || 'claude';
139
+ const verbose = Boolean(input.verbose);
140
+
141
+ const result = await audit({ dir, platform, silent: true, verbose });
142
+
143
+ // Return clean JSON without ANSI codes
144
+ const clean = {
145
+ platform: result.platform,
146
+ score: result.score,
147
+ passed: result.passed,
148
+ failed: result.failed,
149
+ total: result.total,
150
+ grade: result.score >= 80 ? 'A' : result.score >= 60 ? 'B' : result.score >= 40 ? 'C' : 'D',
151
+ criticalFailures: (result.results || [])
152
+ .filter(r => r.passed === false && r.impact === 'critical')
153
+ .map(r => ({ key: r.key, id: r.id, name: r.name, fix: r.fix })),
154
+ highFailures: (result.results || [])
155
+ .filter(r => r.passed === false && r.impact === 'high')
156
+ .map(r => ({ key: r.key, id: r.id, name: r.name, fix: r.fix })),
157
+ suggestedNextCommand: result.suggestedNextCommand || null,
158
+ };
159
+
160
+ if (verbose) {
161
+ clean.allResults = (result.results || []).map(r => ({
162
+ key: r.key,
163
+ id: r.id,
164
+ name: r.name,
165
+ passed: r.passed,
166
+ impact: r.impact,
167
+ fix: r.passed === false ? r.fix : undefined,
168
+ }));
169
+ }
170
+
171
+ return { content: [{ type: 'text', text: JSON.stringify(clean, null, 2) }] };
172
+ }
173
+
174
+ async function handleHarmony(input) {
175
+ const { harmonyAudit } = require('./harmony/audit');
176
+ const dir = input.dir || process.cwd();
177
+ const verbose = Boolean(input.verbose);
178
+
179
+ const result = await harmonyAudit({ dir, silent: true });
180
+
181
+ const clean = {
182
+ harmonyScore: result.harmonyScore,
183
+ activePlatforms: result.activePlatforms || [],
184
+ platformScores: result.platformScores || {},
185
+ driftCount: result.driftCount || 0,
186
+ criticalDrifts: (result.drifts || [])
187
+ .filter(d => d.severity === 'critical')
188
+ .map(d => ({ type: d.type, description: d.description, recommendation: d.recommendation })),
189
+ recommendations: (result.recommendations || []).slice(0, 5),
190
+ };
191
+
192
+ if (verbose) {
193
+ clean.allDrifts = (result.drifts || []).map(d => ({
194
+ type: d.type,
195
+ severity: d.severity,
196
+ description: d.description,
197
+ recommendation: d.recommendation,
198
+ }));
199
+ }
200
+
201
+ return { content: [{ type: 'text', text: JSON.stringify(clean, null, 2) }] };
202
+ }
203
+
204
+ async function handleSetup(input) {
205
+ const { setup } = require('./setup');
206
+ const dir = input.dir || process.cwd();
207
+ const platform = input.platform || 'claude';
208
+ const dryRun = Boolean(input.dryRun);
209
+
210
+ const result = await setup({ dir, platform, silent: true, dryRun });
211
+
212
+ const clean = {
213
+ platform,
214
+ dryRun,
215
+ writtenFiles: result.writtenFiles || [],
216
+ skippedFiles: result.skippedFiles || [],
217
+ message: dryRun
218
+ ? `Dry run: would write ${(result.writtenFiles || []).length} file(s)`
219
+ : `Setup complete: wrote ${(result.writtenFiles || []).length} file(s)`,
220
+ };
221
+
222
+ return { content: [{ type: 'text', text: JSON.stringify(clean, null, 2) }] };
223
+ }
224
+
225
+ async function handleDrift(input) {
226
+ const { detectDrift } = require('./harmony/drift');
227
+ const { buildCanonicalModel, detectActivePlatforms } = require('./harmony/canon');
228
+ const dir = input.dir || process.cwd();
229
+ const minSeverity = input.minSeverity || 'low';
230
+
231
+ const SEVERITY_ORDER = { critical: 3, high: 2, medium: 1, low: 0 };
232
+ const minLevel = SEVERITY_ORDER[minSeverity] || 0;
233
+
234
+ const canonModel = buildCanonicalModel(dir);
235
+ const activePlatforms = input.platforms && input.platforms.length > 0
236
+ ? input.platforms
237
+ : detectActivePlatforms(canonModel);
238
+
239
+ const driftResult = detectDrift(canonModel, activePlatforms, { verbose: true });
240
+
241
+ const filteredDrifts = (driftResult.drifts || [])
242
+ .filter(d => (SEVERITY_ORDER[d.severity] || 0) >= minLevel);
243
+
244
+ const clean = {
245
+ dir,
246
+ activePlatforms,
247
+ totalDrifts: driftResult.drifts ? driftResult.drifts.length : 0,
248
+ filteredDrifts: filteredDrifts.length,
249
+ minSeverity,
250
+ drifts: filteredDrifts.map(d => ({
251
+ type: d.type,
252
+ severity: d.severity,
253
+ description: d.description,
254
+ recommendation: d.recommendation || null,
255
+ platforms: d.platforms || null,
256
+ })),
257
+ summary: driftResult.summary || null,
258
+ };
259
+
260
+ return { content: [{ type: 'text', text: JSON.stringify(clean, null, 2) }] };
261
+ }
262
+
263
+ // ─── JSON-RPC 2.0 / MCP stdio transport ─────────────────────────────────────
264
+
265
+ function sendResponse(id, result) {
266
+ const msg = JSON.stringify({ jsonrpc: '2.0', id, result });
267
+ process.stdout.write(msg + '\n');
268
+ }
269
+
270
+ function sendError(id, code, message, data) {
271
+ const msg = JSON.stringify({
272
+ jsonrpc: '2.0',
273
+ id: id !== undefined ? id : null,
274
+ error: { code, message, ...(data ? { data } : {}) },
275
+ });
276
+ process.stdout.write(msg + '\n');
277
+ }
278
+
279
+ async function handleRequest(req) {
280
+ const { id, method, params } = req;
281
+
282
+ if (method === 'initialize') {
283
+ return sendResponse(id, {
284
+ protocolVersion: '2024-11-05',
285
+ capabilities: { tools: {} },
286
+ serverInfo: { name: 'nerviq', version },
287
+ });
288
+ }
289
+
290
+ if (method === 'tools/list') {
291
+ return sendResponse(id, { tools: TOOLS });
292
+ }
293
+
294
+ if (method === 'tools/call') {
295
+ const toolName = params && params.name;
296
+ const toolInput = (params && params.arguments) || {};
297
+
298
+ try {
299
+ let result;
300
+ if (toolName === 'nerviq_audit') {
301
+ result = await handleAudit(toolInput);
302
+ } else if (toolName === 'nerviq_harmony') {
303
+ result = await handleHarmony(toolInput);
304
+ } else if (toolName === 'nerviq_setup') {
305
+ result = await handleSetup(toolInput);
306
+ } else if (toolName === 'nerviq_drift') {
307
+ result = await handleDrift(toolInput);
308
+ } else {
309
+ return sendError(id, -32601, `Unknown tool: ${toolName}`);
310
+ }
311
+ return sendResponse(id, result);
312
+ } catch (err) {
313
+ return sendError(id, -32000, err.message, { stack: err.stack });
314
+ }
315
+ }
316
+
317
+ if (method === 'notifications/initialized' || method === 'ping') {
318
+ // No response needed for notifications; ack ping
319
+ if (method === 'ping') sendResponse(id, {});
320
+ return;
321
+ }
322
+
323
+ sendError(id, -32601, `Method not found: ${method}`);
324
+ }
325
+
326
+ // ─── Main loop ───────────────────────────────────────────────────────────────
327
+
328
+ function main() {
329
+ let buffer = '';
330
+
331
+ process.stdin.setEncoding('utf8');
332
+ process.stdin.on('data', (chunk) => {
333
+ buffer += chunk;
334
+ const lines = buffer.split('\n');
335
+ buffer = lines.pop(); // keep incomplete line
336
+
337
+ for (const line of lines) {
338
+ const trimmed = line.trim();
339
+ if (!trimmed) continue;
340
+
341
+ let req;
342
+ try {
343
+ req = JSON.parse(trimmed);
344
+ } catch {
345
+ sendError(null, -32700, 'Parse error', { raw: trimmed.slice(0, 200) });
346
+ continue;
347
+ }
348
+
349
+ handleRequest(req).catch((err) => {
350
+ sendError(req.id, -32000, 'Internal error', { message: err.message });
351
+ });
352
+ }
353
+ });
354
+
355
+ process.stdin.on('end', () => {
356
+ // Flush remaining buffer
357
+ if (buffer.trim()) {
358
+ let req;
359
+ try {
360
+ req = JSON.parse(buffer.trim());
361
+ handleRequest(req).catch(() => {});
362
+ } catch {}
363
+ }
364
+ process.exit(0);
365
+ });
366
+
367
+ // Suppress unhandled rejection crashes in MCP server context
368
+ process.on('unhandledRejection', (err) => {
369
+ process.stderr.write(`[nerviq-mcp] Unhandled rejection: ${err && err.message}\n`);
370
+ });
371
+ }
372
+
373
+ main();