ai-cli-mcp 2.0.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.
Files changed (69) hide show
  1. package/.claude/settings.local.json +19 -0
  2. package/.github/workflows/ci.yml +31 -0
  3. package/.github/workflows/test.yml +43 -0
  4. package/.vscode/settings.json +3 -0
  5. package/AGENT.md +57 -0
  6. package/CHANGELOG.md +126 -0
  7. package/LICENSE +22 -0
  8. package/README.md +329 -0
  9. package/RELEASE.md +74 -0
  10. package/data/rooms/refactor-haiku-alias-main/messages.jsonl +5 -0
  11. package/data/rooms/refactor-haiku-alias-main/presence.json +20 -0
  12. package/data/rooms.json +10 -0
  13. package/dist/__tests__/e2e.test.js +238 -0
  14. package/dist/__tests__/edge-cases.test.js +135 -0
  15. package/dist/__tests__/error-cases.test.js +296 -0
  16. package/dist/__tests__/mocks.js +32 -0
  17. package/dist/__tests__/model-alias.test.js +36 -0
  18. package/dist/__tests__/process-management.test.js +632 -0
  19. package/dist/__tests__/server.test.js +665 -0
  20. package/dist/__tests__/setup.js +11 -0
  21. package/dist/__tests__/utils/claude-mock.js +80 -0
  22. package/dist/__tests__/utils/mcp-client.js +104 -0
  23. package/dist/__tests__/utils/persistent-mock.js +25 -0
  24. package/dist/__tests__/utils/test-helpers.js +11 -0
  25. package/dist/__tests__/validation.test.js +212 -0
  26. package/dist/__tests__/version-print.test.js +69 -0
  27. package/dist/parsers.js +54 -0
  28. package/dist/server.js +614 -0
  29. package/docs/RELEASE_CHECKLIST.md +26 -0
  30. package/docs/e2e-testing.md +148 -0
  31. package/docs/local_install.md +111 -0
  32. package/hello.txt +3 -0
  33. package/implementation-log.md +110 -0
  34. package/implementation-plan.md +189 -0
  35. package/investigation-report.md +135 -0
  36. package/package.json +53 -0
  37. package/print-eslint-config.js +3 -0
  38. package/quality-score.json +47 -0
  39. package/refactoring-requirements.md +25 -0
  40. package/review-report.md +132 -0
  41. package/scripts/check-version-log.sh +34 -0
  42. package/scripts/publish-release.sh +95 -0
  43. package/scripts/restore-config.sh +28 -0
  44. package/scripts/test-release.sh +69 -0
  45. package/src/__tests__/e2e.test.ts +290 -0
  46. package/src/__tests__/edge-cases.test.ts +181 -0
  47. package/src/__tests__/error-cases.test.ts +378 -0
  48. package/src/__tests__/mocks.ts +35 -0
  49. package/src/__tests__/model-alias.test.ts +44 -0
  50. package/src/__tests__/process-management.test.ts +772 -0
  51. package/src/__tests__/server.test.ts +851 -0
  52. package/src/__tests__/setup.ts +13 -0
  53. package/src/__tests__/utils/claude-mock.ts +87 -0
  54. package/src/__tests__/utils/mcp-client.ts +129 -0
  55. package/src/__tests__/utils/persistent-mock.ts +29 -0
  56. package/src/__tests__/utils/test-helpers.ts +13 -0
  57. package/src/__tests__/validation.test.ts +258 -0
  58. package/src/__tests__/version-print.test.ts +86 -0
  59. package/src/parsers.ts +55 -0
  60. package/src/server.ts +735 -0
  61. package/start.bat +9 -0
  62. package/start.sh +21 -0
  63. package/test-results.md +119 -0
  64. package/test-standalone.js +5877 -0
  65. package/tsconfig.json +16 -0
  66. package/vitest.config.e2e.ts +27 -0
  67. package/vitest.config.ts +22 -0
  68. package/vitest.config.unit.ts +29 -0
  69. package/xx.txt +1 -0
