-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsetup.js
More file actions
456 lines (383 loc) · 15.7 KB
/
Copy pathsetup.js
File metadata and controls
456 lines (383 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
#!/usr/bin/env node
import { promisify } from "util";
import { exec } from "child_process";
import fs from "fs/promises";
import path from "path";
import os from "os";
import readline from "readline";
const execAsync = promisify(exec);
class SetupScript {
constructor() {
this.projectDir = process.cwd();
this.configPath = this.getClaudeConfigPath();
this.serverConfigPath = path.join(this.projectDir, "config.json");
this.selectedDistribution = null;
}
getClaudeConfigPath() {
const platform = os.platform();
if (platform === "win32") {
return path.join(os.homedir(), "AppData", "Roaming", "Claude", "claude_desktop_config.json");
} else if (platform === "darwin") {
return path.join(os.homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
} else {
return path.join(os.homedir(), ".config", "Claude", "claude_desktop_config.json");
}
}
async promptUser(question) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
return new Promise((resolve) => {
rl.question(question, (answer) => {
rl.close();
resolve(answer.trim());
});
});
}
async detectWSLDistributions() {
console.log("🔍 Detecting available WSL distributions...\n");
try {
const { stdout } = await execAsync("wsl -l -v");
// Parse WSL output to extract distribution names and states
const lines = stdout.split('\n').filter(line => line.trim());
const distributions = [];
for (let i = 1; i < lines.length; i++) { // Skip header
const line = lines[i].trim();
if (line) {
// Remove special characters and parse
const cleanLine = line.replace(/[\x00-\x1f\x7f-\x9f]/g, '');
const parts = cleanLine.split(/\s+/);
if (parts.length >= 3) {
const name = parts[0].replace(/^\*\s*/, ''); // Remove default marker
const state = parts[1];
const version = parts[2];
if (state === "Running" || state === "Stopped") {
distributions.push({
name: name,
state: state,
version: version,
isDefault: line.includes('*')
});
}
}
}
}
return distributions;
} catch (error) {
throw new Error(`Failed to detect WSL distributions: ${error.message}`);
}
}
async selectDistribution(distributions) {
if (distributions.length === 0) {
throw new Error("No WSL distributions found. Please install a Linux distribution first.");
}
console.log("📋 Available WSL distributions:");
distributions.forEach((dist, index) => {
const defaultMarker = dist.isDefault ? " (default)" : "";
const stateIcon = dist.state === "Running" ? "🟢" : "🔴";
console.log(`${index + 1}. ${stateIcon} ${dist.name} - ${dist.state}, WSL${dist.version}${defaultMarker}`);
});
console.log("");
let selectedIndex;
if (distributions.length === 1) {
console.log(`🎯 Only one distribution available: ${distributions[0].name}`);
selectedIndex = 0;
} else {
const answer = await this.promptUser("Select distribution number (or press Enter for default): ");
if (answer === "") {
// Find default distribution
const defaultDist = distributions.find(d => d.isDefault);
if (defaultDist) {
selectedIndex = distributions.indexOf(defaultDist);
console.log(`📌 Using default distribution: ${defaultDist.name}`);
} else {
selectedIndex = 0;
console.log(`📌 Using first distribution: ${distributions[0].name}`);
}
} else {
selectedIndex = parseInt(answer) - 1;
if (isNaN(selectedIndex) || selectedIndex < 0 || selectedIndex >= distributions.length) {
throw new Error("Invalid selection. Please run setup again.");
}
}
}
const selected = distributions[selectedIndex];
console.log(`✅ Selected: ${selected.name}\n`);
return selected;
}
async testDistribution(distribution) {
console.log(`🧪 Testing ${distribution.name}...`);
try {
// Start the distribution if it's stopped
if (distribution.state === "Stopped") {
console.log(` Starting ${distribution.name}...`);
await execAsync(`wsl -d ${distribution.name} -- echo "starting"`);
}
// Test basic commands
const tests = [
{ cmd: "echo 'Hello WSL'", desc: "Basic echo test" },
{ cmd: "whoami", desc: "User identification" },
{ cmd: "pwd", desc: "Working directory" },
{ cmd: "uname -s", desc: "Operating system" }
];
for (const test of tests) {
try {
const { stdout } = await execAsync(`wsl -d ${distribution.name} -- ${test.cmd}`);
console.log(` ✅ ${test.desc}: ${stdout.trim()}`);
} catch (error) {
console.log(` ⚠️ ${test.desc}: ${error.message}`);
}
}
console.log(`✅ ${distribution.name} is working correctly\n`);
} catch (error) {
throw new Error(`Failed to test ${distribution.name}: ${error.message}`);
}
}
async checkPrerequisites() {
console.log("🔍 Checking prerequisites...\n");
// Check Node.js version
try {
const { stdout } = await execAsync("node --version");
const version = stdout.trim();
console.log(`✅ Node.js: ${version}`);
const majorVersion = parseInt(version.slice(1).split('.')[0]);
if (majorVersion < 18) {
throw new Error("Node.js 18+ is required");
}
} catch (error) {
console.log("❌ Node.js not found or version too old");
throw error;
}
// Check WSL
try {
const { stdout } = await execAsync("wsl --version");
console.log("✅ WSL is installed");
} catch (error) {
console.log("❌ WSL not found");
throw new Error("WSL2 is required but not installed");
}
// Detect and select WSL distribution
try {
const distributions = await this.detectWSLDistributions();
this.selectedDistribution = await this.selectDistribution(distributions);
await this.testDistribution(this.selectedDistribution);
} catch (error) {
console.log("❌ WSL distribution setup failed");
throw error;
}
console.log("✅ All prerequisites check passed!\n");
}
async updateServerConfig() {
console.log("⚙️ Updating server configuration...\n");
try {
// Read existing config
let config = {};
try {
const configContent = await fs.readFile(this.serverConfigPath, "utf8");
config = JSON.parse(configContent);
} catch (error) {
// Use default config if file doesn't exist
config = {
wslDistribution: "auto-detect",
defaultTimeout: 30000,
scriptTimeout: 60000,
maxBufferSize: 10485760,
debugMode: false
};
}
// Update with selected distribution
config.wslDistribution = this.selectedDistribution.name;
config.selectedDistributionInfo = {
name: this.selectedDistribution.name,
state: this.selectedDistribution.state,
version: this.selectedDistribution.version,
isDefault: this.selectedDistribution.isDefault,
configuredAt: new Date().toISOString()
};
// Write updated config
await fs.writeFile(this.serverConfigPath, JSON.stringify(config, null, 2));
console.log(`✅ Server configured to use: ${this.selectedDistribution.name}`);
console.log(`📄 Configuration saved to: ${this.serverConfigPath}\n`);
} catch (error) {
throw new Error(`Failed to update server configuration: ${error.message}`);
}
}
async installDependencies() {
console.log("📦 Installing Node.js dependencies...\n");
try {
const { stdout, stderr } = await execAsync("npm install", { cwd: this.projectDir });
console.log("✅ Dependencies installed successfully");
if (stderr) {
console.log("⚠️ Warnings:", stderr);
}
} catch (error) {
console.log("❌ Failed to install dependencies");
throw error;
}
console.log("");
}
async runTests() {
console.log("🧪 Running tests to verify setup...\n");
try {
// Set environment variable for tests to use selected distribution
process.env.WSL_DISTRIBUTION = this.selectedDistribution.name;
const { stdout } = await execAsync("npm test", {
cwd: this.projectDir,
env: { ...process.env, WSL_DISTRIBUTION: this.selectedDistribution.name }
});
console.log(stdout);
} catch (error) {
console.log("❌ Tests failed");
console.log(error.stdout || error.message);
throw error;
}
}
async loadExistingClaudeConfig() {
try {
const configContent = await fs.readFile(this.configPath, "utf8");
return JSON.parse(configContent);
} catch (error) {
if (error.code === 'ENOENT') {
// File doesn't exist, return empty config
return {};
} else if (error instanceof SyntaxError) {
// Invalid JSON, backup and start fresh
const backupPath = `${this.configPath}.backup.${Date.now()}`;
await fs.copyFile(this.configPath, backupPath);
console.log(`⚠️ Invalid JSON in config file. Backed up to: ${backupPath}`);
return {};
} else {
throw error;
}
}
}
async generateConfig() {
console.log("⚙️ Updating Claude Desktop configuration...\n");
const serverPath = path.join(this.projectDir, "src", "index.js").replace(/\\/g, "\\\\");
const newMcpServer = {
"linux-bash": {
command: "node",
args: [serverPath],
env: {
WSL_DISTRIBUTION: this.selectedDistribution.name
}
}
};
// Load existing configuration
let existingConfig = await this.loadExistingClaudeConfig();
// Ensure mcpServers exists
if (!existingConfig.mcpServers) {
existingConfig.mcpServers = {};
console.log("📄 Creating new Claude Desktop configuration");
} else {
console.log("📄 Found existing Claude Desktop configuration");
// Show existing MCP servers
const existingServers = Object.keys(existingConfig.mcpServers);
if (existingServers.length > 0) {
console.log("📋 Existing MCP servers:");
existingServers.forEach(server => {
console.log(` • ${server}`);
});
}
}
// Check if our server already exists
if (existingConfig.mcpServers["linux-bash"]) {
console.log("⚠️ 'linux-bash' MCP server already exists - updating configuration");
} else {
console.log("➕ Adding new 'linux-bash' MCP server");
}
// Merge configurations - add our server without affecting others
const mergedConfig = {
...existingConfig,
mcpServers: {
...existingConfig.mcpServers,
...newMcpServer
}
};
// Create directory if it doesn't exist
await fs.mkdir(path.dirname(this.configPath), { recursive: true });
// Write merged configuration
await fs.writeFile(this.configPath, JSON.stringify(mergedConfig, null, 2));
console.log(`✅ Configuration updated at: ${this.configPath}`);
// Show final MCP servers list
const finalServers = Object.keys(mergedConfig.mcpServers);
console.log("📋 All configured MCP servers:");
finalServers.forEach(server => {
const isNew = server === "linux-bash";
const icon = isNew ? "🆕" : "📌";
const label = isNew ? " (newly added)" : "";
console.log(` ${icon} ${server}${label}`);
});
console.log("");
return this.configPath;
}
async printInstructions(configPath) {
console.log("🎉 Setup completed successfully!\n");
console.log("📋 Configuration Summary:");
console.log(` • WSL Distribution: ${this.selectedDistribution.name}`);
console.log(` • Distribution State: ${this.selectedDistribution.state}`);
console.log(` • WSL Version: ${this.selectedDistribution.version}`);
console.log(` • Server Config: ${this.serverConfigPath}`);
console.log(` • Claude Config: ${configPath}\n`);
console.log("🔧 Claude Desktop Integration:");
console.log(" ✅ MCP server 'linux-bash' has been added to your Claude Desktop configuration");
console.log(" ✅ Existing MCP servers have been preserved");
console.log(" ✅ No existing configurations were modified or removed\n");
console.log("📋 Next steps:");
console.log("1. 🔄 Restart Claude Desktop application");
console.log("2. 🛠️ The 'linux-bash' MCP server should now be available alongside your existing servers");
console.log("3. 🧪 Try these example commands in Claude Desktop:");
console.log(" - 'Check WSL status and show system information'");
console.log(" - 'List files in /home directory'");
console.log(" - 'Show Linux distribution information'");
console.log(" - 'Create a system monitoring script and run it'\n");
console.log("📁 Project files:");
console.log(` - Server: ${path.join(this.projectDir, "src", "index.js")}`);
console.log(` - Server Config: ${this.serverConfigPath}`);
console.log(` - Claude Config: ${configPath}`);
console.log(` - Examples: ${path.join(this.projectDir, "examples")}`);
console.log(` - Tests: ${path.join(this.projectDir, "test")}\n`);
console.log("🔧 Available tools in 'linux-bash' MCP server:");
console.log(" - execute_bash_command: Run single bash commands");
console.log(" - execute_bash_script: Run bash script files with arguments");
console.log(" - create_bash_script: Create new bash scripts");
console.log(" - list_directory: List directory contents");
console.log(" - get_system_info: Get comprehensive system information");
console.log(" - check_wsl_status: Check WSL2 status and distribution info\n");
console.log("🔄 To change WSL distribution later:");
console.log(" Run 'npm run setup' again to reconfigure\n");
console.log("🔗 Integration notes:");
console.log(" • This server works alongside any existing MCP servers you have");
console.log(" • Your existing Claude Desktop configuration has been preserved");
console.log(" • You can use multiple MCP servers simultaneously in Claude Desktop\n");
console.log("📖 For more information, see README.md");
}
async run() {
try {
console.log("🚀 Linux Bash MCP Server Setup\n");
await this.checkPrerequisites();
await this.updateServerConfig();
await this.installDependencies();
await this.runTests();
const configPath = await this.generateConfig();
await this.printInstructions(configPath);
} catch (error) {
console.log("\n❌ Setup failed:", error.message);
console.log("\n🔧 Troubleshooting:");
console.log("1. Ensure WSL2 is installed: 'wsl --install'");
console.log("2. Install a Linux distribution: 'wsl --install -d Ubuntu' or 'wsl --install -d Debian'");
console.log("3. Update WSL: 'wsl --update'");
console.log("4. Check Node.js version: 'node --version' (requires 18+)");
console.log("5. List WSL distributions: 'wsl -l -v'");
console.log("6. See README.md for detailed instructions");
process.exit(1);
}
}
}
// Run setup if this file is executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
const setup = new SetupScript();
setup.run();
}
export default SetupScript;