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.
- package/.claude/settings.local.json +2 -1
- package/dist/__tests__/e2e.test.js +232 -0
- package/dist/__tests__/edge-cases.test.js +135 -0
- package/dist/__tests__/error-cases.test.js +291 -0
- package/dist/__tests__/mocks.js +32 -0
- package/dist/__tests__/model-alias.test.js +36 -0
- package/dist/__tests__/process-management.test.js +630 -0
- package/dist/__tests__/server.test.js +681 -0
- package/dist/__tests__/setup.js +11 -0
- package/dist/__tests__/utils/claude-mock.js +80 -0
- package/dist/__tests__/utils/mcp-client.js +104 -0
- package/dist/__tests__/utils/persistent-mock.js +25 -0
- package/dist/__tests__/utils/test-helpers.js +11 -0
- package/dist/__tests__/validation.test.js +235 -0
- package/dist/__tests__/version-print.test.js +69 -0
- package/dist/__tests__/wait.test.js +229 -0
- package/dist/parsers.js +68 -0
- package/dist/server.js +774 -0
- package/package.json +1 -1
- package/src/__tests__/e2e.test.ts +16 -24
- package/src/__tests__/error-cases.test.ts +8 -17
- package/src/__tests__/process-management.test.ts +22 -24
- package/src/__tests__/validation.test.ts +58 -36
- package/src/server.ts +6 -2
- package/data/rooms/refactor-haiku-alias-main/messages.jsonl +0 -5
- package/data/rooms/refactor-haiku-alias-main/presence.json +0 -20
- package/data/rooms.json +0 -10
- package/hello.txt +0 -3
- package/implementation-log.md +0 -110
- package/implementation-plan.md +0 -189
- package/investigation-report.md +0 -135
- package/quality-score.json +0 -47
- package/refactoring-requirements.md +0 -25
- package/review-report.md +0 -132
- package/test-results.md +0 -119
- package/xx.txt +0 -1
|
@@ -0,0 +1,232 @@
|
|
|
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 run tool', async () => {
|
|
35
|
+
const tools = await client.listTools();
|
|
36
|
+
expect(tools).toHaveLength(6);
|
|
37
|
+
const claudeCodeTool = tools.find((t) => t.name === 'run');
|
|
38
|
+
expect(claudeCodeTool).toEqual({
|
|
39
|
+
name: 'run',
|
|
40
|
+
description: expect.stringContaining('AI Agent Runner'),
|
|
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('sonnet'),
|
|
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_processes')).toBe(true);
|
|
70
|
+
expect(tools.some((t) => t.name === 'get_result')).toBe(true);
|
|
71
|
+
expect(tools.some((t) => t.name === 'kill_process')).toBe(true);
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
describe('Basic Operations', () => {
|
|
75
|
+
it('should execute a simple prompt', async () => {
|
|
76
|
+
const response = await client.callTool('run', {
|
|
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
|
+
// run now returns a PID immediately
|
|
87
|
+
const response = await client.callTool('run', {
|
|
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('run', {
|
|
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('run', {
|
|
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('run', {
|
|
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 run', async () => {
|
|
131
|
+
const response = await client.callTool('run', {
|
|
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 using get_result
|
|
145
|
+
const pid = parseInt(pidMatch[1]);
|
|
146
|
+
const result = await client.callTool('get_result', { pid });
|
|
147
|
+
const resultText = result[0].text;
|
|
148
|
+
const processData = JSON.parse(resultText);
|
|
149
|
+
// Verify that the model was set correctly
|
|
150
|
+
expect(processData.model).toBe('haiku');
|
|
151
|
+
});
|
|
152
|
+
it('should pass non-alias model names unchanged', async () => {
|
|
153
|
+
const response = await client.callTool('run', {
|
|
154
|
+
prompt: 'Test with sonnet model',
|
|
155
|
+
workFolder: testDir,
|
|
156
|
+
model: 'sonnet'
|
|
157
|
+
});
|
|
158
|
+
expect(response).toEqual([{
|
|
159
|
+
type: 'text',
|
|
160
|
+
text: expect.stringContaining('pid'),
|
|
161
|
+
}]);
|
|
162
|
+
// Extract PID
|
|
163
|
+
const responseText = response[0].text;
|
|
164
|
+
const pidMatch = responseText.match(/"pid":\s*(\d+)/);
|
|
165
|
+
const pid = parseInt(pidMatch[1]);
|
|
166
|
+
// Check the process using get_result
|
|
167
|
+
const result = await client.callTool('get_result', { pid });
|
|
168
|
+
const resultText = result[0].text;
|
|
169
|
+
const processData = JSON.parse(resultText);
|
|
170
|
+
// The model should be unchanged
|
|
171
|
+
expect(processData.model).toBe('sonnet');
|
|
172
|
+
});
|
|
173
|
+
it('should work without specifying a model', async () => {
|
|
174
|
+
const response = await client.callTool('run', {
|
|
175
|
+
prompt: 'Test without model parameter',
|
|
176
|
+
workFolder: testDir
|
|
177
|
+
});
|
|
178
|
+
expect(response).toEqual([{
|
|
179
|
+
type: 'text',
|
|
180
|
+
text: expect.stringContaining('pid'),
|
|
181
|
+
}]);
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
describe('Debug Mode', () => {
|
|
185
|
+
it('should log debug information when enabled', async () => {
|
|
186
|
+
// Debug logs go to stderr, which we capture in the client
|
|
187
|
+
const response = await client.callTool('run', {
|
|
188
|
+
prompt: 'Debug test prompt',
|
|
189
|
+
workFolder: testDir,
|
|
190
|
+
});
|
|
191
|
+
expect(response).toBeTruthy();
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
});
|
|
195
|
+
describe('Integration Tests (Local Only)', () => {
|
|
196
|
+
let client;
|
|
197
|
+
let testDir;
|
|
198
|
+
beforeEach(async () => {
|
|
199
|
+
testDir = mkdtempSync(join(tmpdir(), 'claude-code-integration-'));
|
|
200
|
+
// Initialize client without mocks for real Claude testing
|
|
201
|
+
client = new MCPTestClient('dist/server.js', {
|
|
202
|
+
MCP_CLAUDE_DEBUG: 'true',
|
|
203
|
+
});
|
|
204
|
+
});
|
|
205
|
+
afterEach(async () => {
|
|
206
|
+
if (client) {
|
|
207
|
+
await client.disconnect();
|
|
208
|
+
}
|
|
209
|
+
rmSync(testDir, { recursive: true, force: true });
|
|
210
|
+
});
|
|
211
|
+
// These tests will only run locally when Claude is available
|
|
212
|
+
it.skip('should create a file with real Claude CLI', async () => {
|
|
213
|
+
await client.connect();
|
|
214
|
+
const response = await client.callTool('run', {
|
|
215
|
+
prompt: 'Create a file called hello.txt with content "Hello from Claude"',
|
|
216
|
+
workFolder: testDir,
|
|
217
|
+
});
|
|
218
|
+
const filePath = join(testDir, 'hello.txt');
|
|
219
|
+
expect(existsSync(filePath)).toBe(true);
|
|
220
|
+
expect(readFileSync(filePath, 'utf-8')).toContain('Hello from Claude');
|
|
221
|
+
});
|
|
222
|
+
it.skip('should handle git operations with real Claude CLI', async () => {
|
|
223
|
+
await client.connect();
|
|
224
|
+
// Initialize git repo
|
|
225
|
+
const response = await client.callTool('run', {
|
|
226
|
+
prompt: 'Initialize a git repository and create a README.md file',
|
|
227
|
+
workFolder: testDir,
|
|
228
|
+
});
|
|
229
|
+
expect(existsSync(join(testDir, '.git'))).toBe(true);
|
|
230
|
+
expect(existsSync(join(testDir, 'README.md'))).toBe(true);
|
|
231
|
+
});
|
|
232
|
+
});
|
|
@@ -0,0 +1,135 @@
|
|
|
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('run', {
|
|
34
|
+
workFolder: testDir,
|
|
35
|
+
})).rejects.toThrow(/prompt/i);
|
|
36
|
+
});
|
|
37
|
+
it('should reject invalid prompt type', async () => {
|
|
38
|
+
await expect(client.callTool('run', {
|
|
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('run', {
|
|
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('run', {
|
|
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('run', {
|
|
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('run', {
|
|
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('run', {
|
|
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('run', {
|
|
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('run', {
|
|
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('run', {
|
|
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('run', {
|
|
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('run', {
|
|
130
|
+
prompt: 'Read file',
|
|
131
|
+
workFolder: maliciousPath,
|
|
132
|
+
})).rejects.toThrow(/(does not exist|ENOTDIR)/i);
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
});
|
|
@@ -0,0 +1,291 @@
|
|
|
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: class extends Error {
|
|
34
|
+
code;
|
|
35
|
+
constructor(code, message) {
|
|
36
|
+
super(message);
|
|
37
|
+
this.code = code;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}));
|
|
41
|
+
const mockExistsSync = vi.mocked(existsSync);
|
|
42
|
+
const mockSpawn = vi.mocked(spawn);
|
|
43
|
+
const mockHomedir = vi.mocked(homedir);
|
|
44
|
+
describe('Error Handling Tests', () => {
|
|
45
|
+
let consoleErrorSpy;
|
|
46
|
+
let originalEnv;
|
|
47
|
+
let errorHandler = null;
|
|
48
|
+
function setupServerMock() {
|
|
49
|
+
errorHandler = null;
|
|
50
|
+
vi.mocked(Server).mockImplementation(function () {
|
|
51
|
+
this.setRequestHandler = vi.fn();
|
|
52
|
+
this.connect = vi.fn();
|
|
53
|
+
this.close = vi.fn();
|
|
54
|
+
Object.defineProperty(this, 'onerror', {
|
|
55
|
+
get() { return errorHandler; },
|
|
56
|
+
set(handler) { errorHandler = handler; },
|
|
57
|
+
enumerable: true,
|
|
58
|
+
configurable: true
|
|
59
|
+
});
|
|
60
|
+
return this;
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
beforeEach(() => {
|
|
64
|
+
vi.clearAllMocks();
|
|
65
|
+
vi.resetModules();
|
|
66
|
+
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => { });
|
|
67
|
+
originalEnv = { ...process.env };
|
|
68
|
+
process.env = { ...originalEnv };
|
|
69
|
+
});
|
|
70
|
+
afterEach(() => {
|
|
71
|
+
consoleErrorSpy.mockRestore();
|
|
72
|
+
process.env = originalEnv;
|
|
73
|
+
});
|
|
74
|
+
describe('CallToolRequest Error Cases', () => {
|
|
75
|
+
it('should throw error for unknown tool name', async () => {
|
|
76
|
+
mockHomedir.mockReturnValue('/home/user');
|
|
77
|
+
mockExistsSync.mockReturnValue(true);
|
|
78
|
+
// Set up Server mock before importing the module
|
|
79
|
+
setupServerMock();
|
|
80
|
+
const module = await import('../server.js');
|
|
81
|
+
// @ts-ignore
|
|
82
|
+
const { ClaudeCodeServer } = module;
|
|
83
|
+
const server = new ClaudeCodeServer();
|
|
84
|
+
const mockServerInstance = vi.mocked(Server).mock.results[0].value;
|
|
85
|
+
const callToolCall = mockServerInstance.setRequestHandler.mock.calls.find((call) => call[0].name === 'callTool');
|
|
86
|
+
const handler = callToolCall[1];
|
|
87
|
+
await expect(handler({
|
|
88
|
+
params: {
|
|
89
|
+
name: 'unknown_tool',
|
|
90
|
+
arguments: {}
|
|
91
|
+
}
|
|
92
|
+
})).rejects.toThrow('Tool unknown_tool not found');
|
|
93
|
+
});
|
|
94
|
+
it('should handle timeout errors', async () => {
|
|
95
|
+
mockHomedir.mockReturnValue('/home/user');
|
|
96
|
+
mockExistsSync.mockReturnValue(true);
|
|
97
|
+
setupServerMock();
|
|
98
|
+
const module = await import('../server.js');
|
|
99
|
+
// @ts-ignore
|
|
100
|
+
const { ClaudeCodeServer } = module;
|
|
101
|
+
const { McpError } = await import('@modelcontextprotocol/sdk/types.js');
|
|
102
|
+
const server = new ClaudeCodeServer();
|
|
103
|
+
const mockServerInstance = vi.mocked(Server).mock.results[0].value;
|
|
104
|
+
// Find the callTool handler
|
|
105
|
+
let callToolHandler;
|
|
106
|
+
for (const call of mockServerInstance.setRequestHandler.mock.calls) {
|
|
107
|
+
if (call[0].name === 'callTool') {
|
|
108
|
+
callToolHandler = call[1];
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
// Mock spawn to return process without PID
|
|
113
|
+
mockSpawn.mockImplementation(() => {
|
|
114
|
+
const mockProcess = new EventEmitter();
|
|
115
|
+
mockProcess.stdout = new EventEmitter();
|
|
116
|
+
mockProcess.stderr = new EventEmitter();
|
|
117
|
+
mockProcess.stdout.on = vi.fn();
|
|
118
|
+
mockProcess.stderr.on = vi.fn();
|
|
119
|
+
mockProcess.pid = undefined; // No PID to simulate process start failure
|
|
120
|
+
return mockProcess;
|
|
121
|
+
});
|
|
122
|
+
// Call handler
|
|
123
|
+
await expect(callToolHandler({
|
|
124
|
+
params: {
|
|
125
|
+
name: 'run',
|
|
126
|
+
arguments: {
|
|
127
|
+
prompt: 'test',
|
|
128
|
+
workFolder: '/tmp'
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
})).rejects.toThrow('Failed to start claude CLI process');
|
|
132
|
+
});
|
|
133
|
+
it('should handle invalid argument types', async () => {
|
|
134
|
+
mockHomedir.mockReturnValue('/home/user');
|
|
135
|
+
mockExistsSync.mockReturnValue(true);
|
|
136
|
+
setupServerMock();
|
|
137
|
+
const module = await import('../server.js');
|
|
138
|
+
// @ts-ignore
|
|
139
|
+
const { ClaudeCodeServer } = module;
|
|
140
|
+
const server = new ClaudeCodeServer();
|
|
141
|
+
const mockServerInstance = vi.mocked(Server).mock.results[0].value;
|
|
142
|
+
const callToolCall = mockServerInstance.setRequestHandler.mock.calls.find((call) => call[0].name === 'callTool');
|
|
143
|
+
const handler = callToolCall[1];
|
|
144
|
+
await expect(handler({
|
|
145
|
+
params: {
|
|
146
|
+
name: 'run',
|
|
147
|
+
arguments: 'invalid-should-be-object'
|
|
148
|
+
}
|
|
149
|
+
})).rejects.toThrow();
|
|
150
|
+
});
|
|
151
|
+
it('should include CLI error details in error message', async () => {
|
|
152
|
+
mockHomedir.mockReturnValue('/home/user');
|
|
153
|
+
mockExistsSync.mockReturnValue(true);
|
|
154
|
+
setupServerMock();
|
|
155
|
+
const module = await import('../server.js');
|
|
156
|
+
// @ts-ignore
|
|
157
|
+
const { ClaudeCodeServer } = module;
|
|
158
|
+
const server = new ClaudeCodeServer();
|
|
159
|
+
const mockServerInstance = vi.mocked(Server).mock.results[0].value;
|
|
160
|
+
const callToolCall = mockServerInstance.setRequestHandler.mock.calls.find((call) => call[0].name === 'callTool');
|
|
161
|
+
const handler = callToolCall[1];
|
|
162
|
+
// Create a simple mock process
|
|
163
|
+
mockSpawn.mockImplementation(() => {
|
|
164
|
+
const mockProcess = Object.create(EventEmitter.prototype);
|
|
165
|
+
EventEmitter.call(mockProcess);
|
|
166
|
+
mockProcess.stdout = Object.create(EventEmitter.prototype);
|
|
167
|
+
EventEmitter.call(mockProcess.stdout);
|
|
168
|
+
mockProcess.stderr = Object.create(EventEmitter.prototype);
|
|
169
|
+
EventEmitter.call(mockProcess.stderr);
|
|
170
|
+
mockProcess.stdout.on = vi.fn((event, callback) => {
|
|
171
|
+
if (event === 'data') {
|
|
172
|
+
// Send some stdout data
|
|
173
|
+
process.nextTick(() => callback('stdout content'));
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
mockProcess.stderr.on = vi.fn((event, callback) => {
|
|
177
|
+
if (event === 'data') {
|
|
178
|
+
// Send some stderr data
|
|
179
|
+
process.nextTick(() => callback('stderr content'));
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
// Emit error/close event after data is sent
|
|
183
|
+
setTimeout(() => {
|
|
184
|
+
mockProcess.emit('close', 1);
|
|
185
|
+
}, 1);
|
|
186
|
+
return mockProcess;
|
|
187
|
+
});
|
|
188
|
+
await expect(handler({
|
|
189
|
+
params: {
|
|
190
|
+
name: 'run',
|
|
191
|
+
arguments: {
|
|
192
|
+
prompt: 'test',
|
|
193
|
+
workFolder: '/tmp'
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
})).rejects.toThrow();
|
|
197
|
+
});
|
|
198
|
+
});
|
|
199
|
+
describe('Process Spawn Error Cases', () => {
|
|
200
|
+
it('should handle spawn ENOENT error', async () => {
|
|
201
|
+
const module = await import('../server.js');
|
|
202
|
+
// @ts-ignore
|
|
203
|
+
const { spawnAsync } = module;
|
|
204
|
+
const mockProcess = new EventEmitter();
|
|
205
|
+
mockProcess.stdout = new EventEmitter();
|
|
206
|
+
mockProcess.stderr = new EventEmitter();
|
|
207
|
+
mockProcess.stdout.on = vi.fn();
|
|
208
|
+
mockProcess.stderr.on = vi.fn();
|
|
209
|
+
mockSpawn.mockReturnValue(mockProcess);
|
|
210
|
+
const promise = spawnAsync('nonexistent-command', []);
|
|
211
|
+
// Simulate ENOENT error
|
|
212
|
+
setTimeout(() => {
|
|
213
|
+
const error = new Error('spawn ENOENT');
|
|
214
|
+
error.code = 'ENOENT';
|
|
215
|
+
error.path = 'nonexistent-command';
|
|
216
|
+
error.syscall = 'spawn';
|
|
217
|
+
mockProcess.emit('error', error);
|
|
218
|
+
}, 10);
|
|
219
|
+
await expect(promise).rejects.toThrow('Spawn error');
|
|
220
|
+
await expect(promise).rejects.toThrow('nonexistent-command');
|
|
221
|
+
});
|
|
222
|
+
it('should handle generic spawn errors', async () => {
|
|
223
|
+
const module = await import('../server.js');
|
|
224
|
+
// @ts-ignore
|
|
225
|
+
const { spawnAsync } = module;
|
|
226
|
+
const mockProcess = new EventEmitter();
|
|
227
|
+
mockProcess.stdout = new EventEmitter();
|
|
228
|
+
mockProcess.stderr = new EventEmitter();
|
|
229
|
+
mockProcess.stdout.on = vi.fn();
|
|
230
|
+
mockProcess.stderr.on = vi.fn();
|
|
231
|
+
mockSpawn.mockReturnValue(mockProcess);
|
|
232
|
+
const promise = spawnAsync('test', []);
|
|
233
|
+
// Simulate generic error
|
|
234
|
+
setTimeout(() => {
|
|
235
|
+
mockProcess.emit('error', new Error('Generic spawn error'));
|
|
236
|
+
}, 10);
|
|
237
|
+
await expect(promise).rejects.toThrow('Generic spawn error');
|
|
238
|
+
});
|
|
239
|
+
it('should accumulate stderr output before error', async () => {
|
|
240
|
+
const module = await import('../server.js');
|
|
241
|
+
// @ts-ignore
|
|
242
|
+
const { spawnAsync } = module;
|
|
243
|
+
const mockProcess = new EventEmitter();
|
|
244
|
+
mockProcess.stdout = new EventEmitter();
|
|
245
|
+
mockProcess.stderr = new EventEmitter();
|
|
246
|
+
let stderrHandler;
|
|
247
|
+
mockProcess.stdout.on = vi.fn();
|
|
248
|
+
mockProcess.stderr.on = vi.fn((event, handler) => {
|
|
249
|
+
if (event === 'data')
|
|
250
|
+
stderrHandler = handler;
|
|
251
|
+
});
|
|
252
|
+
mockSpawn.mockReturnValue(mockProcess);
|
|
253
|
+
const promise = spawnAsync('test', []);
|
|
254
|
+
// Simulate stderr data then error
|
|
255
|
+
setTimeout(() => {
|
|
256
|
+
stderrHandler('error line 1\n');
|
|
257
|
+
stderrHandler('error line 2\n');
|
|
258
|
+
mockProcess.emit('error', new Error('Command failed'));
|
|
259
|
+
}, 10);
|
|
260
|
+
await expect(promise).rejects.toThrow('error line 1\nerror line 2');
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
describe('Server Initialization Errors', () => {
|
|
264
|
+
it('should handle CLI path not found gracefully', async () => {
|
|
265
|
+
// Mock no CLI found anywhere
|
|
266
|
+
mockHomedir.mockReturnValue('/home/user');
|
|
267
|
+
mockExistsSync.mockReturnValue(false);
|
|
268
|
+
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => { });
|
|
269
|
+
setupServerMock();
|
|
270
|
+
const module = await import('../server.js');
|
|
271
|
+
// @ts-ignore
|
|
272
|
+
const { ClaudeCodeServer } = module;
|
|
273
|
+
const server = new ClaudeCodeServer();
|
|
274
|
+
expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining('Claude CLI not found'));
|
|
275
|
+
consoleWarnSpy.mockRestore();
|
|
276
|
+
});
|
|
277
|
+
it('should handle server connection errors', async () => {
|
|
278
|
+
mockHomedir.mockReturnValue('/home/user');
|
|
279
|
+
mockExistsSync.mockReturnValue(true);
|
|
280
|
+
setupServerMock();
|
|
281
|
+
const module = await import('../server.js');
|
|
282
|
+
// @ts-ignore
|
|
283
|
+
const { ClaudeCodeServer } = module;
|
|
284
|
+
const server = new ClaudeCodeServer();
|
|
285
|
+
// Mock connection failure
|
|
286
|
+
const mockServerInstance = vi.mocked(Server).mock.results[0].value;
|
|
287
|
+
mockServerInstance.connect.mockRejectedValue(new Error('Connection failed'));
|
|
288
|
+
await expect(server.run()).rejects.toThrow('Connection failed');
|
|
289
|
+
});
|
|
290
|
+
});
|
|
291
|
+
});
|