package/dist/server.js ADDED
@@ -0,0 +1,614 @@
1
+ #!/usr/bin/env node
2
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError, } from '@modelcontextprotocol/sdk/types.js';
5
+ import { spawn } from 'node:child_process';
6
+ import { existsSync, readFileSync } from 'node:fs';
7
+ import { homedir } from 'node:os';
8
+ import { join, resolve as pathResolve } from 'node:path';
9
+ import * as path from 'path';
10
+ import { parseCodexOutput, parseClaudeOutput } from './parsers.js';
11
+ // Server version - update this when releasing new versions
12
+ const SERVER_VERSION = "2.0.0";
13
+ // Model alias mappings for user-friendly model names
14
+ const MODEL_ALIASES = {
15
+ 'haiku': 'claude-3-5-haiku-20241022'
16
+ };
17
+ // Define debugMode globally using const
18
+ const debugMode = process.env.MCP_CLAUDE_DEBUG === 'true';
19
+ // Track if this is the first tool use for version printing
20
+ let isFirstToolUse = true;
21
+ // Capture server startup time when the module loads
22
+ const serverStartupTime = new Date().toISOString();
23
+ // Global process manager
24
+ const processManager = new Map();
25
+ // Dedicated debug logging function
26
+ export function debugLog(message, ...optionalParams) {
27
+ if (debugMode) {
28
+ console.error(message, ...optionalParams);
29
+ }
30
+ }
31
+ /**
32
+ * Determine the Codex CLI command/path.
33
+ * Similar to findClaudeCli but for Codex
34
+ */
35
+ export function findCodexCli() {
36
+ debugLog('[Debug] Attempting to find Codex CLI...');
37
+ // Check for custom CLI name from environment variable
38
+ const customCliName = process.env.CODEX_CLI_NAME;
39
+ if (customCliName) {
40
+ debugLog(`[Debug] Using custom Codex CLI name from CODEX_CLI_NAME: ${customCliName}`);
41
+ // If it's an absolute path, use it directly
42
+ if (path.isAbsolute(customCliName)) {
43
+ debugLog(`[Debug] CODEX_CLI_NAME is an absolute path: ${customCliName}`);
44
+ return customCliName;
45
+ }
46
+ // If it starts with ~ or ./, reject as relative paths are not allowed
47
+ if (customCliName.startsWith('./') || customCliName.startsWith('../') || customCliName.includes('/')) {
48
+ throw new Error(`Invalid CODEX_CLI_NAME: Relative paths are not allowed. Use either a simple name (e.g., 'codex') or an absolute path (e.g., '/tmp/codex-test')`);
49
+ }
50
+ }
51
+ const cliName = customCliName || 'codex';
52
+ // Try local install path: ~/.codex/local/codex
53
+ const userPath = join(homedir(), '.codex', 'local', 'codex');
54
+ debugLog(`[Debug] Checking for Codex CLI at local user path: ${userPath}`);
55
+ if (existsSync(userPath)) {
56
+ debugLog(`[Debug] Found Codex CLI at local user path: ${userPath}. Using this path.`);
57
+ return userPath;
58
+ }
59
+ else {
60
+ debugLog(`[Debug] Codex CLI not found at local user path: ${userPath}.`);
61
+ }
62
+ // Fallback to CLI name (PATH lookup)
63
+ debugLog(`[Debug] Falling back to "${cliName}" command name, relying on spawn/PATH lookup.`);
64
+ console.warn(`[Warning] Codex CLI not found at ~/.codex/local/codex. Falling back to "${cliName}" in PATH. Ensure it is installed and accessible.`);
65
+ return cliName;
66
+ }
67
+ /**
68
+ * Determine the Claude CLI command/path.
69
+ * 1. Checks for CLAUDE_CLI_NAME environment variable:
70
+ * - If absolute path, uses it directly
71
+ * - If relative path, throws error
72
+ * - If simple name, continues with path resolution
73
+ * 2. Checks for Claude CLI at the local user path: ~/.claude/local/claude.
74
+ * 3. If not found, defaults to the CLI name (or 'claude'), relying on the system's PATH for lookup.
75
+ */
76
+ export function findClaudeCli() {
77
+ debugLog('[Debug] Attempting to find Claude CLI...');
78
+ // Check for custom CLI name from environment variable
79
+ const customCliName = process.env.CLAUDE_CLI_NAME;
80
+ if (customCliName) {
81
+ debugLog(`[Debug] Using custom Claude CLI name from CLAUDE_CLI_NAME: ${customCliName}`);
82
+ // If it's an absolute path, use it directly
83
+ if (path.isAbsolute(customCliName)) {
84
+ debugLog(`[Debug] CLAUDE_CLI_NAME is an absolute path: ${customCliName}`);
85
+ return customCliName;
86
+ }
87
+ // If it starts with ~ or ./, reject as relative paths are not allowed
88
+ if (customCliName.startsWith('./') || customCliName.startsWith('../') || customCliName.includes('/')) {
89
+ throw new Error(`Invalid CLAUDE_CLI_NAME: Relative paths are not allowed. Use either a simple name (e.g., 'claude') or an absolute path (e.g., '/tmp/claude-test')`);
90
+ }
91
+ }
92
+ const cliName = customCliName || 'claude';
93
+ // Try local install path: ~/.claude/local/claude (using the original name for local installs)
94
+ const userPath = join(homedir(), '.claude', 'local', 'claude');
95
+ debugLog(`[Debug] Checking for Claude CLI at local user path: ${userPath}`);
96
+ if (existsSync(userPath)) {
97
+ debugLog(`[Debug] Found Claude CLI at local user path: ${userPath}. Using this path.`);
98
+ return userPath;
99
+ }
100
+ else {
101
+ debugLog(`[Debug] Claude CLI not found at local user path: ${userPath}.`);
102
+ }
103
+ // 3. Fallback to CLI name (PATH lookup)
104
+ debugLog(`[Debug] Falling back to "${cliName}" command name, relying on spawn/PATH lookup.`);
105
+ console.warn(`[Warning] Claude CLI not found at ~/.claude/local/claude. Falling back to "${cliName}" in PATH. Ensure it is installed and accessible.`);
106
+ return cliName;
107
+ }
108
+ /**
109
+ * Resolves model aliases to their full model names
110
+ * @param model - The model name or alias to resolve
111
+ * @returns The full model name, or the original value if no alias exists
112
+ */
113
+ export function resolveModelAlias(model) {
114
+ return MODEL_ALIASES[model] || model;
115
+ }
116
+ // Ensure spawnAsync is defined correctly *before* the class
117
+ export async function spawnAsync(command, args, options) {
118
+ return new Promise((resolve, reject) => {
119
+ debugLog(`[Spawn] Running command: ${command} ${args.join(' ')}`);
120
+ const process = spawn(command, args, {
121
+ shell: false, // Reverted to false
122
+ timeout: options?.timeout,
123
+ cwd: options?.cwd,
124
+ stdio: ['ignore', 'pipe', 'pipe']
125
+ });
126
+ let stdout = '';
127
+ let stderr = '';
128
+ process.stdout.on('data', (data) => { stdout += data.toString(); });
129
+ process.stderr.on('data', (data) => {
130
+ stderr += data.toString();
131
+ debugLog(`[Spawn Stderr Chunk] ${data.toString()}`);
132
+ });
133
+ process.on('error', (error) => {
134
+ debugLog(`[Spawn Error Event] Full error object:`, error);
135
+ let errorMessage = `Spawn error: ${error.message}`;
136
+ if (error.path) {
137
+ errorMessage += ` | Path: ${error.path}`;
138
+ }
139
+ if (error.syscall) {
140
+ errorMessage += ` | Syscall: ${error.syscall}`;
141
+ }
142
+ errorMessage += `\nStderr: ${stderr.trim()}`;
143
+ reject(new Error(errorMessage));
144
+ });
145
+ process.on('close', (code) => {
146
+ debugLog(`[Spawn Close] Exit code: ${code}`);
147
+ debugLog(`[Spawn Stderr Full] ${stderr.trim()}`);
148
+ debugLog(`[Spawn Stdout Full] ${stdout.trim()}`);
149
+ if (code === 0) {
150
+ resolve({ stdout, stderr });
151
+ }
152
+ else {
153
+ reject(new Error(`Command failed with exit code ${code}\nStderr: ${stderr.trim()}\nStdout: ${stdout.trim()}`));
154
+ }
155
+ });
156
+ });
157
+ }
158
+ /**
159
+ * MCP Server for Claude Code
160
+ * Provides a simple MCP tool to run Claude CLI in one-shot mode
161
+ */
162
+ export class ClaudeCodeServer {
163
+ server;
164
+ claudeCliPath;
165
+ codexCliPath;
166
+ sigintHandler;
167
+ packageVersion;
168
+ constructor() {
169
+ // Use the simplified findClaudeCli function
170
+ this.claudeCliPath = findClaudeCli(); // Removed debugMode argument
171
+ this.codexCliPath = findCodexCli();
172
+ console.error(`[Setup] Using Claude CLI command/path: ${this.claudeCliPath}`);
173
+ console.error(`[Setup] Using Codex CLI command/path: ${this.codexCliPath}`);
174
+ this.packageVersion = SERVER_VERSION;
175
+ this.server = new Server({
176
+ name: 'ai_cli_mcp',
177
+ version: SERVER_VERSION,
178
+ }, {
179
+ capabilities: {
180
+ tools: {},
181
+ },
182
+ });
183
+ this.setupToolHandlers();
184
+ this.server.onerror = (error) => console.error('[Error]', error);
185
+ this.sigintHandler = async () => {
186
+ await this.server.close();
187
+ process.exit(0);
188
+ };
189
+ process.on('SIGINT', this.sigintHandler);
190
+ }
191
+ /**
192
+ * Set up the MCP tool handlers
193
+ */
194
+ setupToolHandlers() {
195
+ // Define available tools
196
+ this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
197
+ tools: [
198
+ {
199
+ name: 'run',
200
+ description: `AI Agent Runner: Starts a Claude or Codex CLI process in the background and returns a PID immediately. Use list_processes and get_result to monitor progress.
201
+
202
+ • File ops: Create, read, (fuzzy) edit, move, copy, delete, list files, analyze/ocr images, file content analysis
203
+ • Code: Generate / analyse / refactor / fix
204
+ • Git: Stage ▸ commit ▸ push ▸ tag (any workflow)
205
+ • Terminal: Run any CLI cmd or open URLs
206
+ • Web search + summarise content on-the-fly
207
+ • Multi-step workflows & GitHub integration
208
+
209
+ **IMPORTANT**: This tool now returns immediately with a PID. Use other tools to check status and get results.
210
+
211
+ **Supported models**:
212
+ "sonnet", "opus", "haiku", "gpt-5-low", "gpt-5-medium", "gpt-5-high"
213
+
214
+ **Prompt input**: You must provide EITHER prompt (string) OR prompt_file (file path), but not both.
215
+
216
+ **Prompt tips**
217
+ 1. Be concise, explicit & step-by-step for complex tasks.
218
+ 2. Check process status with list_processes
219
+ 3. Get results with get_result using the returned PID
220
+ 4. Kill long-running processes with kill_process if needed
221
+
222
+ `,
223
+ inputSchema: {
224
+ type: 'object',
225
+ properties: {
226
+ agent: {
227
+ type: 'string',
228
+ description: 'The agent to use: "claude" or "codex". Defaults to "claude".',
229
+ enum: ['claude', 'codex'],
230
+ },
231
+ prompt: {
232
+ type: 'string',
233
+ description: 'The detailed natural language prompt for the agent to execute. Either this or prompt_file is required.',
234
+ },
235
+ prompt_file: {
236
+ type: 'string',
237
+ description: 'Path to a file containing the prompt. Either this or prompt is required. Must be an absolute path or relative to workFolder.',
238
+ },
239
+ workFolder: {
240
+ type: 'string',
241
+ description: 'The working directory for the agent execution. Must be an absolute path.',
242
+ },
243
+ model: {
244
+ type: 'string',
245
+ description: 'The model to use: "sonnet", "opus", "haiku", "gpt-5-low", "gpt-5-medium", "gpt-5-high".',
246
+ },
247
+ session_id: {
248
+ type: 'string',
249
+ description: 'Optional session ID to resume a previous session. Supported for: haiku, sonnet, opus.',
250
+ },
251
+ },
252
+ required: ['workFolder'],
253
+ },
254
+ },
255
+ {
256
+ name: 'list_processes',
257
+ description: 'List all running and completed AI agent processes with their status, PID, and basic info.',
258
+ inputSchema: {
259
+ type: 'object',
260
+ properties: {},
261
+ },
262
+ },
263
+ {
264
+ name: 'get_result',
265
+ description: 'Get the current output and status of an AI agent process by PID. Returns the output from the agent including session_id (if applicable), along with process metadata.',
266
+ inputSchema: {
267
+ type: 'object',
268
+ properties: {
269
+ pid: {
270
+ type: 'number',
271
+ description: 'The process ID returned by run tool.',
272
+ },
273
+ },
274
+ required: ['pid'],
275
+ },
276
+ },
277
+ {
278
+ name: 'kill_process',
279
+ description: 'Terminate a running AI agent process by PID.',
280
+ inputSchema: {
281
+ type: 'object',
282
+ properties: {
283
+ pid: {
284
+ type: 'number',
285
+ description: 'The process ID to terminate.',
286
+ },
287
+ },
288
+ required: ['pid'],
289
+ },
290
+ }
291
+ ],
292
+ }));
293
+ // Handle tool calls
294
+ const executionTimeoutMs = 1800000; // 30 minutes timeout
295
+ this.server.setRequestHandler(CallToolRequestSchema, async (args, call) => {
296
+ debugLog('[Debug] Handling CallToolRequest:', args);
297
+ const toolName = args.params.name;
298
+ const toolArguments = args.params.arguments || {};
299
+ switch (toolName) {
300
+ case 'run':
301
+ return this.handleRun(toolArguments);
302
+ case 'list_processes':
303
+ return this.handleListProcesses();
304
+ case 'get_result':
305
+ return this.handleGetResult(toolArguments);
306
+ case 'kill_process':
307
+ return this.handleKillProcess(toolArguments);
308
+ default:
309
+ throw new McpError(ErrorCode.MethodNotFound, `Tool ${toolName} not found`);
310
+ }
311
+ });
312
+ }
313
+ /**
314
+ * Handle run tool - starts Claude or Codex process and returns PID immediately
315
+ */
316
+ async handleRun(toolArguments) {
317
+ // Validate workFolder is required
318
+ if (!toolArguments.workFolder || typeof toolArguments.workFolder !== 'string') {
319
+ throw new McpError(ErrorCode.InvalidParams, 'Missing or invalid required parameter: workFolder');
320
+ }
321
+ // Validate that either prompt or prompt_file is provided
322
+ const hasPrompt = toolArguments.prompt && typeof toolArguments.prompt === 'string' && toolArguments.prompt.trim() !== '';
323
+ const hasPromptFile = toolArguments.prompt_file && typeof toolArguments.prompt_file === 'string' && toolArguments.prompt_file.trim() !== '';
324
+ if (!hasPrompt && !hasPromptFile) {
325
+ throw new McpError(ErrorCode.InvalidParams, 'Either prompt or prompt_file must be provided');
326
+ }
327
+ if (hasPrompt && hasPromptFile) {
328
+ throw new McpError(ErrorCode.InvalidParams, 'Cannot specify both prompt and prompt_file. Please use only one.');
329
+ }
330
+ // Determine the prompt to use
331
+ let prompt;
332
+ if (hasPrompt) {
333
+ prompt = toolArguments.prompt;
334
+ }
335
+ else {
336
+ // Read prompt from file
337
+ const promptFilePath = path.isAbsolute(toolArguments.prompt_file)
338
+ ? toolArguments.prompt_file
339
+ : pathResolve(toolArguments.workFolder, toolArguments.prompt_file);
340
+ if (!existsSync(promptFilePath)) {
341
+ throw new McpError(ErrorCode.InvalidParams, `Prompt file does not exist: ${promptFilePath}`);
342
+ }
343
+ try {
344
+ prompt = readFileSync(promptFilePath, 'utf-8');
345
+ }
346
+ catch (error) {
347
+ throw new McpError(ErrorCode.InvalidParams, `Failed to read prompt file: ${error.message}`);
348
+ }
349
+ }
350
+ // Determine working directory
351
+ const resolvedCwd = pathResolve(toolArguments.workFolder);
352
+ if (!existsSync(resolvedCwd)) {
353
+ throw new McpError(ErrorCode.InvalidParams, `Working folder does not exist: ${toolArguments.workFolder}`);
354
+ }
355
+ const effectiveCwd = resolvedCwd;
356
+ // Print version on first use
357
+ if (isFirstToolUse) {
358
+ console.error(`ai_cli_mcp v${SERVER_VERSION} started at ${serverStartupTime}`);
359
+ isFirstToolUse = false;
360
+ }
361
+ // Determine which agent to use based on model name
362
+ const model = toolArguments.model || '';
363
+ const agent = model.startsWith('gpt-') ? 'codex' : 'claude';
364
+ let cliPath;
365
+ let processArgs;
366
+ if (agent === 'codex') {
367
+ // Handle Codex
368
+ cliPath = this.codexCliPath;
369
+ processArgs = ['exec'];
370
+ // Parse model format for Codex (e.g., gpt-5-low -> model: gpt-5, effort: low)
371
+ if (toolArguments.model) {
372
+ // Split by "gpt-5-" to get the effort level
373
+ const effort = toolArguments.model.replace('gpt-5-', '');
374
+ if (effort && effort !== toolArguments.model) {
375
+ processArgs.push('-c', `model_reasoning_effort=${effort}`);
376
+ }
377
+ processArgs.push('--model', 'gpt-5');
378
+ }
379
+ processArgs.push('--full-auto', '--json', prompt);
380
+ }
381
+ else {
382
+ // Handle Claude (default)
383
+ cliPath = this.claudeCliPath;
384
+ processArgs = ['--dangerously-skip-permissions', '--output-format', 'json'];
385
+ // Add session_id if provided (Claude only)
386
+ if (toolArguments.session_id && typeof toolArguments.session_id === 'string') {
387
+ processArgs.push('-r', toolArguments.session_id);
388
+ }
389
+ processArgs.push('-p', prompt);
390
+ if (toolArguments.model && typeof toolArguments.model === 'string') {
391
+ const resolvedModel = resolveModelAlias(toolArguments.model);
392
+ processArgs.push('--model', resolvedModel);
393
+ }
394
+ }
395
+ // Spawn process without waiting
396
+ const childProcess = spawn(cliPath, processArgs, {
397
+ cwd: effectiveCwd,
398
+ stdio: ['ignore', 'pipe', 'pipe'],
399
+ detached: false
400
+ });
401
+ const pid = childProcess.pid;
402
+ if (!pid) {
403
+ throw new McpError(ErrorCode.InternalError, `Failed to start ${agent} CLI process`);
404
+ }
405
+ // Create process tracking entry
406
+ const processEntry = {
407
+ pid,
408
+ process: childProcess,
409
+ prompt,
410
+ workFolder: effectiveCwd,
411
+ model: toolArguments.model,
412
+ toolType: agent,
413
+ startTime: new Date().toISOString(),
414
+ stdout: '',
415
+ stderr: '',
416
+ status: 'running'
417
+ };
418
+ // Track the process
419
+ processManager.set(pid, processEntry);
420
+ // Set up output collection
421
+ childProcess.stdout.on('data', (data) => {
422
+ const entry = processManager.get(pid);
423
+ if (entry) {
424
+ entry.stdout += data.toString();
425
+ }
426
+ });
427
+ childProcess.stderr.on('data', (data) => {
428
+ const entry = processManager.get(pid);
429
+ if (entry) {
430
+ entry.stderr += data.toString();
431
+ }
432
+ });
433
+ childProcess.on('close', (code) => {
434
+ const entry = processManager.get(pid);
435
+ if (entry) {
436
+ entry.status = code === 0 ? 'completed' : 'failed';
437
+ entry.exitCode = code !== null ? code : undefined;
438
+ }
439
+ });
440
+ childProcess.on('error', (error) => {
441
+ const entry = processManager.get(pid);
442
+ if (entry) {
443
+ entry.status = 'failed';
444
+ entry.stderr += `\nProcess error: ${error.message}`;
445
+ }
446
+ });
447
+ // Return PID immediately
448
+ return {
449
+ content: [{
450
+ type: 'text',
451
+ text: JSON.stringify({
452
+ pid,
453
+ status: 'started',
454
+ agent,
455
+ message: `${agent} process started successfully`
456
+ }, null, 2)
457
+ }]
458
+ };
459
+ }
460
+ /**
461
+ * Handle list_processes tool
462
+ */
463
+ async handleListProcesses() {
464
+ const processes = [];
465
+ for (const [pid, process] of processManager.entries()) {
466
+ const processInfo = {
467
+ pid,
468
+ agent: process.toolType,
469
+ status: process.status,
470
+ startTime: process.startTime,
471
+ prompt: process.prompt.substring(0, 100) + (process.prompt.length > 100 ? '...' : ''),
472
+ workFolder: process.workFolder,
473
+ model: process.model,
474
+ exitCode: process.exitCode
475
+ };
476
+ // Try to extract session_id from JSON output if available
477
+ if (process.stdout) {
478
+ try {
479
+ const claudeOutput = JSON.parse(process.stdout);
480
+ if (claudeOutput.session_id) {
481
+ processInfo.session_id = claudeOutput.session_id;
482
+ }
483
+ }
484
+ catch (e) {
485
+ // Ignore parsing errors
486
+ }
487
+ }
488
+ processes.push(processInfo);
489
+ }
490
+ return {
491
+ content: [{
492
+ type: 'text',
493
+ text: JSON.stringify(processes, null, 2)
494
+ }]
495
+ };
496
+ }
497
+ /**
498
+ * Handle get_result tool
499
+ */
500
+ async handleGetResult(toolArguments) {
501
+ if (!toolArguments.pid || typeof toolArguments.pid !== 'number') {
502
+ throw new McpError(ErrorCode.InvalidParams, 'Missing or invalid required parameter: pid');
503
+ }
504
+ const pid = toolArguments.pid;
505
+ const process = processManager.get(pid);
506
+ if (!process) {
507
+ throw new McpError(ErrorCode.InvalidParams, `Process with PID ${pid} not found`);
508
+ }
509
+ // Parse output based on agent type
510
+ let agentOutput = null;
511
+ if (process.stdout) {
512
+ if (process.toolType === 'codex') {
513
+ agentOutput = parseCodexOutput(process.stdout);
514
+ }
515
+ else if (process.toolType === 'claude') {
516
+ agentOutput = parseClaudeOutput(process.stdout);
517
+ }
518
+ }
519
+ // Construct response with agent's output and process metadata
520
+ const response = {
521
+ pid,
522
+ agent: process.toolType,
523
+ status: process.status,
524
+ exitCode: process.exitCode,
525
+ startTime: process.startTime,
526
+ workFolder: process.workFolder,
527
+ prompt: process.prompt,
528
+ model: process.model
529
+ };
530
+ // If we have valid output from agent, include it
531
+ if (agentOutput) {
532
+ response.agentOutput = agentOutput;
533
+ // Extract session_id if available (Claude only)
534
+ if (process.toolType === 'claude' && agentOutput.session_id) {
535
+ response.session_id = agentOutput.session_id;
536
+ }
537
+ }
538
+ else {
539
+ // Fallback to raw output
540
+ response.stdout = process.stdout;
541
+ response.stderr = process.stderr;
542
+ }
543
+ return {
544
+ content: [{
545
+ type: 'text',
546
+ text: JSON.stringify(response, null, 2)
547
+ }]
548
+ };
549
+ }
550
+ /**
551
+ * Handle kill_process tool
552
+ */
553
+ async handleKillProcess(toolArguments) {
554
+ if (!toolArguments.pid || typeof toolArguments.pid !== 'number') {
555
+ throw new McpError(ErrorCode.InvalidParams, 'Missing or invalid required parameter: pid');
556
+ }
557
+ const pid = toolArguments.pid;
558
+ const processEntry = processManager.get(pid);
559
+ if (!processEntry) {
560
+ throw new McpError(ErrorCode.InvalidParams, `Process with PID ${pid} not found`);
561
+ }
562
+ if (processEntry.status !== 'running') {
563
+ return {
564
+ content: [{
565
+ type: 'text',
566
+ text: JSON.stringify({
567
+ pid,
568
+ status: processEntry.status,
569
+ message: 'Process already terminated'
570
+ }, null, 2)
571
+ }]
572
+ };
573
+ }
574
+ try {
575
+ processEntry.process.kill('SIGTERM');
576
+ processEntry.status = 'failed';
577
+ processEntry.stderr += '\nProcess terminated by user';
578
+ return {
579
+ content: [{
580
+ type: 'text',
581
+ text: JSON.stringify({
582
+ pid,
583
+ status: 'terminated',
584
+ message: 'Process terminated successfully'
585
+ }, null, 2)
586
+ }]
587
+ };
588
+ }
589
+ catch (error) {
590
+ throw new McpError(ErrorCode.InternalError, `Failed to terminate process: ${error.message}`);
591
+ }
592
+ }
593
+ /**
594
+ * Start the MCP server
595
+ */
596
+ async run() {
597
+ // Revert to original server start logic if listen caused errors
598
+ const transport = new StdioServerTransport();
599
+ await this.server.connect(transport);
600
+ console.error('AI CLI MCP server running on stdio');
601
+ }
602
+ /**
603
+ * Clean up resources (for testing)
604
+ */
605
+ async cleanup() {
606
+ if (this.sigintHandler) {
607
+ process.removeListener('SIGINT', this.sigintHandler);
608
+ }
609
+ await this.server.close();
610
+ }
611
+ }
612
+ // Create and run the server if this is the main module
613
+ const server = new ClaudeCodeServer();
614
+ server.run().catch(console.error);
@@ -0,0 +1,26 @@
1
+ # Release Checklist
2
+
3
+ ## Pre-Release Checks
4
+
5
+ - [ ] Tests are green on GitHub CI
6
+ - [ ] Run linter locally (`npm run lint`)
7
+ - [ ] Run type checker locally (`npm run typecheck`)
8
+ - [ ] Run tests locally (`npm test`)
9
+ - [ ] Run build locally (`npm run build`)
10
+ - [ ] Changelog version has been increased
11
+ - [ ] Changelog entries for the new version are written
12
+ - [ ] Version in `server.ts` (hardcoded) is updated
13
+ - [ ] Version in `package.json` is updated
14
+
15
+ ## Local Verification
16
+
17
+ - [ ] Install npm package locally (`npm pack && npm install -g <package-name>-<version>.tgz`)
18
+ - [ ] Test the locally installed package using the npm inspector (automated tests)
19
+
20
+ ## Release Steps
21
+
22
+ - [ ] Push all changes to the main branch
23
+ - [ ] Create a git tag for the version (e.g., `git tag v1.2.3`)
24
+ - [ ] Push the git tag (e.g., `git push origin v1.2.3`)
25
+ - [ ] Publish to npm (`npm publish`)
26
+ - [ ] Create a GitHub Release based on the tag, including changelog notes