ai-cli-mcp 2.1.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,671 +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.0.1";
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 with their status, PID, and basic info.',
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
- }));
327
- // Handle tool calls
328
- const executionTimeoutMs = 1800000; // 30 minutes timeout
329
- this.server.setRequestHandler(CallToolRequestSchema, async (args, call) => {
330
- debugLog('[Debug] Handling CallToolRequest:', args);
331
- const toolName = args.params.name;
332
- const toolArguments = args.params.arguments || {};
333
- switch (toolName) {
334
- case 'run':
335
- return this.handleRun(toolArguments);
336
- case 'list_processes':
337
- return this.handleListProcesses();
338
- case 'get_result':
339
- return this.handleGetResult(toolArguments);
340
- case 'kill_process':
341
- return this.handleKillProcess(toolArguments);
342
- default:
343
- throw new McpError(ErrorCode.MethodNotFound, `Tool ${toolName} not found`);
344
- }
345
- });
346
- }
347
- /**
348
- * Handle run tool - starts Claude or Codex process and returns PID immediately
349
- */
350
- async handleRun(toolArguments) {
351
- // Validate workFolder is required
352
- if (!toolArguments.workFolder || typeof toolArguments.workFolder !== 'string') {
353
- throw new McpError(ErrorCode.InvalidParams, 'Missing or invalid required parameter: workFolder');
354
- }
355
- // Validate that either prompt or prompt_file is provided
356
- const hasPrompt = toolArguments.prompt && typeof toolArguments.prompt === 'string' && toolArguments.prompt.trim() !== '';
357
- const hasPromptFile = toolArguments.prompt_file && typeof toolArguments.prompt_file === 'string' && toolArguments.prompt_file.trim() !== '';
358
- if (!hasPrompt && !hasPromptFile) {
359
- throw new McpError(ErrorCode.InvalidParams, 'Either prompt or prompt_file must be provided');
360
- }
361
- if (hasPrompt && hasPromptFile) {
362
- throw new McpError(ErrorCode.InvalidParams, 'Cannot specify both prompt and prompt_file. Please use only one.');
363
- }
364
- // Determine the prompt to use
365
- let prompt;
366
- if (hasPrompt) {
367
- prompt = toolArguments.prompt;
368
- }
369
- else {
370
- // Read prompt from file
371
- const promptFilePath = path.isAbsolute(toolArguments.prompt_file)
372
- ? toolArguments.prompt_file
373
- : pathResolve(toolArguments.workFolder, toolArguments.prompt_file);
374
- if (!existsSync(promptFilePath)) {
375
- throw new McpError(ErrorCode.InvalidParams, `Prompt file does not exist: ${promptFilePath}`);
376
- }
377
- try {
378
- prompt = readFileSync(promptFilePath, 'utf-8');
379
- }
380
- catch (error) {
381
- throw new McpError(ErrorCode.InvalidParams, `Failed to read prompt file: ${error.message}`);
382
- }
383
- }
384
- // Determine working directory
385
- const resolvedCwd = pathResolve(toolArguments.workFolder);
386
- if (!existsSync(resolvedCwd)) {
387
- throw new McpError(ErrorCode.InvalidParams, `Working folder does not exist: ${toolArguments.workFolder}`);
388
- }
389
- const effectiveCwd = resolvedCwd;
390
- // Print version on first use
391
- if (isFirstToolUse) {
392
- console.error(`ai_cli_mcp v${SERVER_VERSION} started at ${serverStartupTime}`);
393
- isFirstToolUse = false;
394
- }
395
- // Determine which agent to use based on model name
396
- const model = toolArguments.model || '';
397
- let agent;
398
- if (model.startsWith('gpt-')) {
399
- agent = 'codex';
400
- }
401
- else if (model.startsWith('gemini')) {
402
- agent = 'gemini';
403
- }
404
- else {
405
- agent = 'claude';
406
- }
407
- let cliPath;
408
- let processArgs;
409
- if (agent === 'codex') {
410
- // Handle Codex
411
- cliPath = this.codexCliPath;
412
- processArgs = ['exec'];
413
- // Parse model format for Codex (e.g., gpt-5-low -> model: gpt-5, effort: low)
414
- if (toolArguments.model) {
415
- // Split by "gpt-5-" to get the effort level
416
- const effort = toolArguments.model.replace('gpt-5-', '');
417
- if (effort && effort !== toolArguments.model) {
418
- processArgs.push('-c', `model_reasoning_effort=${effort}`);
419
- }
420
- processArgs.push('--model', 'gpt-5');
421
- }
422
- processArgs.push('--full-auto', '--json', prompt);
423
- }
424
- else if (agent === 'gemini') {
425
- // Handle Gemini
426
- cliPath = this.geminiCliPath;
427
- processArgs = ['-y', '--output-format', 'json'];
428
- // Add model if specified
429
- if (toolArguments.model) {
430
- processArgs.push('--model', toolArguments.model);
431
- }
432
- // Add prompt as positional argument
433
- processArgs.push(prompt);
434
- }
435
- else {
436
- // Handle Claude (default)
437
- cliPath = this.claudeCliPath;
438
- processArgs = ['--dangerously-skip-permissions', '--output-format', 'json'];
439
- // Add session_id if provided (Claude only)
440
- if (toolArguments.session_id && typeof toolArguments.session_id === 'string') {
441
- processArgs.push('-r', toolArguments.session_id);
442
- }
443
- processArgs.push('-p', prompt);
444
- if (toolArguments.model && typeof toolArguments.model === 'string') {
445
- const resolvedModel = resolveModelAlias(toolArguments.model);
446
- processArgs.push('--model', resolvedModel);
447
- }
448
- }
449
- // Spawn process without waiting
450
- const childProcess = spawn(cliPath, processArgs, {
451
- cwd: effectiveCwd,
452
- stdio: ['ignore', 'pipe', 'pipe'],
453
- detached: false
454
- });
455
- const pid = childProcess.pid;
456
- if (!pid) {
457
- throw new McpError(ErrorCode.InternalError, `Failed to start ${agent} CLI process`);
458
- }
459
- // Create process tracking entry
460
- const processEntry = {
461
- pid,
462
- process: childProcess,
463
- prompt,
464
- workFolder: effectiveCwd,
465
- model: toolArguments.model,
466
- toolType: agent,
467
- startTime: new Date().toISOString(),
468
- stdout: '',
469
- stderr: '',
470
- status: 'running'
471
- };
472
- // Track the process
473
- processManager.set(pid, processEntry);
474
- // Set up output collection
475
- childProcess.stdout.on('data', (data) => {
476
- const entry = processManager.get(pid);
477
- if (entry) {
478
- entry.stdout += data.toString();
479
- }
480
- });
481
- childProcess.stderr.on('data', (data) => {
482
- const entry = processManager.get(pid);
483
- if (entry) {
484
- entry.stderr += data.toString();
485
- }
486
- });
487
- childProcess.on('close', (code) => {
488
- const entry = processManager.get(pid);
489
- if (entry) {
490
- entry.status = code === 0 ? 'completed' : 'failed';
491
- entry.exitCode = code !== null ? code : undefined;
492
- }
493
- });
494
- childProcess.on('error', (error) => {
495
- const entry = processManager.get(pid);
496
- if (entry) {
497
- entry.status = 'failed';
498
- entry.stderr += `\nProcess error: ${error.message}`;
499
- }
500
- });
501
- // Return PID immediately
502
- return {
503
- content: [{
504
- type: 'text',
505
- text: JSON.stringify({
506
- pid,
507
- status: 'started',
508
- agent,
509
- message: `${agent} process started successfully`
510
- }, null, 2)
511
- }]
512
- };
513
- }
514
- /**
515
- * Handle list_processes tool
516
- */
517
- async handleListProcesses() {
518
- const processes = [];
519
- for (const [pid, process] of processManager.entries()) {
520
- const processInfo = {
521
- pid,
522
- agent: process.toolType,
523
- status: process.status,
524
- startTime: process.startTime,
525
- prompt: process.prompt.substring(0, 100) + (process.prompt.length > 100 ? '...' : ''),
526
- workFolder: process.workFolder,
527
- model: process.model,
528
- exitCode: process.exitCode
529
- };
530
- // Try to extract session_id from JSON output if available
531
- if (process.stdout) {
532
- try {
533
- const claudeOutput = JSON.parse(process.stdout);
534
- if (claudeOutput.session_id) {
535
- processInfo.session_id = claudeOutput.session_id;
536
- }
537
- }
538
- catch (e) {
539
- // Ignore parsing errors
540
- }
541
- }
542
- processes.push(processInfo);
543
- }
544
- return {
545
- content: [{
546
- type: 'text',
547
- text: JSON.stringify(processes, null, 2)
548
- }]
549
- };
550
- }
551
- /**
552
- * Handle get_result tool
553
- */
554
- async handleGetResult(toolArguments) {
555
- if (!toolArguments.pid || typeof toolArguments.pid !== 'number') {
556
- throw new McpError(ErrorCode.InvalidParams, 'Missing or invalid required parameter: pid');
557
- }
558
- const pid = toolArguments.pid;
559
- const process = processManager.get(pid);
560
- if (!process) {
561
- throw new McpError(ErrorCode.InvalidParams, `Process with PID ${pid} not found`);
562
- }
563
- // Parse output based on agent type
564
- let agentOutput = null;
565
- if (process.stdout) {
566
- if (process.toolType === 'codex') {
567
- agentOutput = parseCodexOutput(process.stdout);
568
- }
569
- else if (process.toolType === 'claude') {
570
- agentOutput = parseClaudeOutput(process.stdout);
571
- }
572
- else if (process.toolType === 'gemini') {
573
- agentOutput = parseGeminiOutput(process.stdout);
574
- }
575
- }
576
- // Construct response with agent's output and process metadata
577
- const response = {
578
- pid,
579
- agent: process.toolType,
580
- status: process.status,
581
- exitCode: process.exitCode,
582
- startTime: process.startTime,
583
- workFolder: process.workFolder,
584
- prompt: process.prompt,
585
- model: process.model
586
- };
587
- // If we have valid output from agent, include it
588
- if (agentOutput) {
589
- response.agentOutput = agentOutput;
590
- // Extract session_id if available (Claude only)
591
- if (process.toolType === 'claude' && agentOutput.session_id) {
592
- response.session_id = agentOutput.session_id;
593
- }
594
- }
595
- else {
596
- // Fallback to raw output
597
- response.stdout = process.stdout;
598
- response.stderr = process.stderr;
599
- }
600
- return {
601
- content: [{
602
- type: 'text',
603
- text: JSON.stringify(response, null, 2)
604
- }]
605
- };
606
- }
607
- /**
608
- * Handle kill_process tool
609
- */
610
- async handleKillProcess(toolArguments) {
611
- if (!toolArguments.pid || typeof toolArguments.pid !== 'number') {
612
- throw new McpError(ErrorCode.InvalidParams, 'Missing or invalid required parameter: pid');
613
- }
614
- const pid = toolArguments.pid;
615
- const processEntry = processManager.get(pid);
616
- if (!processEntry) {
617
- throw new McpError(ErrorCode.InvalidParams, `Process with PID ${pid} not found`);
618
- }
619
- if (processEntry.status !== 'running') {
620
- return {
621
- content: [{
622
- type: 'text',
623
- text: JSON.stringify({
624
- pid,
625
- status: processEntry.status,
626
- message: 'Process already terminated'
627
- }, null, 2)
628
- }]
629
- };
630
- }
631
- try {
632
- processEntry.process.kill('SIGTERM');
633
- processEntry.status = 'failed';
634
- processEntry.stderr += '\nProcess terminated by user';
635
- return {
636
- content: [{
637
- type: 'text',
638
- text: JSON.stringify({
639
- pid,
640
- status: 'terminated',
641
- message: 'Process terminated successfully'
642
- }, null, 2)
643
- }]
644
- };
645
- }
646
- catch (error) {
647
- throw new McpError(ErrorCode.InternalError, `Failed to terminate process: ${error.message}`);
648
- }
649
- }
650
- /**
651
- * Start the MCP server
652
- */
653
- async run() {
654
- // Revert to original server start logic if listen caused errors
655
- const transport = new StdioServerTransport();
656
- await this.server.connect(transport);
657
- console.error('AI CLI MCP server running on stdio');
658
- }
659
- /**
660
- * Clean up resources (for testing)
661
- */
662
- async cleanup() {
663
- if (this.sigintHandler) {
664
- process.removeListener('SIGINT', this.sigintHandler);
665
- }
666
- await this.server.close();
667
- }
668
- }
669
- // Create and run the server if this is the main module
670
- const server = new ClaudeCodeServer();
671
- server.run().catch(console.error);