@nerviq/cli 1.13.0 → 1.15.0

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/src/mcp-server.js CHANGED
@@ -1,34 +1,37 @@
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
-
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
+ * nerviq_check_score — quick score check with threshold gate
14
+ * nerviq_get_config — read current platform config (files, settings, trust)
15
+ * nerviq_apply_fix — apply a governance fix by check key
16
+ *
17
+ * Usage:
18
+ * node src/mcp-server.js
19
+ * (or via nerviq-mcp binary)
20
+ *
21
+ * Register in an MCP host config:
22
+ * {
23
+ * "mcpServers": {
24
+ * "nerviq": {
25
+ * "command": "npx",
26
+ * "args": ["nerviq-mcp"],
27
+ * "env": {}
28
+ * }
29
+ * }
30
+ * }
31
+ */
32
+
33
+ 'use strict';
34
+
32
35
  const { version } = require('../package.json');
33
36
 
34
37
  function buildMcpAuditPayload(result, options = {}) {
@@ -101,298 +104,609 @@ function buildMcpHarmonyPayload(result, options = {}) {
101
104
 
102
105
  return payload;
103
106
  }
104
-
105
- // ─── Tool definitions ────────────────────────────────────────────────────────
106
-
107
- const TOOLS = [
108
- {
109
- name: 'nerviq_audit',
110
- description: 'Run a Nerviq audit on a project directory for a given platform. Returns JSON with score, passed/failed checks, and recommendations.',
111
- inputSchema: {
112
- type: 'object',
113
- properties: {
114
- dir: {
115
- type: 'string',
116
- description: 'Absolute path to the project directory to audit. Defaults to current working directory.',
117
- },
118
- platform: {
119
- type: 'string',
120
- description: 'Platform to audit. One of: claude, codex, cursor, copilot, gemini, windsurf, aider, opencode.',
121
- enum: ['claude', 'codex', 'cursor', 'copilot', 'gemini', 'windsurf', 'aider', 'opencode'],
122
- default: 'claude',
123
- },
124
- verbose: {
125
- type: 'boolean',
126
- description: 'Include all checks in output, not just failures.',
127
- default: false,
128
- },
129
- },
130
- required: [],
131
- },
132
- },
133
- {
134
- name: 'nerviq_harmony',
135
- description: 'Run a harmony audit across all detected AI platforms in a project. Returns cross-platform alignment scores, drift analysis, and recommendations.',
136
- inputSchema: {
137
- type: 'object',
138
- properties: {
139
- dir: {
140
- type: 'string',
141
- description: 'Absolute path to the project directory. Defaults to current working directory.',
142
- },
143
- verbose: {
144
- type: 'boolean',
145
- description: 'Include detailed per-platform results.',
146
- default: false,
147
- },
148
- },
149
- required: [],
150
- },
151
- },
152
- {
153
- name: 'nerviq_setup',
154
- description: 'Generate and write baseline configuration files for a platform in a project directory. Returns the list of files written.',
155
- inputSchema: {
156
- type: 'object',
157
- properties: {
158
- dir: {
159
- type: 'string',
160
- description: 'Absolute path to the project directory. Defaults to current working directory.',
161
- },
162
- platform: {
163
- type: 'string',
164
- description: 'Platform to set up. One of: claude, codex, cursor, copilot, gemini, windsurf, aider, opencode.',
165
- enum: ['claude', 'codex', 'cursor', 'copilot', 'gemini', 'windsurf', 'aider', 'opencode'],
166
- default: 'claude',
167
- },
168
- dryRun: {
169
- type: 'boolean',
170
- description: 'Preview files that would be written without actually writing them.',
171
- default: false,
172
- },
173
- },
174
- required: [],
175
- },
176
- },
177
- {
178
- name: 'nerviq_drift',
179
- description: 'Detect configuration drift between AI platforms in a project. Returns drift items with severity, type, and recommendations.',
180
- inputSchema: {
181
- type: 'object',
182
- properties: {
183
- dir: {
184
- type: 'string',
185
- description: 'Absolute path to the project directory. Defaults to current working directory.',
186
- },
187
- platforms: {
188
- type: 'array',
189
- items: { type: 'string' },
190
- description: 'Specific platforms to compare. Defaults to all detected platforms.',
191
- },
192
- minSeverity: {
193
- type: 'string',
194
- description: 'Minimum severity to include. One of: critical, high, medium, low.',
195
- enum: ['critical', 'high', 'medium', 'low'],
196
- default: 'low',
197
- },
198
- },
199
- required: [],
200
- },
201
- },
202
- ];
203
-
204
- // ─── Tool handlers ───────────────────────────────────────────────────────────
205
-
107
+
108
+ // ─── Tool definitions ────────────────────────────────────────────────────────
109
+
110
+ const TOOLS = [
111
+ {
112
+ name: 'nerviq_audit',
113
+ description: 'Run a Nerviq audit on a project directory for a given platform. Returns JSON with score, passed/failed checks, and recommendations.',
114
+ inputSchema: {
115
+ type: 'object',
116
+ properties: {
117
+ dir: {
118
+ type: 'string',
119
+ description: 'Absolute path to the project directory to audit. Defaults to current working directory.',
120
+ },
121
+ platform: {
122
+ type: 'string',
123
+ description: 'Platform to audit. One of: claude, codex, cursor, copilot, gemini, windsurf, aider, opencode.',
124
+ enum: ['claude', 'codex', 'cursor', 'copilot', 'gemini', 'windsurf', 'aider', 'opencode'],
125
+ default: 'claude',
126
+ },
127
+ verbose: {
128
+ type: 'boolean',
129
+ description: 'Include all checks in output, not just failures.',
130
+ default: false,
131
+ },
132
+ },
133
+ required: [],
134
+ },
135
+ },
136
+ {
137
+ name: 'nerviq_harmony',
138
+ description: 'Run a harmony audit across all detected AI platforms in a project. Returns cross-platform alignment scores, drift analysis, and recommendations.',
139
+ inputSchema: {
140
+ type: 'object',
141
+ properties: {
142
+ dir: {
143
+ type: 'string',
144
+ description: 'Absolute path to the project directory. Defaults to current working directory.',
145
+ },
146
+ verbose: {
147
+ type: 'boolean',
148
+ description: 'Include detailed per-platform results.',
149
+ default: false,
150
+ },
151
+ },
152
+ required: [],
153
+ },
154
+ },
155
+ {
156
+ name: 'nerviq_setup',
157
+ description: 'Generate and write baseline configuration files for a platform in a project directory. Returns the list of files written.',
158
+ inputSchema: {
159
+ type: 'object',
160
+ properties: {
161
+ dir: {
162
+ type: 'string',
163
+ description: 'Absolute path to the project directory. Defaults to current working directory.',
164
+ },
165
+ platform: {
166
+ type: 'string',
167
+ description: 'Platform to set up. One of: claude, codex, cursor, copilot, gemini, windsurf, aider, opencode.',
168
+ enum: ['claude', 'codex', 'cursor', 'copilot', 'gemini', 'windsurf', 'aider', 'opencode'],
169
+ default: 'claude',
170
+ },
171
+ dryRun: {
172
+ type: 'boolean',
173
+ description: 'Preview files that would be written without actually writing them.',
174
+ default: false,
175
+ },
176
+ },
177
+ required: [],
178
+ },
179
+ },
180
+ {
181
+ name: 'nerviq_drift',
182
+ description: 'Detect configuration drift between AI platforms in a project. Returns drift items with severity, type, and recommendations.',
183
+ inputSchema: {
184
+ type: 'object',
185
+ properties: {
186
+ dir: {
187
+ type: 'string',
188
+ description: 'Absolute path to the project directory. Defaults to current working directory.',
189
+ },
190
+ platforms: {
191
+ type: 'array',
192
+ items: { type: 'string' },
193
+ description: 'Specific platforms to compare. Defaults to all detected platforms.',
194
+ },
195
+ minSeverity: {
196
+ type: 'string',
197
+ description: 'Minimum severity to include. One of: critical, high, medium, low.',
198
+ enum: ['critical', 'high', 'medium', 'low'],
199
+ default: 'low',
200
+ },
201
+ },
202
+ required: [],
203
+ },
204
+ },
205
+ {
206
+ name: 'nerviq_check_score',
207
+ description: 'Quick score check for a project — returns score, grade, and whether it meets a threshold. Lighter than a full audit.',
208
+ inputSchema: {
209
+ type: 'object',
210
+ properties: {
211
+ dir: {
212
+ type: 'string',
213
+ description: 'Absolute path to the project directory. Defaults to current working directory.',
214
+ },
215
+ platform: {
216
+ type: 'string',
217
+ description: 'Platform to check. Defaults to claude.',
218
+ enum: ['claude', 'codex', 'cursor', 'copilot', 'gemini', 'windsurf', 'aider', 'opencode'],
219
+ default: 'claude',
220
+ },
221
+ threshold: {
222
+ type: 'number',
223
+ description: 'Minimum passing score (0-100). Returns pass/fail against this threshold.',
224
+ default: 0,
225
+ },
226
+ },
227
+ required: [],
228
+ },
229
+ },
230
+ {
231
+ name: 'nerviq_get_config',
232
+ description: 'Read the current AI agent configuration for a platform in a project. Returns instruction files, settings, MCP servers, hooks, and trust posture.',
233
+ inputSchema: {
234
+ type: 'object',
235
+ properties: {
236
+ dir: {
237
+ type: 'string',
238
+ description: 'Absolute path to the project directory. Defaults to current working directory.',
239
+ },
240
+ platform: {
241
+ type: 'string',
242
+ description: 'Platform to inspect. Defaults to claude.',
243
+ enum: ['claude', 'codex', 'cursor', 'copilot', 'gemini', 'windsurf', 'aider', 'opencode'],
244
+ default: 'claude',
245
+ },
246
+ },
247
+ required: [],
248
+ },
249
+ },
250
+ {
251
+ name: 'nerviq_apply_fix',
252
+ description: 'Apply a specific governance fix by check key. Runs setup/plan for the targeted check and returns what was changed.',
253
+ inputSchema: {
254
+ type: 'object',
255
+ properties: {
256
+ dir: {
257
+ type: 'string',
258
+ description: 'Absolute path to the project directory. Defaults to current working directory.',
259
+ },
260
+ platform: {
261
+ type: 'string',
262
+ description: 'Platform to fix. Defaults to claude.',
263
+ enum: ['claude', 'codex', 'cursor', 'copilot', 'gemini', 'windsurf', 'aider', 'opencode'],
264
+ default: 'claude',
265
+ },
266
+ checkKey: {
267
+ type: 'string',
268
+ description: 'The check key to fix (e.g. "claudeMd", "settingsPermissions", "hookExists"). Get available keys from nerviq_audit results.',
269
+ },
270
+ dryRun: {
271
+ type: 'boolean',
272
+ description: 'Preview the fix without applying it.',
273
+ default: false,
274
+ },
275
+ },
276
+ required: ['checkKey'],
277
+ },
278
+ },
279
+ ];
280
+
281
+ // ─── Tool handlers ───────────────────────────────────────────────────────────
282
+
206
283
  async function handleAudit(input) {
207
- const { audit } = require('./audit');
208
- const dir = input.dir || process.cwd();
209
- const platform = input.platform || 'claude';
210
- const verbose = Boolean(input.verbose);
211
-
284
+ const { audit } = require('./audit');
285
+ const dir = input.dir || process.cwd();
286
+ const platform = input.platform || 'claude';
287
+ const verbose = Boolean(input.verbose);
288
+
212
289
  const result = await audit({ dir, platform, silent: true, verbose });
213
290
  const clean = buildMcpAuditPayload(result, { verbose });
214
291
  return { content: [{ type: 'text', text: JSON.stringify(clean, null, 2) }] };
215
292
  }
216
-
217
- async function handleHarmony(input) {
218
- const { harmonyAudit } = require('./harmony/audit');
219
- const dir = input.dir || process.cwd();
220
- const verbose = Boolean(input.verbose);
221
-
293
+
294
+ async function handleHarmony(input) {
295
+ const { harmonyAudit } = require('./harmony/audit');
296
+ const dir = input.dir || process.cwd();
297
+ const verbose = Boolean(input.verbose);
298
+
222
299
  const result = await harmonyAudit({ dir, silent: true });
223
300
  const clean = buildMcpHarmonyPayload(result, { verbose });
224
301
  return { content: [{ type: 'text', text: JSON.stringify(clean, null, 2) }] };
225
302
  }
226
-
227
- async function handleSetup(input) {
228
- const { setup } = require('./setup');
229
- const dir = input.dir || process.cwd();
230
- const platform = input.platform || 'claude';
231
- const dryRun = Boolean(input.dryRun);
232
-
233
- const result = await setup({ dir, platform, silent: true, dryRun });
234
-
235
- const clean = {
236
- platform,
237
- dryRun,
238
- writtenFiles: result.writtenFiles || [],
239
- skippedFiles: result.skippedFiles || [],
240
- message: dryRun
241
- ? `Dry run: would write ${(result.writtenFiles || []).length} file(s)`
242
- : `Setup complete: wrote ${(result.writtenFiles || []).length} file(s)`,
243
- };
244
-
245
- return { content: [{ type: 'text', text: JSON.stringify(clean, null, 2) }] };
246
- }
247
-
248
- async function handleDrift(input) {
249
- const { detectDrift } = require('./harmony/drift');
250
- const { buildCanonicalModel, detectActivePlatforms } = require('./harmony/canon');
251
- const dir = input.dir || process.cwd();
252
- const minSeverity = input.minSeverity || 'low';
253
-
254
- const SEVERITY_ORDER = { critical: 3, high: 2, medium: 1, low: 0 };
255
- const minLevel = SEVERITY_ORDER[minSeverity] || 0;
256
-
257
- const canonModel = buildCanonicalModel(dir);
258
- const activePlatforms = input.platforms && input.platforms.length > 0
259
- ? input.platforms
260
- : detectActivePlatforms(canonModel);
261
-
262
- const driftResult = detectDrift(canonModel, activePlatforms, { verbose: true });
263
-
264
- const filteredDrifts = (driftResult.drifts || [])
265
- .filter(d => (SEVERITY_ORDER[d.severity] || 0) >= minLevel);
266
-
267
- const clean = {
268
- dir,
269
- activePlatforms,
270
- totalDrifts: driftResult.drifts ? driftResult.drifts.length : 0,
271
- filteredDrifts: filteredDrifts.length,
272
- minSeverity,
273
- drifts: filteredDrifts.map(d => ({
274
- type: d.type,
275
- severity: d.severity,
276
- description: d.description,
277
- recommendation: d.recommendation || null,
278
- platforms: d.platforms || null,
279
- })),
280
- summary: driftResult.summary || null,
281
- };
282
-
283
- return { content: [{ type: 'text', text: JSON.stringify(clean, null, 2) }] };
284
- }
285
-
286
- // ─── JSON-RPC 2.0 / MCP stdio transport ─────────────────────────────────────
287
-
288
- function sendResponse(id, result) {
289
- const msg = JSON.stringify({ jsonrpc: '2.0', id, result });
290
- process.stdout.write(msg + '\n');
291
- }
292
-
293
- function sendError(id, code, message, data) {
294
- const msg = JSON.stringify({
295
- jsonrpc: '2.0',
296
- id: id !== undefined ? id : null,
297
- error: { code, message, ...(data ? { data } : {}) },
298
- });
299
- process.stdout.write(msg + '\n');
300
- }
301
-
302
- async function handleRequest(req) {
303
- const { id, method, params } = req;
304
-
305
- if (method === 'initialize') {
306
- return sendResponse(id, {
307
- protocolVersion: '2024-11-05',
308
- capabilities: { tools: {} },
309
- serverInfo: { name: 'nerviq', version },
310
- });
311
- }
312
-
313
- if (method === 'tools/list') {
314
- return sendResponse(id, { tools: TOOLS });
315
- }
316
-
317
- if (method === 'tools/call') {
318
- const toolName = params && params.name;
319
- const toolInput = (params && params.arguments) || {};
320
-
321
- try {
322
- let result;
323
- if (toolName === 'nerviq_audit') {
324
- result = await handleAudit(toolInput);
325
- } else if (toolName === 'nerviq_harmony') {
326
- result = await handleHarmony(toolInput);
327
- } else if (toolName === 'nerviq_setup') {
328
- result = await handleSetup(toolInput);
329
- } else if (toolName === 'nerviq_drift') {
330
- result = await handleDrift(toolInput);
331
- } else {
332
- return sendError(id, -32601, `Unknown tool: ${toolName}`);
333
- }
334
- return sendResponse(id, result);
335
- } catch (err) {
336
- return sendError(id, -32000, err.message, { stack: err.stack });
337
- }
338
- }
339
-
340
- if (method === 'notifications/initialized' || method === 'ping') {
341
- // No response needed for notifications; ack ping
342
- if (method === 'ping') sendResponse(id, {});
343
- return;
344
- }
345
-
346
- sendError(id, -32601, `Method not found: ${method}`);
347
- }
348
-
349
- // ─── Main loop ───────────────────────────────────────────────────────────────
350
-
351
- function main() {
352
- let buffer = '';
353
-
354
- process.stdin.setEncoding('utf8');
355
- process.stdin.on('data', (chunk) => {
356
- buffer += chunk;
357
- const lines = buffer.split('\n');
358
- buffer = lines.pop(); // keep incomplete line
359
-
360
- for (const line of lines) {
361
- const trimmed = line.trim();
362
- if (!trimmed) continue;
363
-
364
- let req;
365
- try {
366
- req = JSON.parse(trimmed);
367
- } catch {
368
- sendError(null, -32700, 'Parse error', { raw: trimmed.slice(0, 200) });
369
- continue;
370
- }
371
-
372
- handleRequest(req).catch((err) => {
373
- sendError(req.id, -32000, 'Internal error', { message: err.message });
374
- });
375
- }
376
- });
377
-
378
- process.stdin.on('end', () => {
379
- // Flush remaining buffer
380
- if (buffer.trim()) {
381
- let req;
382
- try {
383
- req = JSON.parse(buffer.trim());
384
- handleRequest(req).catch(() => {});
385
- } catch {}
386
- }
387
- process.exit(0);
388
- });
389
-
390
- // Suppress unhandled rejection crashes in MCP server context
391
- process.on('unhandledRejection', (err) => {
392
- process.stderr.write(`[nerviq-mcp] Unhandled rejection: ${err && err.message}\n`);
393
- });
394
- }
395
-
303
+
304
+ async function handleSetup(input) {
305
+ const { setup } = require('./setup');
306
+ const dir = input.dir || process.cwd();
307
+ const platform = input.platform || 'claude';
308
+ const dryRun = Boolean(input.dryRun);
309
+
310
+ const result = await setup({ dir, platform, silent: true, dryRun });
311
+
312
+ const clean = {
313
+ platform,
314
+ dryRun,
315
+ writtenFiles: result.writtenFiles || [],
316
+ skippedFiles: result.skippedFiles || [],
317
+ message: dryRun
318
+ ? `Dry run: would write ${(result.writtenFiles || []).length} file(s)`
319
+ : `Setup complete: wrote ${(result.writtenFiles || []).length} file(s)`,
320
+ };
321
+
322
+ return { content: [{ type: 'text', text: JSON.stringify(clean, null, 2) }] };
323
+ }
324
+
325
+ async function handleDrift(input) {
326
+ const { detectDrift } = require('./harmony/drift');
327
+ const { buildCanonicalModel, detectActivePlatforms } = require('./harmony/canon');
328
+ const dir = input.dir || process.cwd();
329
+ const minSeverity = input.minSeverity || 'low';
330
+
331
+ const SEVERITY_ORDER = { critical: 3, high: 2, medium: 1, low: 0 };
332
+ const minLevel = SEVERITY_ORDER[minSeverity] || 0;
333
+
334
+ const canonModel = buildCanonicalModel(dir);
335
+ const activePlatforms = input.platforms && input.platforms.length > 0
336
+ ? input.platforms
337
+ : detectActivePlatforms(canonModel);
338
+
339
+ const driftResult = detectDrift(canonModel, activePlatforms, { verbose: true });
340
+
341
+ const filteredDrifts = (driftResult.drifts || [])
342
+ .filter(d => (SEVERITY_ORDER[d.severity] || 0) >= minLevel);
343
+
344
+ const clean = {
345
+ dir,
346
+ activePlatforms,
347
+ totalDrifts: driftResult.drifts ? driftResult.drifts.length : 0,
348
+ filteredDrifts: filteredDrifts.length,
349
+ minSeverity,
350
+ drifts: filteredDrifts.map(d => ({
351
+ type: d.type,
352
+ severity: d.severity,
353
+ description: d.description,
354
+ recommendation: d.recommendation || null,
355
+ platforms: d.platforms || null,
356
+ })),
357
+ summary: driftResult.summary || null,
358
+ };
359
+
360
+ return { content: [{ type: 'text', text: JSON.stringify(clean, null, 2) }] };
361
+ }
362
+
363
+ async function handleCheckScore(input) {
364
+ const { audit } = require('./audit');
365
+ const dir = input.dir || process.cwd();
366
+ const platform = input.platform || 'claude';
367
+ const threshold = input.threshold || 0;
368
+
369
+ const result = await audit({ dir, platform, silent: true });
370
+ const score = result.score;
371
+ const grade = score >= 80 ? 'A' : score >= 60 ? 'B' : score >= 40 ? 'C' : 'D';
372
+ const pass = threshold > 0 ? score >= threshold : true;
373
+
374
+ const clean = {
375
+ score,
376
+ grade,
377
+ platform,
378
+ passed: result.passed,
379
+ failed: result.failed,
380
+ threshold: threshold || null,
381
+ pass,
382
+ remediation_command: score < 70 ? `npx @nerviq/cli augment --platform ${platform}` : null,
383
+ };
384
+
385
+ return { content: [{ type: 'text', text: JSON.stringify(clean, null, 2) }] };
386
+ }
387
+
388
+ async function handleGetConfig(input) {
389
+ const fs = require('fs');
390
+ const path = require('path');
391
+ const dir = input.dir || process.cwd();
392
+ const platform = input.platform || 'claude';
393
+
394
+ const config = { platform, dir, files: {} };
395
+
396
+ // Platform-specific config file mappings
397
+ const FILE_MAP = {
398
+ claude: {
399
+ instructions: ['CLAUDE.md', '.claude/CLAUDE.md'],
400
+ settings: ['.claude/settings.json', '.claude/settings.local.json'],
401
+ rules: '.claude/rules',
402
+ hooks: '.claude/hooks',
403
+ },
404
+ codex: {
405
+ instructions: ['AGENTS.md'],
406
+ settings: ['.codex/config.toml'],
407
+ rules: null,
408
+ hooks: null,
409
+ },
410
+ gemini: {
411
+ instructions: ['GEMINI.md'],
412
+ settings: ['.gemini/settings.json'],
413
+ rules: null,
414
+ hooks: null,
415
+ },
416
+ copilot: {
417
+ instructions: ['.github/copilot-instructions.md'],
418
+ settings: [],
419
+ rules: null,
420
+ hooks: null,
421
+ },
422
+ cursor: {
423
+ instructions: ['.cursorrules'],
424
+ settings: [],
425
+ rules: '.cursor/rules',
426
+ hooks: null,
427
+ },
428
+ windsurf: {
429
+ instructions: ['.windsurfrules'],
430
+ settings: [],
431
+ rules: '.windsurf/rules',
432
+ hooks: null,
433
+ },
434
+ aider: {
435
+ instructions: ['.aider.conf.yml'],
436
+ settings: ['.aiderignore'],
437
+ rules: null,
438
+ hooks: null,
439
+ },
440
+ opencode: {
441
+ instructions: ['opencode.json'],
442
+ settings: ['.opencode'],
443
+ rules: null,
444
+ hooks: null,
445
+ },
446
+ };
447
+
448
+ const mapping = FILE_MAP[platform] || FILE_MAP.claude;
449
+
450
+ // Read instruction files
451
+ for (const f of mapping.instructions) {
452
+ const fullPath = path.join(dir, f);
453
+ if (fs.existsSync(fullPath)) {
454
+ try {
455
+ const content = fs.readFileSync(fullPath, 'utf8');
456
+ config.files[f] = { exists: true, size: content.length, lines: content.split('\n').length };
457
+ } catch { config.files[f] = { exists: true, error: 'unreadable' }; }
458
+ } else {
459
+ config.files[f] = { exists: false };
460
+ }
461
+ }
462
+
463
+ // Read settings files
464
+ for (const f of mapping.settings) {
465
+ const fullPath = path.join(dir, f);
466
+ if (fs.existsSync(fullPath)) {
467
+ try {
468
+ const content = fs.readFileSync(fullPath, 'utf8');
469
+ if (f.endsWith('.json')) {
470
+ config.files[f] = { exists: true, parsed: JSON.parse(content) };
471
+ } else {
472
+ config.files[f] = { exists: true, size: content.length };
473
+ }
474
+ } catch { config.files[f] = { exists: true, error: 'parse-failed' }; }
475
+ } else {
476
+ config.files[f] = { exists: false };
477
+ }
478
+ }
479
+
480
+ // Check rules dir
481
+ if (mapping.rules) {
482
+ const rulesPath = path.join(dir, mapping.rules);
483
+ if (fs.existsSync(rulesPath)) {
484
+ try {
485
+ const entries = fs.readdirSync(rulesPath);
486
+ config.files[mapping.rules] = { exists: true, count: entries.length, entries };
487
+ } catch { config.files[mapping.rules] = { exists: true, error: 'unreadable' }; }
488
+ } else {
489
+ config.files[mapping.rules] = { exists: false };
490
+ }
491
+ }
492
+
493
+ // Check hooks dir
494
+ if (mapping.hooks) {
495
+ const hooksPath = path.join(dir, mapping.hooks);
496
+ if (fs.existsSync(hooksPath)) {
497
+ try {
498
+ const entries = fs.readdirSync(hooksPath);
499
+ config.files[mapping.hooks] = { exists: true, count: entries.length, entries };
500
+ } catch { config.files[mapping.hooks] = { exists: true, error: 'unreadable' }; }
501
+ } else {
502
+ config.files[mapping.hooks] = { exists: false };
503
+ }
504
+ }
505
+
506
+ // Trust posture summary
507
+ if (platform === 'claude' && config.files['.claude/settings.json'] && config.files['.claude/settings.json'].parsed) {
508
+ const settings = config.files['.claude/settings.json'].parsed;
509
+ config.trustPosture = {
510
+ allowedTools: settings.permissions?.allow || [],
511
+ deniedPatterns: settings.permissions?.deny || [],
512
+ hasExplicitPermissions: !!(settings.permissions),
513
+ };
514
+ }
515
+
516
+ return { content: [{ type: 'text', text: JSON.stringify(config, null, 2) }] };
517
+ }
518
+
519
+ async function handleApplyFix(input) {
520
+ const { audit } = require('./audit');
521
+ const { setup } = require('./setup');
522
+ const dir = input.dir || process.cwd();
523
+ const platform = input.platform || 'claude';
524
+ const checkKey = input.checkKey;
525
+ const dryRun = Boolean(input.dryRun);
526
+
527
+ // First, verify the check actually fails
528
+ const preAudit = await audit({ dir, platform, silent: true });
529
+ const targetCheck = (preAudit.results || []).find(r => r.key === checkKey);
530
+
531
+ if (!targetCheck) {
532
+ return { content: [{ type: 'text', text: JSON.stringify({
533
+ status: 'error',
534
+ message: `Check key "${checkKey}" not found in ${platform} audit. Use nerviq_audit to see available check keys.`,
535
+ }, null, 2) }] };
536
+ }
537
+
538
+ if (targetCheck.passed) {
539
+ return { content: [{ type: 'text', text: JSON.stringify({
540
+ status: 'already_passing',
541
+ checkKey,
542
+ message: `Check "${checkKey}" is already passing. No fix needed.`,
543
+ }, null, 2) }] };
544
+ }
545
+
546
+ // Map check categories to setup --only targets
547
+ const CATEGORY_TO_ONLY = {
548
+ memory: 'instructions',
549
+ security: 'permissions',
550
+ automation: 'hooks',
551
+ workflow: 'commands',
552
+ tools: 'mcp',
553
+ quality: 'instructions',
554
+ git: 'instructions',
555
+ };
556
+
557
+ const only = CATEGORY_TO_ONLY[targetCheck.category] || null;
558
+
559
+ if (dryRun) {
560
+ return { content: [{ type: 'text', text: JSON.stringify({
561
+ status: 'dry_run',
562
+ checkKey,
563
+ category: targetCheck.category,
564
+ fix: targetCheck.fix,
565
+ would_run: `npx @nerviq/cli setup --platform ${platform}${only ? ` --only ${only}` : ''}`,
566
+ }, null, 2) }] };
567
+ }
568
+
569
+ // Apply the fix
570
+ const setupResult = await setup({
571
+ dir,
572
+ platform,
573
+ silent: true,
574
+ only: only ? [only] : undefined,
575
+ });
576
+
577
+ // Re-audit to check if fix worked
578
+ const postAudit = await audit({ dir, platform, silent: true });
579
+ const postCheck = (postAudit.results || []).find(r => r.key === checkKey);
580
+
581
+ return { content: [{ type: 'text', text: JSON.stringify({
582
+ status: postCheck && postCheck.passed ? 'fixed' : 'attempted',
583
+ checkKey,
584
+ category: targetCheck.category,
585
+ fix_description: targetCheck.fix,
586
+ files_written: setupResult.writtenFiles || [],
587
+ score_before: preAudit.score,
588
+ score_after: postAudit.score,
589
+ check_now_passing: postCheck ? postCheck.passed : false,
590
+ rollback_id: setupResult.rollbackId || null,
591
+ }, null, 2) }] };
592
+ }
593
+
594
+ // ─── JSON-RPC 2.0 / MCP stdio transport ─────────────────────────────────────
595
+
596
+ function sendResponse(id, result) {
597
+ const msg = JSON.stringify({ jsonrpc: '2.0', id, result });
598
+ process.stdout.write(msg + '\n');
599
+ }
600
+
601
+ function sendError(id, code, message, data) {
602
+ const msg = JSON.stringify({
603
+ jsonrpc: '2.0',
604
+ id: id !== undefined ? id : null,
605
+ error: { code, message, ...(data ? { data } : {}) },
606
+ });
607
+ process.stdout.write(msg + '\n');
608
+ }
609
+
610
+ async function handleRequest(req) {
611
+ const { id, method, params } = req;
612
+
613
+ if (method === 'initialize') {
614
+ return sendResponse(id, {
615
+ protocolVersion: '2024-11-05',
616
+ capabilities: { tools: {} },
617
+ serverInfo: { name: 'nerviq', version },
618
+ });
619
+ }
620
+
621
+ if (method === 'tools/list') {
622
+ return sendResponse(id, { tools: TOOLS });
623
+ }
624
+
625
+ if (method === 'tools/call') {
626
+ const toolName = params && params.name;
627
+ const toolInput = (params && params.arguments) || {};
628
+
629
+ try {
630
+ let result;
631
+ if (toolName === 'nerviq_audit') {
632
+ result = await handleAudit(toolInput);
633
+ } else if (toolName === 'nerviq_harmony') {
634
+ result = await handleHarmony(toolInput);
635
+ } else if (toolName === 'nerviq_setup') {
636
+ result = await handleSetup(toolInput);
637
+ } else if (toolName === 'nerviq_drift') {
638
+ result = await handleDrift(toolInput);
639
+ } else if (toolName === 'nerviq_check_score') {
640
+ result = await handleCheckScore(toolInput);
641
+ } else if (toolName === 'nerviq_get_config') {
642
+ result = await handleGetConfig(toolInput);
643
+ } else if (toolName === 'nerviq_apply_fix') {
644
+ result = await handleApplyFix(toolInput);
645
+ } else {
646
+ return sendError(id, -32601, `Unknown tool: ${toolName}`);
647
+ }
648
+ return sendResponse(id, result);
649
+ } catch (err) {
650
+ return sendError(id, -32000, err.message, { stack: err.stack });
651
+ }
652
+ }
653
+
654
+ if (method === 'notifications/initialized' || method === 'ping') {
655
+ // No response needed for notifications; ack ping
656
+ if (method === 'ping') sendResponse(id, {});
657
+ return;
658
+ }
659
+
660
+ sendError(id, -32601, `Method not found: ${method}`);
661
+ }
662
+
663
+ // ─── Main loop ───────────────────────────────────────────────────────────────
664
+
665
+ function main() {
666
+ let buffer = '';
667
+
668
+ process.stdin.setEncoding('utf8');
669
+ process.stdin.on('data', (chunk) => {
670
+ buffer += chunk;
671
+ const lines = buffer.split('\n');
672
+ buffer = lines.pop(); // keep incomplete line
673
+
674
+ for (const line of lines) {
675
+ const trimmed = line.trim();
676
+ if (!trimmed) continue;
677
+
678
+ let req;
679
+ try {
680
+ req = JSON.parse(trimmed);
681
+ } catch {
682
+ sendError(null, -32700, 'Parse error', { raw: trimmed.slice(0, 200) });
683
+ continue;
684
+ }
685
+
686
+ handleRequest(req).catch((err) => {
687
+ sendError(req.id, -32000, 'Internal error', { message: err.message });
688
+ });
689
+ }
690
+ });
691
+
692
+ process.stdin.on('end', () => {
693
+ // Flush remaining buffer
694
+ if (buffer.trim()) {
695
+ let req;
696
+ try {
697
+ req = JSON.parse(buffer.trim());
698
+ handleRequest(req).catch(() => {});
699
+ } catch {}
700
+ }
701
+ process.exit(0);
702
+ });
703
+
704
+ // Suppress unhandled rejection crashes in MCP server context
705
+ process.on('unhandledRejection', (err) => {
706
+ process.stderr.write(`[nerviq-mcp] Unhandled rejection: ${err && err.message}\n`);
707
+ });
708
+ }
709
+
396
710
  if (require.main === module) {
397
711
  main();
398
712
  }
@@ -405,5 +719,8 @@ module.exports = {
405
719
  handleHarmony,
406
720
  handleSetup,
407
721
  handleDrift,
722
+ handleCheckScore,
723
+ handleGetConfig,
724
+ handleApplyFix,
408
725
  main,
409
726
  };