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