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.
@@ -1,238 +0,0 @@
1
- import { describe, it, expect, beforeEach, afterEach, afterAll } from 'vitest';
2
- import { mkdtempSync, rmSync, readFileSync, existsSync } from 'node:fs';
3
- import { join } from 'node:path';
4
- import { tmpdir } from 'node:os';
5
- import { MCPTestClient } from './utils/mcp-client.js';
6
- import { getSharedMock, cleanupSharedMock } from './utils/persistent-mock.js';
7
- describe('Claude Code MCP E2E Tests', () => {
8
- let client;
9
- let testDir;
10
- const serverPath = 'dist/server.js';
11
- beforeEach(async () => {
12
- // Ensure mock exists
13
- await getSharedMock();
14
- // Create a temporary directory for test files
15
- testDir = mkdtempSync(join(tmpdir(), 'claude-code-test-'));
16
- // Initialize MCP client with debug mode and custom binary name using absolute path
17
- client = new MCPTestClient(serverPath, {
18
- MCP_CLAUDE_DEBUG: 'true',
19
- CLAUDE_CLI_NAME: '/tmp/claude-code-test-mock/claudeMocked',
20
- });
21
- await client.connect();
22
- });
23
- afterEach(async () => {
24
- // Disconnect client
25
- await client.disconnect();
26
- // Clean up test directory
27
- rmSync(testDir, { recursive: true, force: true });
28
- });
29
- afterAll(async () => {
30
- // Only cleanup mock at the very end
31
- await cleanupSharedMock();
32
- });
33
- describe('Tool Registration', () => {
34
- it('should register claude_code tool', async () => {
35
- const tools = await client.listTools();
36
- expect(tools).toHaveLength(4);
37
- const claudeCodeTool = tools.find((t) => t.name === 'claude_code');
38
- expect(claudeCodeTool).toEqual({
39
- name: 'claude_code',
40
- description: expect.stringContaining('Claude Code Agent'),
41
- inputSchema: {
42
- type: 'object',
43
- properties: {
44
- prompt: {
45
- type: 'string',
46
- description: expect.stringContaining('Either this or prompt_file is required'),
47
- },
48
- prompt_file: {
49
- type: 'string',
50
- description: expect.stringContaining('Path to a file containing the prompt'),
51
- },
52
- workFolder: {
53
- type: 'string',
54
- description: expect.stringContaining('working directory'),
55
- },
56
- model: {
57
- type: 'string',
58
- description: expect.stringContaining('Claude model'),
59
- },
60
- session_id: {
61
- type: 'string',
62
- description: expect.stringContaining('session ID'),
63
- },
64
- },
65
- required: ['workFolder'],
66
- },
67
- });
68
- // Verify other tools exist
69
- expect(tools.some((t) => t.name === 'list_claude_processes')).toBe(true);
70
- expect(tools.some((t) => t.name === 'get_claude_result')).toBe(true);
71
- expect(tools.some((t) => t.name === 'kill_claude_process')).toBe(true);
72
- });
73
- });
74
- describe('Basic Operations', () => {
75
- it('should execute a simple prompt', async () => {
76
- const response = await client.callTool('claude_code', {
77
- prompt: 'create a file called test.txt with content "Hello World"',
78
- workFolder: testDir,
79
- });
80
- expect(response).toEqual([{
81
- type: 'text',
82
- text: expect.stringContaining('successfully'),
83
- }]);
84
- });
85
- it('should handle process management correctly', async () => {
86
- // claude_code now returns a PID immediately
87
- const response = await client.callTool('claude_code', {
88
- prompt: 'error',
89
- workFolder: testDir,
90
- });
91
- expect(response).toEqual([{
92
- type: 'text',
93
- text: expect.stringContaining('pid'),
94
- }]);
95
- // Extract PID from response
96
- const responseText = response[0].text;
97
- const pidMatch = responseText.match(/"pid":\s*(\d+)/);
98
- expect(pidMatch).toBeTruthy();
99
- });
100
- it('should reject missing workFolder', async () => {
101
- await expect(client.callTool('claude_code', {
102
- prompt: 'List files in current directory',
103
- })).rejects.toThrow(/workFolder/i);
104
- });
105
- });
106
- describe('Working Directory Handling', () => {
107
- it('should respect custom working directory', async () => {
108
- const response = await client.callTool('claude_code', {
109
- prompt: 'Show current working directory',
110
- workFolder: testDir,
111
- });
112
- expect(response).toBeTruthy();
113
- });
114
- it('should reject non-existent working directory', async () => {
115
- const nonExistentDir = join(testDir, 'non-existent');
116
- await expect(client.callTool('claude_code', {
117
- prompt: 'Test prompt',
118
- workFolder: nonExistentDir,
119
- })).rejects.toThrow(/does not exist/i);
120
- });
121
- });
122
- describe('Timeout Handling', () => {
123
- it('should respect timeout settings', async () => {
124
- // This would require modifying the mock to simulate a long-running command
125
- // Since we're testing locally, we'll skip the actual timeout test
126
- expect(true).toBe(true);
127
- });
128
- });
129
- describe('Model Alias Handling', () => {
130
- it('should resolve haiku alias when calling claude_code', async () => {
131
- const response = await client.callTool('claude_code', {
132
- prompt: 'Test with haiku model',
133
- workFolder: testDir,
134
- model: 'haiku'
135
- });
136
- expect(response).toEqual([{
137
- type: 'text',
138
- text: expect.stringContaining('pid'),
139
- }]);
140
- // Extract PID from response
141
- const responseText = response[0].text;
142
- const pidMatch = responseText.match(/"pid":\s*(\d+)/);
143
- expect(pidMatch).toBeTruthy();
144
- // Get the PID and check the process
145
- const pid = parseInt(pidMatch[1]);
146
- const processes = await client.callTool('list_claude_processes', {});
147
- const processesText = processes[0].text;
148
- const processData = JSON.parse(processesText);
149
- // Find our process
150
- const ourProcess = processData.find((p) => p.pid === pid);
151
- expect(ourProcess).toBeTruthy();
152
- // Verify that the model was set correctly
153
- expect(ourProcess.model).toBe('haiku');
154
- });
155
- it('should pass non-alias model names unchanged', async () => {
156
- const response = await client.callTool('claude_code', {
157
- prompt: 'Test with sonnet model',
158
- workFolder: testDir,
159
- model: 'sonnet'
160
- });
161
- expect(response).toEqual([{
162
- type: 'text',
163
- text: expect.stringContaining('pid'),
164
- }]);
165
- // Extract PID
166
- const responseText = response[0].text;
167
- const pidMatch = responseText.match(/"pid":\s*(\d+)/);
168
- const pid = parseInt(pidMatch[1]);
169
- // Check the process
170
- const processes = await client.callTool('list_claude_processes', {});
171
- const processesText = processes[0].text;
172
- const processData = JSON.parse(processesText);
173
- // Find our process
174
- const ourProcess = processData.find((p) => p.pid === pid);
175
- expect(ourProcess).toBeTruthy();
176
- // The model should be unchanged
177
- expect(ourProcess.model).toBe('sonnet');
178
- });
179
- it('should work without specifying a model', async () => {
180
- const response = await client.callTool('claude_code', {
181
- prompt: 'Test without model parameter',
182
- workFolder: testDir
183
- });
184
- expect(response).toEqual([{
185
- type: 'text',
186
- text: expect.stringContaining('pid'),
187
- }]);
188
- });
189
- });
190
- describe('Debug Mode', () => {
191
- it('should log debug information when enabled', async () => {
192
- // Debug logs go to stderr, which we capture in the client
193
- const response = await client.callTool('claude_code', {
194
- prompt: 'Debug test prompt',
195
- workFolder: testDir,
196
- });
197
- expect(response).toBeTruthy();
198
- });
199
- });
200
- });
201
- describe('Integration Tests (Local Only)', () => {
202
- let client;
203
- let testDir;
204
- beforeEach(async () => {
205
- testDir = mkdtempSync(join(tmpdir(), 'claude-code-integration-'));
206
- // Initialize client without mocks for real Claude testing
207
- client = new MCPTestClient('dist/server.js', {
208
- MCP_CLAUDE_DEBUG: 'true',
209
- });
210
- });
211
- afterEach(async () => {
212
- if (client) {
213
- await client.disconnect();
214
- }
215
- rmSync(testDir, { recursive: true, force: true });
216
- });
217
- // These tests will only run locally when Claude is available
218
- it.skip('should create a file with real Claude CLI', async () => {
219
- await client.connect();
220
- const response = await client.callTool('claude_code', {
221
- prompt: 'Create a file called hello.txt with content "Hello from Claude"',
222
- workFolder: testDir,
223
- });
224
- const filePath = join(testDir, 'hello.txt');
225
- expect(existsSync(filePath)).toBe(true);
226
- expect(readFileSync(filePath, 'utf-8')).toContain('Hello from Claude');
227
- });
228
- it.skip('should handle git operations with real Claude CLI', async () => {
229
- await client.connect();
230
- // Initialize git repo
231
- const response = await client.callTool('claude_code', {
232
- prompt: 'Initialize a git repository and create a README.md file',
233
- workFolder: testDir,
234
- });
235
- expect(existsSync(join(testDir, '.git'))).toBe(true);
236
- expect(existsSync(join(testDir, 'README.md'))).toBe(true);
237
- });
238
- });
@@ -1,135 +0,0 @@
1
- import { describe, it, expect, beforeEach, afterEach, afterAll } from 'vitest';
2
- import { mkdtempSync, rmSync } from 'node:fs';
3
- import { join } from 'node:path';
4
- import { tmpdir } from 'node:os';
5
- import { MCPTestClient } from './utils/mcp-client.js';
6
- import { getSharedMock, cleanupSharedMock } from './utils/persistent-mock.js';
7
- describe('Claude Code Edge Cases', () => {
8
- let client;
9
- let testDir;
10
- const serverPath = 'dist/server.js';
11
- beforeEach(async () => {
12
- // Ensure mock exists
13
- await getSharedMock();
14
- // Create test directory
15
- testDir = mkdtempSync(join(tmpdir(), 'claude-code-edge-'));
16
- // Initialize client with custom binary name using absolute path
17
- client = new MCPTestClient(serverPath, {
18
- MCP_CLAUDE_DEBUG: 'true',
19
- CLAUDE_CLI_NAME: '/tmp/claude-code-test-mock/claudeMocked',
20
- });
21
- await client.connect();
22
- });
23
- afterEach(async () => {
24
- await client.disconnect();
25
- rmSync(testDir, { recursive: true, force: true });
26
- });
27
- afterAll(async () => {
28
- // Cleanup mock only at the end
29
- await cleanupSharedMock();
30
- });
31
- describe('Input Validation', () => {
32
- it('should reject missing prompt', async () => {
33
- await expect(client.callTool('claude_code', {
34
- workFolder: testDir,
35
- })).rejects.toThrow(/prompt/i);
36
- });
37
- it('should reject invalid prompt type', async () => {
38
- await expect(client.callTool('claude_code', {
39
- prompt: 123, // Should be string
40
- workFolder: testDir,
41
- })).rejects.toThrow();
42
- });
43
- it('should reject invalid workFolder type', async () => {
44
- await expect(client.callTool('claude_code', {
45
- prompt: 'Test prompt',
46
- workFolder: 123, // Should be string
47
- })).rejects.toThrow(/workFolder/i);
48
- });
49
- it('should reject empty prompt', async () => {
50
- await expect(client.callTool('claude_code', {
51
- prompt: '',
52
- workFolder: testDir,
53
- })).rejects.toThrow(/prompt/i);
54
- });
55
- });
56
- describe('Special Characters', () => {
57
- it.skip('should handle prompts with quotes', async () => {
58
- // Skipping: This test fails in CI when mock is not found at expected path
59
- const response = await client.callTool('claude_code', {
60
- prompt: 'Create a file with content "Hello \\"World\\""',
61
- workFolder: testDir,
62
- });
63
- expect(response).toBeTruthy();
64
- });
65
- it('should handle prompts with newlines', async () => {
66
- const response = await client.callTool('claude_code', {
67
- prompt: 'Create a file with content:\\nLine 1\\nLine 2',
68
- workFolder: testDir,
69
- });
70
- expect(response).toBeTruthy();
71
- });
72
- it('should handle prompts with shell special characters', async () => {
73
- const response = await client.callTool('claude_code', {
74
- prompt: 'Create a file named test$file.txt',
75
- workFolder: testDir,
76
- });
77
- expect(response).toBeTruthy();
78
- });
79
- });
80
- describe('Error Recovery', () => {
81
- it('should handle Claude CLI not found gracefully', async () => {
82
- // Create a client with a different binary name that doesn't exist
83
- const errorClient = new MCPTestClient(serverPath, {
84
- MCP_CLAUDE_DEBUG: 'true',
85
- CLAUDE_CLI_NAME: 'non-existent-claude',
86
- });
87
- await errorClient.connect();
88
- await expect(errorClient.callTool('claude_code', {
89
- prompt: 'Test prompt',
90
- workFolder: testDir,
91
- })).rejects.toThrow();
92
- await errorClient.disconnect();
93
- });
94
- it('should handle permission denied errors', async () => {
95
- const restrictedDir = '/root/restricted';
96
- // Non-existent directories now throw an error
97
- await expect(client.callTool('claude_code', {
98
- prompt: 'Test prompt',
99
- workFolder: restrictedDir,
100
- })).rejects.toThrow(/does not exist/i);
101
- });
102
- });
103
- describe('Concurrent Requests', () => {
104
- it('should handle multiple simultaneous requests', async () => {
105
- const promises = Array(5).fill(null).map((_, i) => client.callTool('claude_code', {
106
- prompt: `Create file test${i}.txt`,
107
- workFolder: testDir,
108
- }));
109
- const results = await Promise.allSettled(promises);
110
- const successful = results.filter(r => r.status === 'fulfilled');
111
- expect(successful.length).toBeGreaterThan(0);
112
- });
113
- });
114
- describe('Large Prompts', () => {
115
- it('should handle very long prompts', async () => {
116
- const longPrompt = 'Create a file with content: ' + 'x'.repeat(10000);
117
- const response = await client.callTool('claude_code', {
118
- prompt: longPrompt,
119
- workFolder: testDir,
120
- });
121
- expect(response).toBeTruthy();
122
- });
123
- });
124
- describe('Path Traversal', () => {
125
- it('should prevent path traversal attacks', async () => {
126
- const maliciousPath = join(testDir, '..', '..', 'etc', 'passwd');
127
- // Server resolves paths and checks existence
128
- // The path /etc/passwd may exist but be a file, not a directory
129
- await expect(client.callTool('claude_code', {
130
- prompt: 'Read file',
131
- workFolder: maliciousPath,
132
- })).rejects.toThrow(/(does not exist|ENOTDIR)/i);
133
- });
134
- });
135
- });
@@ -1,296 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
- import { spawn } from 'node:child_process';
3
- import { existsSync } from 'node:fs';
4
- import { homedir } from 'node:os';
5
- import { EventEmitter } from 'node:events';
6
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
7
- // Mock dependencies
8
- vi.mock('node:child_process');
9
- vi.mock('node:fs');
10
- vi.mock('node:os');
11
- vi.mock('node:path', () => ({
12
- resolve: vi.fn((path) => path),
13
- join: vi.fn((...args) => args.join('/')),
14
- isAbsolute: vi.fn((path) => path.startsWith('/'))
15
- }));
16
- vi.mock('@modelcontextprotocol/sdk/server/index.js', () => ({
17
- Server: vi.fn().mockImplementation(function () {
18
- this.setRequestHandler = vi.fn();
19
- this.connect = vi.fn();
20
- this.close = vi.fn();
21
- this.onerror = undefined;
22
- return this;
23
- }),
24
- }));
25
- vi.mock('@modelcontextprotocol/sdk/types.js', () => ({
26
- ListToolsRequestSchema: { name: 'listTools' },
27
- CallToolRequestSchema: { name: 'callTool' },
28
- ErrorCode: {
29
- InternalError: 'InternalError',
30
- MethodNotFound: 'MethodNotFound',
31
- InvalidParams: 'InvalidParams'
32
- },
33
- McpError: vi.fn().mockImplementation((code, message) => {
34
- const error = new Error(message);
35
- error.code = code;
36
- return error;
37
- })
38
- }));
39
- const mockExistsSync = vi.mocked(existsSync);
40
- const mockSpawn = vi.mocked(spawn);
41
- const mockHomedir = vi.mocked(homedir);
42
- describe('Error Handling Tests', () => {
43
- let consoleErrorSpy;
44
- let originalEnv;
45
- let errorHandler = null;
46
- function setupServerMock() {
47
- errorHandler = null;
48
- vi.mocked(Server).mockImplementation(function () {
49
- this.setRequestHandler = vi.fn();
50
- this.connect = vi.fn();
51
- this.close = vi.fn();
52
- Object.defineProperty(this, 'onerror', {
53
- get() { return errorHandler; },
54
- set(handler) { errorHandler = handler; },
55
- enumerable: true,
56
- configurable: true
57
- });
58
- return this;
59
- });
60
- }
61
- beforeEach(() => {
62
- vi.clearAllMocks();
63
- vi.resetModules();
64
- consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => { });
65
- originalEnv = { ...process.env };
66
- process.env = { ...originalEnv };
67
- });
68
- afterEach(() => {
69
- consoleErrorSpy.mockRestore();
70
- process.env = originalEnv;
71
- });
72
- describe('CallToolRequest Error Cases', () => {
73
- it('should throw error for unknown tool name', async () => {
74
- mockHomedir.mockReturnValue('/home/user');
75
- mockExistsSync.mockReturnValue(true);
76
- // Set up Server mock before importing the module
77
- setupServerMock();
78
- const module = await import('../server.js');
79
- // @ts-ignore
80
- const { ClaudeCodeServer } = module;
81
- const server = new ClaudeCodeServer();
82
- const mockServerInstance = vi.mocked(Server).mock.results[0].value;
83
- const callToolCall = mockServerInstance.setRequestHandler.mock.calls.find((call) => call[0].name === 'callTool');
84
- const handler = callToolCall[1];
85
- await expect(handler({
86
- params: {
87
- name: 'unknown_tool',
88
- arguments: {}
89
- }
90
- })).rejects.toThrow('Tool unknown_tool not found');
91
- });
92
- it('should handle timeout errors', async () => {
93
- mockHomedir.mockReturnValue('/home/user');
94
- mockExistsSync.mockReturnValue(true);
95
- setupServerMock();
96
- const module = await import('../server.js');
97
- // @ts-ignore
98
- const { ClaudeCodeServer } = module;
99
- const { McpError } = await import('@modelcontextprotocol/sdk/types.js');
100
- const server = new ClaudeCodeServer();
101
- const mockServerInstance = vi.mocked(Server).mock.results[0].value;
102
- // Find the callTool handler
103
- let callToolHandler;
104
- for (const call of mockServerInstance.setRequestHandler.mock.calls) {
105
- if (call[0].name === 'callTool') {
106
- callToolHandler = call[1];
107
- break;
108
- }
109
- }
110
- // Mock spawn to return process without PID
111
- mockSpawn.mockImplementation(() => {
112
- const mockProcess = new EventEmitter();
113
- mockProcess.stdout = new EventEmitter();
114
- mockProcess.stderr = new EventEmitter();
115
- mockProcess.stdout.on = vi.fn();
116
- mockProcess.stderr.on = vi.fn();
117
- mockProcess.pid = undefined; // No PID to simulate process start failure
118
- return mockProcess;
119
- });
120
- // Call handler
121
- try {
122
- await callToolHandler({
123
- params: {
124
- name: 'claude_code',
125
- arguments: {
126
- prompt: 'test',
127
- workFolder: '/tmp'
128
- }
129
- }
130
- });
131
- expect.fail('Should have thrown');
132
- }
133
- catch (err) {
134
- // Check if McpError was called with the process start failure message
135
- expect(McpError).toHaveBeenCalledWith('InternalError', 'Failed to start Claude CLI process');
136
- }
137
- });
138
- it('should handle invalid argument types', async () => {
139
- mockHomedir.mockReturnValue('/home/user');
140
- mockExistsSync.mockReturnValue(true);
141
- setupServerMock();
142
- const module = await import('../server.js');
143
- // @ts-ignore
144
- const { ClaudeCodeServer } = module;
145
- const server = new ClaudeCodeServer();
146
- const mockServerInstance = vi.mocked(Server).mock.results[0].value;
147
- const callToolCall = mockServerInstance.setRequestHandler.mock.calls.find((call) => call[0].name === 'callTool');
148
- const handler = callToolCall[1];
149
- await expect(handler({
150
- params: {
151
- name: 'claude_code',
152
- arguments: 'invalid-should-be-object'
153
- }
154
- })).rejects.toThrow();
155
- });
156
- it('should include CLI error details in error message', async () => {
157
- mockHomedir.mockReturnValue('/home/user');
158
- mockExistsSync.mockReturnValue(true);
159
- setupServerMock();
160
- const module = await import('../server.js');
161
- // @ts-ignore
162
- const { ClaudeCodeServer } = module;
163
- const server = new ClaudeCodeServer();
164
- const mockServerInstance = vi.mocked(Server).mock.results[0].value;
165
- const callToolCall = mockServerInstance.setRequestHandler.mock.calls.find((call) => call[0].name === 'callTool');
166
- const handler = callToolCall[1];
167
- // Create a simple mock process
168
- mockSpawn.mockImplementation(() => {
169
- const mockProcess = Object.create(EventEmitter.prototype);
170
- EventEmitter.call(mockProcess);
171
- mockProcess.stdout = Object.create(EventEmitter.prototype);
172
- EventEmitter.call(mockProcess.stdout);
173
- mockProcess.stderr = Object.create(EventEmitter.prototype);
174
- EventEmitter.call(mockProcess.stderr);
175
- mockProcess.stdout.on = vi.fn((event, callback) => {
176
- if (event === 'data') {
177
- // Send some stdout data
178
- process.nextTick(() => callback('stdout content'));
179
- }
180
- });
181
- mockProcess.stderr.on = vi.fn((event, callback) => {
182
- if (event === 'data') {
183
- // Send some stderr data
184
- process.nextTick(() => callback('stderr content'));
185
- }
186
- });
187
- // Emit error/close event after data is sent
188
- setTimeout(() => {
189
- mockProcess.emit('close', 1);
190
- }, 1);
191
- return mockProcess;
192
- });
193
- await expect(handler({
194
- params: {
195
- name: 'claude_code',
196
- arguments: {
197
- prompt: 'test',
198
- workFolder: '/tmp'
199
- }
200
- }
201
- })).rejects.toThrow();
202
- });
203
- });
204
- describe('Process Spawn Error Cases', () => {
205
- it('should handle spawn ENOENT error', async () => {
206
- const module = await import('../server.js');
207
- // @ts-ignore
208
- const { spawnAsync } = module;
209
- const mockProcess = new EventEmitter();
210
- mockProcess.stdout = new EventEmitter();
211
- mockProcess.stderr = new EventEmitter();
212
- mockProcess.stdout.on = vi.fn();
213
- mockProcess.stderr.on = vi.fn();
214
- mockSpawn.mockReturnValue(mockProcess);
215
- const promise = spawnAsync('nonexistent-command', []);
216
- // Simulate ENOENT error
217
- setTimeout(() => {
218
- const error = new Error('spawn ENOENT');
219
- error.code = 'ENOENT';
220
- error.path = 'nonexistent-command';
221
- error.syscall = 'spawn';
222
- mockProcess.emit('error', error);
223
- }, 10);
224
- await expect(promise).rejects.toThrow('Spawn error');
225
- await expect(promise).rejects.toThrow('nonexistent-command');
226
- });
227
- it('should handle generic spawn errors', async () => {
228
- const module = await import('../server.js');
229
- // @ts-ignore
230
- const { spawnAsync } = module;
231
- const mockProcess = new EventEmitter();
232
- mockProcess.stdout = new EventEmitter();
233
- mockProcess.stderr = new EventEmitter();
234
- mockProcess.stdout.on = vi.fn();
235
- mockProcess.stderr.on = vi.fn();
236
- mockSpawn.mockReturnValue(mockProcess);
237
- const promise = spawnAsync('test', []);
238
- // Simulate generic error
239
- setTimeout(() => {
240
- mockProcess.emit('error', new Error('Generic spawn error'));
241
- }, 10);
242
- await expect(promise).rejects.toThrow('Generic spawn error');
243
- });
244
- it('should accumulate stderr output before error', async () => {
245
- const module = await import('../server.js');
246
- // @ts-ignore
247
- const { spawnAsync } = module;
248
- const mockProcess = new EventEmitter();
249
- mockProcess.stdout = new EventEmitter();
250
- mockProcess.stderr = new EventEmitter();
251
- let stderrHandler;
252
- mockProcess.stdout.on = vi.fn();
253
- mockProcess.stderr.on = vi.fn((event, handler) => {
254
- if (event === 'data')
255
- stderrHandler = handler;
256
- });
257
- mockSpawn.mockReturnValue(mockProcess);
258
- const promise = spawnAsync('test', []);
259
- // Simulate stderr data then error
260
- setTimeout(() => {
261
- stderrHandler('error line 1\n');
262
- stderrHandler('error line 2\n');
263
- mockProcess.emit('error', new Error('Command failed'));
264
- }, 10);
265
- await expect(promise).rejects.toThrow('error line 1\nerror line 2');
266
- });
267
- });
268
- describe('Server Initialization Errors', () => {
269
- it('should handle CLI path not found gracefully', async () => {
270
- // Mock no CLI found anywhere
271
- mockHomedir.mockReturnValue('/home/user');
272
- mockExistsSync.mockReturnValue(false);
273
- const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => { });
274
- setupServerMock();
275
- const module = await import('../server.js');
276
- // @ts-ignore
277
- const { ClaudeCodeServer } = module;
278
- const server = new ClaudeCodeServer();
279
- expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining('Claude CLI not found'));
280
- consoleWarnSpy.mockRestore();
281
- });
282
- it('should handle server connection errors', async () => {
283
- mockHomedir.mockReturnValue('/home/user');
284
- mockExistsSync.mockReturnValue(true);
285
- setupServerMock();
286
- const module = await import('../server.js');
287
- // @ts-ignore
288
- const { ClaudeCodeServer } = module;
289
- const server = new ClaudeCodeServer();
290
- // Mock connection failure
291
- const mockServerInstance = vi.mocked(Server).mock.results[0].value;
292
- mockServerInstance.connect.mockRejectedValue(new Error('Connection failed'));
293
- await expect(server.run()).rejects.toThrow('Connection failed');
294
- });
295
- });
296
- });