ai-cli-mcp 2.3.0 → 2.3.1

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 (36) hide show
  1. package/.claude/settings.local.json +2 -1
  2. package/dist/__tests__/e2e.test.js +232 -0
  3. package/dist/__tests__/edge-cases.test.js +135 -0
  4. package/dist/__tests__/error-cases.test.js +291 -0
  5. package/dist/__tests__/mocks.js +32 -0
  6. package/dist/__tests__/model-alias.test.js +36 -0
  7. package/dist/__tests__/process-management.test.js +630 -0
  8. package/dist/__tests__/server.test.js +681 -0
  9. package/dist/__tests__/setup.js +11 -0
  10. package/dist/__tests__/utils/claude-mock.js +80 -0
  11. package/dist/__tests__/utils/mcp-client.js +104 -0
  12. package/dist/__tests__/utils/persistent-mock.js +25 -0
  13. package/dist/__tests__/utils/test-helpers.js +11 -0
  14. package/dist/__tests__/validation.test.js +235 -0
  15. package/dist/__tests__/version-print.test.js +69 -0
  16. package/dist/__tests__/wait.test.js +229 -0
  17. package/dist/parsers.js +68 -0
  18. package/dist/server.js +774 -0
  19. package/package.json +1 -1
  20. package/src/__tests__/e2e.test.ts +16 -24
  21. package/src/__tests__/error-cases.test.ts +8 -17
  22. package/src/__tests__/process-management.test.ts +22 -24
  23. package/src/__tests__/validation.test.ts +58 -36
  24. package/src/server.ts +6 -2
  25. package/data/rooms/refactor-haiku-alias-main/messages.jsonl +0 -5
  26. package/data/rooms/refactor-haiku-alias-main/presence.json +0 -20
  27. package/data/rooms.json +0 -10
  28. package/hello.txt +0 -3
  29. package/implementation-log.md +0 -110
  30. package/implementation-plan.md +0 -189
  31. package/investigation-report.md +0 -135
  32. package/quality-score.json +0 -47
  33. package/refactoring-requirements.md +0 -25
  34. package/review-report.md +0 -132
  35. package/test-results.md +0 -119
  36. package/xx.txt +0 -1
package/dist/server.js ADDED
@@ -0,0 +1,774 @@
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 { fileURLToPath } from 'node:url';
10
+ import * as path from 'path';
11
+ import { parseCodexOutput, parseClaudeOutput, parseGeminiOutput } from './parsers.js';
12
+ // Server version - update this when releasing new versions
13
+ const SERVER_VERSION = "2.2.0";
14
+ // Model alias mappings for user-friendly model names
15
+ const MODEL_ALIASES = {
16
+ 'haiku': 'claude-3-5-haiku-20241022'
17
+ };
18
+ // Define debugMode globally using const
19
+ const debugMode = process.env.MCP_CLAUDE_DEBUG === 'true';
20
+ // Track if this is the first tool use for version printing
21
+ let isFirstToolUse = true;
22
+ // Capture server startup time when the module loads
23
+ const serverStartupTime = new Date().toISOString();
24
+ // Global process manager
25
+ const processManager = new Map();
26
+ // Dedicated debug logging function
27
+ export function debugLog(message, ...optionalParams) {
28
+ if (debugMode) {
29
+ console.error(message, ...optionalParams);
30
+ }
31
+ }
32
+ /**
33
+ * Determine the Gemini CLI command/path.
34
+ * Similar to findClaudeCli but for Gemini
35
+ */
36
+ export function findGeminiCli() {
37
+ debugLog('[Debug] Attempting to find Gemini CLI...');
38
+ // Check for custom CLI name from environment variable
39
+ const customCliName = process.env.GEMINI_CLI_NAME;
40
+ if (customCliName) {
41
+ debugLog(`[Debug] Using custom Gemini CLI name from GEMINI_CLI_NAME: ${customCliName}`);
42
+ // If it's an absolute path, use it directly
43
+ if (path.isAbsolute(customCliName)) {
44
+ debugLog(`[Debug] GEMINI_CLI_NAME is an absolute path: ${customCliName}`);
45
+ return customCliName;
46
+ }
47
+ // If it starts with ~ or ./, reject as relative paths are not allowed
48
+ if (customCliName.startsWith('./') || customCliName.startsWith('../') || customCliName.includes('/')) {
49
+ throw new Error(`Invalid GEMINI_CLI_NAME: Relative paths are not allowed. Use either a simple name (e.g., 'gemini') or an absolute path (e.g., '/tmp/gemini-test')`);
50
+ }
51
+ }
52
+ const cliName = customCliName || 'gemini';
53
+ // Try local install path: ~/.gemini/local/gemini
54
+ const userPath = join(homedir(), '.gemini', 'local', 'gemini');
55
+ debugLog(`[Debug] Checking for Gemini CLI at local user path: ${userPath}`);
56
+ if (existsSync(userPath)) {
57
+ debugLog(`[Debug] Found Gemini CLI at local user path: ${userPath}. Using this path.`);
58
+ return userPath;
59
+ }
60
+ else {
61
+ debugLog(`[Debug] Gemini CLI not found at local user path: ${userPath}.`);
62
+ }
63
+ // Fallback to CLI name (PATH lookup)
64
+ debugLog(`[Debug] Falling back to "${cliName}" command name, relying on spawn/PATH lookup.`);
65
+ console.warn(`[Warning] Gemini CLI not found at ~/.gemini/local/gemini. Falling back to "${cliName}" in PATH. Ensure it is installed and accessible.`);
66
+ return cliName;
67
+ }
68
+ /**
69
+ * Determine the Codex CLI command/path.
70
+ * Similar to findClaudeCli but for Codex
71
+ */
72
+ export function findCodexCli() {
73
+ debugLog('[Debug] Attempting to find Codex CLI...');
74
+ // Check for custom CLI name from environment variable
75
+ const customCliName = process.env.CODEX_CLI_NAME;
76
+ if (customCliName) {
77
+ debugLog(`[Debug] Using custom Codex CLI name from CODEX_CLI_NAME: ${customCliName}`);
78
+ // If it's an absolute path, use it directly
79
+ if (path.isAbsolute(customCliName)) {
80
+ debugLog(`[Debug] CODEX_CLI_NAME is an absolute path: ${customCliName}`);
81
+ return customCliName;
82
+ }
83
+ // If it starts with ~ or ./, reject as relative paths are not allowed
84
+ if (customCliName.startsWith('./') || customCliName.startsWith('../') || customCliName.includes('/')) {
85
+ 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')`);
86
+ }
87
+ }
88
+ const cliName = customCliName || 'codex';
89
+ // Try local install path: ~/.codex/local/codex
90
+ const userPath = join(homedir(), '.codex', 'local', 'codex');
91
+ debugLog(`[Debug] Checking for Codex CLI at local user path: ${userPath}`);
92
+ if (existsSync(userPath)) {
93
+ debugLog(`[Debug] Found Codex CLI at local user path: ${userPath}. Using this path.`);
94
+ return userPath;
95
+ }
96
+ else {
97
+ debugLog(`[Debug] Codex CLI not found at local user path: ${userPath}.`);
98
+ }
99
+ // Fallback to CLI name (PATH lookup)
100
+ debugLog(`[Debug] Falling back to "${cliName}" command name, relying on spawn/PATH lookup.`);
101
+ console.warn(`[Warning] Codex CLI not found at ~/.codex/local/codex. Falling back to "${cliName}" in PATH. Ensure it is installed and accessible.`);
102
+ return cliName;
103
+ }
104
+ /**
105
+ * Determine the Claude CLI command/path.
106
+ * 1. Checks for CLAUDE_CLI_NAME environment variable:
107
+ * - If absolute path, uses it directly
108
+ * - If relative path, throws error
109
+ * - If simple name, continues with path resolution
110
+ * 2. Checks for Claude CLI at the local user path: ~/.claude/local/claude.
111
+ * 3. If not found, defaults to the CLI name (or 'claude'), relying on the system's PATH for lookup.
112
+ */
113
+ export function findClaudeCli() {
114
+ debugLog('[Debug] Attempting to find Claude CLI...');
115
+ // Check for custom CLI name from environment variable
116
+ const customCliName = process.env.CLAUDE_CLI_NAME;
117
+ if (customCliName) {
118
+ debugLog(`[Debug] Using custom Claude CLI name from CLAUDE_CLI_NAME: ${customCliName}`);
119
+ // If it's an absolute path, use it directly
120
+ if (path.isAbsolute(customCliName)) {
121
+ debugLog(`[Debug] CLAUDE_CLI_NAME is an absolute path: ${customCliName}`);
122
+ return customCliName;
123
+ }
124
+ // If it starts with ~ or ./, reject as relative paths are not allowed
125
+ if (customCliName.startsWith('./') || customCliName.startsWith('../') || customCliName.includes('/')) {
126
+ 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')`);
127
+ }
128
+ }
129
+ const cliName = customCliName || 'claude';
130
+ // Try local install path: ~/.claude/local/claude (using the original name for local installs)
131
+ const userPath = join(homedir(), '.claude', 'local', 'claude');
132
+ debugLog(`[Debug] Checking for Claude CLI at local user path: ${userPath}`);
133
+ if (existsSync(userPath)) {
134
+ debugLog(`[Debug] Found Claude CLI at local user path: ${userPath}. Using this path.`);
135
+ return userPath;
136
+ }
137
+ else {
138
+ debugLog(`[Debug] Claude CLI not found at local user path: ${userPath}.`);
139
+ }
140
+ // 3. Fallback to CLI name (PATH lookup)
141
+ debugLog(`[Debug] Falling back to "${cliName}" command name, relying on spawn/PATH lookup.`);
142
+ console.warn(`[Warning] Claude CLI not found at ~/.claude/local/claude. Falling back to "${cliName}" in PATH. Ensure it is installed and accessible.`);
143
+ return cliName;
144
+ }
145
+ /**
146
+ * Resolves model aliases to their full model names
147
+ * @param model - The model name or alias to resolve
148
+ * @returns The full model name, or the original value if no alias exists
149
+ */
150
+ export function resolveModelAlias(model) {
151
+ return MODEL_ALIASES[model] || model;
152
+ }
153
+ // Ensure spawnAsync is defined correctly *before* the class
154
+ export async function spawnAsync(command, args, options) {
155
+ return new Promise((resolve, reject) => {
156
+ debugLog(`[Spawn] Running command: ${command} ${args.join(' ')}`);
157
+ const process = spawn(command, args, {
158
+ shell: false, // Reverted to false
159
+ timeout: options?.timeout,
160
+ cwd: options?.cwd,
161
+ stdio: ['ignore', 'pipe', 'pipe']
162
+ });
163
+ let stdout = '';
164
+ let stderr = '';
165
+ process.stdout.on('data', (data) => { stdout += data.toString(); });
166
+ process.stderr.on('data', (data) => {
167
+ stderr += data.toString();
168
+ debugLog(`[Spawn Stderr Chunk] ${data.toString()}`);
169
+ });
170
+ process.on('error', (error) => {
171
+ debugLog(`[Spawn Error Event] Full error object:`, error);
172
+ let errorMessage = `Spawn error: ${error.message}`;
173
+ if (error.path) {
174
+ errorMessage += ` | Path: ${error.path}`;
175
+ }
176
+ if (error.syscall) {
177
+ errorMessage += ` | Syscall: ${error.syscall}`;
178
+ }
179
+ errorMessage += `\nStderr: ${stderr.trim()}`;
180
+ reject(new Error(errorMessage));
181
+ });
182
+ process.on('close', (code) => {
183
+ debugLog(`[Spawn Close] Exit code: ${code}`);
184
+ debugLog(`[Spawn Stderr Full] ${stderr.trim()}`);
185
+ debugLog(`[Spawn Stdout Full] ${stdout.trim()}`);
186
+ if (code === 0) {
187
+ resolve({ stdout, stderr });
188
+ }
189
+ else {
190
+ reject(new Error(`Command failed with exit code ${code}\nStderr: ${stderr.trim()}\nStdout: ${stdout.trim()}`));
191
+ }
192
+ });
193
+ });
194
+ }
195
+ /**
196
+ * MCP Server for Claude Code
197
+ * Provides a simple MCP tool to run Claude CLI in one-shot mode
198
+ */
199
+ export class ClaudeCodeServer {
200
+ server;
201
+ claudeCliPath;
202
+ codexCliPath;
203
+ geminiCliPath;
204
+ sigintHandler;
205
+ packageVersion;
206
+ constructor() {
207
+ // Use the simplified findClaudeCli function
208
+ this.claudeCliPath = findClaudeCli(); // Removed debugMode argument
209
+ this.codexCliPath = findCodexCli();
210
+ this.geminiCliPath = findGeminiCli();
211
+ console.error(`[Setup] Using Claude CLI command/path: ${this.claudeCliPath}`);
212
+ console.error(`[Setup] Using Codex CLI command/path: ${this.codexCliPath}`);
213
+ console.error(`[Setup] Using Gemini CLI command/path: ${this.geminiCliPath}`);
214
+ this.packageVersion = SERVER_VERSION;
215
+ this.server = new Server({
216
+ name: 'ai_cli_mcp',
217
+ version: SERVER_VERSION,
218
+ }, {
219
+ capabilities: {
220
+ tools: {},
221
+ },
222
+ });
223
+ this.setupToolHandlers();
224
+ this.server.onerror = (error) => console.error('[Error]', error);
225
+ this.sigintHandler = async () => {
226
+ await this.server.close();
227
+ process.exit(0);
228
+ };
229
+ process.on('SIGINT', this.sigintHandler);
230
+ }
231
+ /**
232
+ * Set up the MCP tool handlers
233
+ */
234
+ setupToolHandlers() {
235
+ // Define available tools
236
+ this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
237
+ tools: [
238
+ {
239
+ name: 'run',
240
+ description: `AI Agent Runner: Starts a Claude, Codex, or Gemini CLI process in the background and returns a PID immediately. Use list_processes and get_result to monitor progress.
241
+
242
+ • File ops: Create, read, (fuzzy) edit, move, copy, delete, list files, analyze/ocr images, file content analysis
243
+ • Code: Generate / analyse / refactor / fix
244
+ • Git: Stage ▸ commit ▸ push ▸ tag (any workflow)
245
+ • Terminal: Run any CLI cmd or open URLs
246
+ • Web search + summarise content on-the-fly
247
+ • Multi-step workflows & GitHub integration
248
+
249
+ **IMPORTANT**: This tool now returns immediately with a PID. Use other tools to check status and get results.
250
+
251
+ **Supported models**:
252
+ "sonnet", "opus", "haiku", "gpt-5-low", "gpt-5-medium", "gpt-5-high", "gemini-2.5-pro", "gemini-2.5-flash", "gemini-3-pro-preview"
253
+
254
+ **Prompt input**: You must provide EITHER prompt (string) OR prompt_file (file path), but not both.
255
+
256
+ **Prompt tips**
257
+ 1. Be concise, explicit & step-by-step for complex tasks.
258
+ 2. Check process status with list_processes
259
+ 3. Get results with get_result using the returned PID
260
+ 4. Kill long-running processes with kill_process if needed
261
+
262
+ `,
263
+ inputSchema: {
264
+ type: 'object',
265
+ properties: {
266
+ prompt: {
267
+ type: 'string',
268
+ description: 'The detailed natural language prompt for the agent to execute. Either this or prompt_file is required.',
269
+ },
270
+ prompt_file: {
271
+ type: 'string',
272
+ description: 'Path to a file containing the prompt. Either this or prompt is required. Must be an absolute path or relative to workFolder.',
273
+ },
274
+ workFolder: {
275
+ type: 'string',
276
+ description: 'The working directory for the agent execution. Must be an absolute path.',
277
+ },
278
+ model: {
279
+ type: 'string',
280
+ description: 'The model to use: "sonnet", "opus", "haiku", "gpt-5-low", "gpt-5-medium", "gpt-5-high", "gemini-2.5-pro", "gemini-2.5-flash", "gemini-3-pro-preview".',
281
+ },
282
+ session_id: {
283
+ type: 'string',
284
+ description: 'Optional session ID to resume a previous session. Supported for: haiku, sonnet, opus, gemini-2.5-pro, gemini-2.5-flash, gemini-3-pro-preview.',
285
+ },
286
+ },
287
+ required: ['workFolder'],
288
+ },
289
+ },
290
+ {
291
+ name: 'list_processes',
292
+ description: 'List all running and completed AI agent processes. Returns a simple list with PID, agent type, and status for each process.',
293
+ inputSchema: {
294
+ type: 'object',
295
+ properties: {},
296
+ },
297
+ },
298
+ {
299
+ name: 'get_result',
300
+ 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.',
301
+ inputSchema: {
302
+ type: 'object',
303
+ properties: {
304
+ pid: {
305
+ type: 'number',
306
+ description: 'The process ID returned by run tool.',
307
+ },
308
+ },
309
+ required: ['pid'],
310
+ },
311
+ },
312
+ {
313
+ name: 'wait',
314
+ description: 'Wait for multiple AI agent processes to complete and return their results. Blocks until all specified PIDs finish or timeout occurs.',
315
+ inputSchema: {
316
+ type: 'object',
317
+ properties: {
318
+ pids: {
319
+ type: 'array',
320
+ items: { type: 'number' },
321
+ description: 'List of process IDs to wait for (returned by the run tool).',
322
+ },
323
+ timeout: {
324
+ type: 'number',
325
+ description: 'Optional: Maximum time to wait in seconds. Defaults to 180 (3 minutes).',
326
+ },
327
+ },
328
+ required: ['pids'],
329
+ },
330
+ },
331
+ {
332
+ name: 'kill_process',
333
+ description: 'Terminate a running AI agent process by PID.',
334
+ inputSchema: {
335
+ type: 'object',
336
+ properties: {
337
+ pid: {
338
+ type: 'number',
339
+ description: 'The process ID to terminate.',
340
+ },
341
+ },
342
+ required: ['pid'],
343
+ },
344
+ },
345
+ {
346
+ name: 'cleanup_processes',
347
+ description: 'Remove all completed and failed processes from the process list to free up memory.',
348
+ inputSchema: {
349
+ type: 'object',
350
+ properties: {},
351
+ },
352
+ }
353
+ ],
354
+ }));
355
+ // Handle tool calls
356
+ const executionTimeoutMs = 1800000; // 30 minutes timeout
357
+ this.server.setRequestHandler(CallToolRequestSchema, async (args, call) => {
358
+ debugLog('[Debug] Handling CallToolRequest:', args);
359
+ const toolName = args.params.name;
360
+ const toolArguments = args.params.arguments || {};
361
+ switch (toolName) {
362
+ case 'run':
363
+ return this.handleRun(toolArguments);
364
+ case 'list_processes':
365
+ return this.handleListProcesses();
366
+ case 'get_result':
367
+ return this.handleGetResult(toolArguments);
368
+ case 'wait':
369
+ return this.handleWait(toolArguments);
370
+ case 'kill_process':
371
+ return this.handleKillProcess(toolArguments);
372
+ case 'cleanup_processes':
373
+ return this.handleCleanupProcesses();
374
+ default:
375
+ throw new McpError(ErrorCode.MethodNotFound, `Tool ${toolName} not found`);
376
+ }
377
+ });
378
+ }
379
+ /**
380
+ * Handle run tool - starts Claude or Codex process and returns PID immediately
381
+ */
382
+ async handleRun(toolArguments) {
383
+ // Validate workFolder is required
384
+ if (!toolArguments.workFolder || typeof toolArguments.workFolder !== 'string') {
385
+ throw new McpError(ErrorCode.InvalidParams, 'Missing or invalid required parameter: workFolder');
386
+ }
387
+ // Validate that either prompt or prompt_file is provided
388
+ const hasPrompt = toolArguments.prompt && typeof toolArguments.prompt === 'string' && toolArguments.prompt.trim() !== '';
389
+ const hasPromptFile = toolArguments.prompt_file && typeof toolArguments.prompt_file === 'string' && toolArguments.prompt_file.trim() !== '';
390
+ if (!hasPrompt && !hasPromptFile) {
391
+ throw new McpError(ErrorCode.InvalidParams, 'Either prompt or prompt_file must be provided');
392
+ }
393
+ if (hasPrompt && hasPromptFile) {
394
+ throw new McpError(ErrorCode.InvalidParams, 'Cannot specify both prompt and prompt_file. Please use only one.');
395
+ }
396
+ // Determine the prompt to use
397
+ let prompt;
398
+ if (hasPrompt) {
399
+ prompt = toolArguments.prompt;
400
+ }
401
+ else {
402
+ // Read prompt from file
403
+ const promptFilePath = path.isAbsolute(toolArguments.prompt_file)
404
+ ? toolArguments.prompt_file
405
+ : pathResolve(toolArguments.workFolder, toolArguments.prompt_file);
406
+ if (!existsSync(promptFilePath)) {
407
+ throw new McpError(ErrorCode.InvalidParams, `Prompt file does not exist: ${promptFilePath}`);
408
+ }
409
+ try {
410
+ prompt = readFileSync(promptFilePath, 'utf-8');
411
+ }
412
+ catch (error) {
413
+ throw new McpError(ErrorCode.InvalidParams, `Failed to read prompt file: ${error.message}`);
414
+ }
415
+ }
416
+ // Determine working directory
417
+ const resolvedCwd = pathResolve(toolArguments.workFolder);
418
+ if (!existsSync(resolvedCwd)) {
419
+ throw new McpError(ErrorCode.InvalidParams, `Working folder does not exist: ${toolArguments.workFolder}`);
420
+ }
421
+ const effectiveCwd = resolvedCwd;
422
+ // Print version on first use
423
+ if (isFirstToolUse) {
424
+ console.error(`ai_cli_mcp v${SERVER_VERSION} started at ${serverStartupTime}`);
425
+ isFirstToolUse = false;
426
+ }
427
+ // Determine which agent to use based on model name
428
+ const model = toolArguments.model || '';
429
+ let agent;
430
+ if (model.startsWith('gpt-')) {
431
+ agent = 'codex';
432
+ }
433
+ else if (model.startsWith('gemini')) {
434
+ agent = 'gemini';
435
+ }
436
+ else {
437
+ agent = 'claude';
438
+ }
439
+ let cliPath;
440
+ let processArgs;
441
+ if (agent === 'codex') {
442
+ // Handle Codex
443
+ cliPath = this.codexCliPath;
444
+ processArgs = ['exec'];
445
+ // Parse model format for Codex (e.g., gpt-5-low -> model: gpt-5, effort: low)
446
+ if (toolArguments.model) {
447
+ // Split by "gpt-5-" to get the effort level
448
+ const effort = toolArguments.model.replace('gpt-5-', '');
449
+ if (effort && effort !== toolArguments.model) {
450
+ processArgs.push('-c', `model_reasoning_effort=${effort}`);
451
+ }
452
+ processArgs.push('--model', 'gpt-5');
453
+ }
454
+ processArgs.push('--full-auto', '--json', prompt);
455
+ }
456
+ else if (agent === 'gemini') {
457
+ // Handle Gemini
458
+ cliPath = this.geminiCliPath;
459
+ processArgs = ['-y', '--output-format', 'json'];
460
+ // Add session_id if provided
461
+ if (toolArguments.session_id && typeof toolArguments.session_id === 'string') {
462
+ processArgs.push('-r', toolArguments.session_id);
463
+ }
464
+ // Add model if specified
465
+ if (toolArguments.model) {
466
+ processArgs.push('--model', toolArguments.model);
467
+ }
468
+ // Add prompt as positional argument
469
+ processArgs.push(prompt);
470
+ }
471
+ else {
472
+ // Handle Claude (default)
473
+ cliPath = this.claudeCliPath;
474
+ processArgs = ['--dangerously-skip-permissions', '--output-format', 'json'];
475
+ // Add session_id if provided (Claude only)
476
+ if (toolArguments.session_id && typeof toolArguments.session_id === 'string') {
477
+ processArgs.push('-r', toolArguments.session_id);
478
+ }
479
+ processArgs.push('-p', prompt);
480
+ if (toolArguments.model && typeof toolArguments.model === 'string') {
481
+ const resolvedModel = resolveModelAlias(toolArguments.model);
482
+ processArgs.push('--model', resolvedModel);
483
+ }
484
+ }
485
+ // Spawn process without waiting
486
+ const childProcess = spawn(cliPath, processArgs, {
487
+ cwd: effectiveCwd,
488
+ stdio: ['ignore', 'pipe', 'pipe'],
489
+ detached: false
490
+ });
491
+ const pid = childProcess.pid;
492
+ if (!pid) {
493
+ throw new McpError(ErrorCode.InternalError, `Failed to start ${agent} CLI process`);
494
+ }
495
+ // Create process tracking entry
496
+ const processEntry = {
497
+ pid,
498
+ process: childProcess,
499
+ prompt,
500
+ workFolder: effectiveCwd,
501
+ model: toolArguments.model,
502
+ toolType: agent,
503
+ startTime: new Date().toISOString(),
504
+ stdout: '',
505
+ stderr: '',
506
+ status: 'running'
507
+ };
508
+ // Track the process
509
+ processManager.set(pid, processEntry);
510
+ // Set up output collection
511
+ childProcess.stdout.on('data', (data) => {
512
+ const entry = processManager.get(pid);
513
+ if (entry) {
514
+ entry.stdout += data.toString();
515
+ }
516
+ });
517
+ childProcess.stderr.on('data', (data) => {
518
+ const entry = processManager.get(pid);
519
+ if (entry) {
520
+ entry.stderr += data.toString();
521
+ }
522
+ });
523
+ childProcess.on('close', (code) => {
524
+ const entry = processManager.get(pid);
525
+ if (entry) {
526
+ entry.status = code === 0 ? 'completed' : 'failed';
527
+ entry.exitCode = code !== null ? code : undefined;
528
+ }
529
+ });
530
+ childProcess.on('error', (error) => {
531
+ const entry = processManager.get(pid);
532
+ if (entry) {
533
+ entry.status = 'failed';
534
+ entry.stderr += `\nProcess error: ${error.message}`;
535
+ }
536
+ });
537
+ // Return PID immediately
538
+ return {
539
+ content: [{
540
+ type: 'text',
541
+ text: JSON.stringify({
542
+ pid,
543
+ status: 'started',
544
+ agent,
545
+ message: `${agent} process started successfully`
546
+ }, null, 2)
547
+ }]
548
+ };
549
+ }
550
+ /**
551
+ * Handle list_processes tool
552
+ */
553
+ async handleListProcesses() {
554
+ const processes = [];
555
+ for (const [pid, process] of processManager.entries()) {
556
+ const processInfo = {
557
+ pid,
558
+ agent: process.toolType,
559
+ status: process.status
560
+ };
561
+ processes.push(processInfo);
562
+ }
563
+ return {
564
+ content: [{
565
+ type: 'text',
566
+ text: JSON.stringify(processes, null, 2)
567
+ }]
568
+ };
569
+ }
570
+ /**
571
+ * Helper to get process result object
572
+ */
573
+ getProcessResultHelper(pid) {
574
+ const process = processManager.get(pid);
575
+ if (!process) {
576
+ throw new McpError(ErrorCode.InvalidParams, `Process with PID ${pid} not found`);
577
+ }
578
+ // Parse output based on agent type
579
+ let agentOutput = null;
580
+ if (process.stdout) {
581
+ if (process.toolType === 'codex') {
582
+ agentOutput = parseCodexOutput(process.stdout);
583
+ }
584
+ else if (process.toolType === 'claude') {
585
+ agentOutput = parseClaudeOutput(process.stdout);
586
+ }
587
+ else if (process.toolType === 'gemini') {
588
+ agentOutput = parseGeminiOutput(process.stdout);
589
+ }
590
+ }
591
+ // Construct response with agent's output and process metadata
592
+ const response = {
593
+ pid,
594
+ agent: process.toolType,
595
+ status: process.status,
596
+ exitCode: process.exitCode,
597
+ startTime: process.startTime,
598
+ workFolder: process.workFolder,
599
+ prompt: process.prompt,
600
+ model: process.model
601
+ };
602
+ // If we have valid output from agent, include it
603
+ if (agentOutput) {
604
+ response.agentOutput = agentOutput;
605
+ // Extract session_id if available (Claude and Gemini)
606
+ if ((process.toolType === 'claude' || process.toolType === 'gemini') && agentOutput.session_id) {
607
+ response.session_id = agentOutput.session_id;
608
+ }
609
+ }
610
+ else {
611
+ // Fallback to raw output
612
+ response.stdout = process.stdout;
613
+ response.stderr = process.stderr;
614
+ }
615
+ return response;
616
+ }
617
+ /**
618
+ * Handle get_result tool
619
+ */
620
+ async handleGetResult(toolArguments) {
621
+ if (!toolArguments.pid || typeof toolArguments.pid !== 'number') {
622
+ throw new McpError(ErrorCode.InvalidParams, 'Missing or invalid required parameter: pid');
623
+ }
624
+ const pid = toolArguments.pid;
625
+ const response = this.getProcessResultHelper(pid);
626
+ return {
627
+ content: [{
628
+ type: 'text',
629
+ text: JSON.stringify(response, null, 2)
630
+ }]
631
+ };
632
+ }
633
+ /**
634
+ * Handle wait tool
635
+ */
636
+ async handleWait(toolArguments) {
637
+ if (!toolArguments.pids || !Array.isArray(toolArguments.pids) || toolArguments.pids.length === 0) {
638
+ throw new McpError(ErrorCode.InvalidParams, 'Missing or invalid required parameter: pids (must be a non-empty array of numbers)');
639
+ }
640
+ const pids = toolArguments.pids;
641
+ // Default timeout: 3 minutes (180 seconds)
642
+ const timeoutSeconds = typeof toolArguments.timeout === 'number' ? toolArguments.timeout : 180;
643
+ const timeoutMs = timeoutSeconds * 1000;
644
+ // Validate all PIDs exist first
645
+ for (const pid of pids) {
646
+ if (!processManager.has(pid)) {
647
+ throw new McpError(ErrorCode.InvalidParams, `Process with PID ${pid} not found`);
648
+ }
649
+ }
650
+ // Create promises for each process
651
+ const waitPromises = pids.map(pid => {
652
+ const processEntry = processManager.get(pid);
653
+ if (processEntry.status !== 'running') {
654
+ return Promise.resolve();
655
+ }
656
+ return new Promise((resolve) => {
657
+ processEntry.process.once('close', () => {
658
+ resolve();
659
+ });
660
+ });
661
+ });
662
+ // Create a timeout promise
663
+ const timeoutPromise = new Promise((_, reject) => {
664
+ setTimeout(() => {
665
+ reject(new Error(`Timed out after ${timeoutSeconds} seconds waiting for processes`));
666
+ }, timeoutMs);
667
+ });
668
+ try {
669
+ // Wait for all processes to finish or timeout
670
+ await Promise.race([Promise.all(waitPromises), timeoutPromise]);
671
+ }
672
+ catch (error) {
673
+ throw new McpError(ErrorCode.InternalError, error.message);
674
+ }
675
+ // Collect results
676
+ const results = pids.map(pid => this.getProcessResultHelper(pid));
677
+ return {
678
+ content: [{
679
+ type: 'text',
680
+ text: JSON.stringify(results, null, 2)
681
+ }]
682
+ };
683
+ }
684
+ /**
685
+ * Handle kill_process tool
686
+ */
687
+ async handleKillProcess(toolArguments) {
688
+ if (!toolArguments.pid || typeof toolArguments.pid !== 'number') {
689
+ throw new McpError(ErrorCode.InvalidParams, 'Missing or invalid required parameter: pid');
690
+ }
691
+ const pid = toolArguments.pid;
692
+ const processEntry = processManager.get(pid);
693
+ if (!processEntry) {
694
+ throw new McpError(ErrorCode.InvalidParams, `Process with PID ${pid} not found`);
695
+ }
696
+ if (processEntry.status !== 'running') {
697
+ return {
698
+ content: [{
699
+ type: 'text',
700
+ text: JSON.stringify({
701
+ pid,
702
+ status: processEntry.status,
703
+ message: 'Process already terminated'
704
+ }, null, 2)
705
+ }]
706
+ };
707
+ }
708
+ try {
709
+ processEntry.process.kill('SIGTERM');
710
+ processEntry.status = 'failed';
711
+ processEntry.stderr += '\nProcess terminated by user';
712
+ return {
713
+ content: [{
714
+ type: 'text',
715
+ text: JSON.stringify({
716
+ pid,
717
+ status: 'terminated',
718
+ message: 'Process terminated successfully'
719
+ }, null, 2)
720
+ }]
721
+ };
722
+ }
723
+ catch (error) {
724
+ throw new McpError(ErrorCode.InternalError, `Failed to terminate process: ${error.message}`);
725
+ }
726
+ }
727
+ /**
728
+ * Handle cleanup_processes tool
729
+ */
730
+ async handleCleanupProcesses() {
731
+ const removedPids = [];
732
+ // Iterate through all processes and collect PIDs to remove
733
+ for (const [pid, process] of processManager.entries()) {
734
+ if (process.status === 'completed' || process.status === 'failed') {
735
+ removedPids.push(pid);
736
+ processManager.delete(pid);
737
+ }
738
+ }
739
+ return {
740
+ content: [{
741
+ type: 'text',
742
+ text: JSON.stringify({
743
+ removed: removedPids.length,
744
+ removedPids,
745
+ message: `Cleaned up ${removedPids.length} finished process(es)`
746
+ }, null, 2)
747
+ }]
748
+ };
749
+ }
750
+ /**
751
+ * Start the MCP server
752
+ */
753
+ async run() {
754
+ // Revert to original server start logic if listen caused errors
755
+ const transport = new StdioServerTransport();
756
+ await this.server.connect(transport);
757
+ console.error('AI CLI MCP server running on stdio');
758
+ }
759
+ /**
760
+ * Clean up resources (for testing)
761
+ */
762
+ async cleanup() {
763
+ if (this.sigintHandler) {
764
+ process.removeListener('SIGINT', this.sigintHandler);
765
+ }
766
+ await this.server.close();
767
+ }
768
+ }
769
+ // Create and run the server if this is the main module
770
+ const __filename = fileURLToPath(import.meta.url);
771
+ if (process.argv[1] === __filename) {
772
+ const server = new ClaudeCodeServer();
773
+ server.run().catch(console.error);
774
+ }