-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsetup-claude-server.js
More file actions
executable file
·376 lines (327 loc) · 12 KB
/
setup-claude-server.js
File metadata and controls
executable file
·376 lines (327 loc) · 12 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
import { homedir, platform } from 'os';
import { join } from 'path';
import { readFileSync, writeFileSync, existsSync, appendFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import { exec } from "node:child_process";
import { version as nodeVersion } from 'process';
// Optional analytics - will gracefully degrade if posthog-node isn't available
let client = null;
let uniqueUserId = 'unknown';
try {
const { PostHog } = await import('posthog-node');
const machineIdModule = await import('node-machine-id');
client = new PostHog(
'phc_TFQqTkCwtFGxlwkXDY3gSs7uvJJcJu8GurfXd6mV063',
{
host: 'https://eu.i.posthog.com',
flushAt: 1, // send all every time
flushInterval: 0 //send always
}
);
// Get a unique user ID
uniqueUserId = machineIdModule.machineIdSync();
} catch (error) {
//console.error('Analytics module not available - continuing without tracking');
}
// Function to get npm version
async function getNpmVersion() {
try {
return new Promise((resolve, reject) => {
exec('npm --version', (error, stdout, stderr) => {
if (error) {
resolve('unknown');
return;
}
resolve(stdout.trim());
});
});
} catch (error) {
return 'unknown';
}
}
// Function to detect shell environment
function detectShell() {
// Check for Windows shells
if (process.platform === 'win32') {
if (process.env.TERM_PROGRAM === 'vscode') return 'vscode-terminal';
if (process.env.WT_SESSION) return 'windows-terminal';
if (process.env.SHELL?.includes('bash')) return 'git-bash';
if (process.env.TERM?.includes('xterm')) return 'xterm-on-windows';
if (process.env.ComSpec?.toLowerCase().includes('powershell')) return 'powershell';
if (process.env.PROMPT) return 'cmd';
// WSL detection
if (process.env.WSL_DISTRO_NAME || process.env.WSLENV) {
return `wsl-${process.env.WSL_DISTRO_NAME || 'unknown'}`;
}
return 'windows-unknown';
}
// Unix-based shells
if (process.env.SHELL) {
const shellPath = process.env.SHELL.toLowerCase();
if (shellPath.includes('bash')) return 'bash';
if (shellPath.includes('zsh')) return 'zsh';
if (shellPath.includes('fish')) return 'fish';
if (shellPath.includes('ksh')) return 'ksh';
if (shellPath.includes('csh')) return 'csh';
if (shellPath.includes('dash')) return 'dash';
return `other-unix-${shellPath.split('/').pop()}`;
}
// Terminal emulators and IDE terminals
if (process.env.TERM_PROGRAM) {
return process.env.TERM_PROGRAM.toLowerCase();
}
return 'unknown-shell';
}
// Function to determine execution context
function getExecutionContext() {
// Check if running from npx
const isNpx = process.env.npm_lifecycle_event === 'npx' ||
process.env.npm_execpath?.includes('npx') ||
process.env._?.includes('npx') ||
import.meta.url.includes('node_modules');
// Check if installed globally
const isGlobal = process.env.npm_config_global === 'true' ||
process.argv[1]?.includes('node_modules/.bin');
// Check if it's run from a script in package.json
const isNpmScript = !!process.env.npm_lifecycle_script;
return {
runMethod: isNpx ? 'npx' : (isGlobal ? 'global' : (isNpmScript ? 'npm_script' : 'direct')),
isCI: !!process.env.CI || !!process.env.GITHUB_ACTIONS || !!process.env.TRAVIS || !!process.env.CIRCLECI,
shell: detectShell()
};
}
// Helper function to get standard environment properties for tracking
let npmVersionCache = null;
async function getTrackingProperties(additionalProps = {}) {
if (npmVersionCache === null) {
npmVersionCache = await getNpmVersion();
}
const context = getExecutionContext();
return {
platform: platform(),
nodeVersion: nodeVersion,
npmVersion: npmVersionCache,
executionContext: context.runMethod,
isCI: context.isCI,
shell: context.shell,
timestamp: new Date().toISOString(),
...additionalProps
};
}
// Helper function for tracking that handles missing PostHog gracefully
async function trackEvent(eventName, additionalProps = {}) {
if (!client) return; // Skip tracking if PostHog client isn't available
try {
client.capture({
distinctId: uniqueUserId,
event: eventName,
properties: await getTrackingProperties(additionalProps)
});
} catch (error) {
// Silently fail if tracking fails - we don't want to break the setup process
//console.log(`Note: Event tracking unavailable for ${eventName}`);
}
}
// Initial tracking
trackEvent('npx_setup_start');
// Fix for Windows ESM path resolution
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Determine OS and set appropriate config path
const os = platform();
const isWindows = os === 'win32'; // Define isWindows variable
let claudeConfigPath;
switch (os) {
case 'win32':
claudeConfigPath = join(process.env.APPDATA, 'Claude', 'claude_desktop_config.json');
break;
case 'darwin':
claudeConfigPath = join(homedir(), 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
break;
case 'linux':
claudeConfigPath = join(homedir(), '.config', 'Claude', 'claude_desktop_config.json');
break;
default:
// Fallback for other platforms
claudeConfigPath = join(homedir(), '.claude_desktop_config.json');
}
// Setup logging
const LOG_FILE = join(__dirname, 'setup.log');
function logToFile(message, isError = false) {
const timestamp = new Date().toISOString();
const logMessage = `${timestamp} - ${isError ? 'ERROR: ' : ''}${message}\n`;
try {
appendFileSync(LOG_FILE, logMessage);
// For setup script, we'll still output to console but in JSON format
const jsonOutput = {
type: isError ? 'error' : 'info',
timestamp,
message
};
process.stdout.write(JSON.stringify(jsonOutput) + '\n');
} catch (err) {
// Last resort error handling
process.stderr.write(JSON.stringify({
type: 'error',
timestamp: new Date().toISOString(),
message: `Failed to write to log file: ${err.message}`
}) + '\n');
}
}
async function execAsync(command) {
return new Promise((resolve, reject) => {
// Use PowerShell on Windows for better Unicode support and consistency
const actualCommand = isWindows
? `cmd.exe /c ${command}`
: command;
exec(actualCommand, (error, stdout, stderr) => {
if (error) {
reject(error);
return;
}
resolve({ stdout, stderr });
});
});
}
async function restartClaude() {
try {
const platform = process.platform
// ignore errors on windows when claude is not running.
// just silently kill the process
try {
switch (platform) {
case "win32":
await execAsync(
`taskkill /F /IM "Claude.exe"`,
)
break;
case "darwin":
await execAsync(
`killall "Claude"`,
)
break;
case "linux":
await execAsync(
`pkill -f "claude"`,
)
break;
}
} catch {}
await new Promise((resolve) => setTimeout(resolve, 3000))
if (platform === "win32") {
// it will never start claude
// await execAsync(`start "" "Claude.exe"`)
} else if (platform === "darwin") {
await execAsync(`open -a "Claude"`)
} else if (platform === "linux") {
await execAsync(`claude`)
}
logToFile(`Claude has been restarted.`)
} catch (error) {
await trackEvent('npx_setup_restart_claude_error', { error: error.message });
logToFile(`Failed to restart Claude: ${error}`, true)
}
}
// Check if config file exists and create default if not
if (!existsSync(claudeConfigPath)) {
logToFile(`Claude config file not found at: ${claudeConfigPath}`);
logToFile('Creating default config file...');
// Track new installation
await trackEvent('npx_setup_create_default_config');
// Create the directory if it doesn't exist
const configDir = dirname(claudeConfigPath);
if (!existsSync(configDir)) {
import('fs').then(fs => fs.mkdirSync(configDir, { recursive: true }));
}
// Create default config with shell based on platform
const defaultConfig = {
"serverConfig": isWindows
? {
"command": "cmd.exe",
"args": ["/c"]
}
: {
"command": "/bin/sh",
"args": ["-c"]
}
};
writeFileSync(claudeConfigPath, JSON.stringify(defaultConfig, null, 2));
logToFile('Default config file created. Please update it with your Claude API credentials.');
}
// Main function to export for ESM compatibility
export default async function setup() {
try {
// Read existing config
const configData = readFileSync(claudeConfigPath, 'utf8');
const config = JSON.parse(configData);
// Prepare the new server config based on OS
// Determine if running through npx or locally
const isNpx = import.meta.url.includes('node_modules');
// Fix Windows path handling for npx execution
let serverConfig;
if (isNpx) {
serverConfig = {
"command": isWindows ? "npx.cmd" : "npx",
"args": [
"@wonderwhy-er/desktop-commander"
]
};
} else {
// For local installation, use absolute path to handle Windows properly
const indexPath = join(__dirname, 'dist', 'index.js');
serverConfig = {
"command": "node",
"args": [
indexPath.replace(/\\/g, '\\\\') // Double escape backslashes for JSON
]
};
}
// Initialize mcpServers if it doesn't exist
if (!config.mcpServers) {
config.mcpServers = {};
}
// Check if the old "desktopCommander" exists and remove it
if (config.mcpServers.desktopCommander) {
logToFile('Found old "desktopCommander" installation. Removing it...');
delete config.mcpServers.desktopCommander;
}
// Add or update the terminal server config with the proper name "desktop-commander"
config.mcpServers["desktop-commander"] = serverConfig;
// Write the updated config back
writeFileSync(claudeConfigPath, JSON.stringify(config, null, 2), 'utf8');
await trackEvent('npx_setup_update_config');
logToFile('Successfully added MCP server to Claude configuration!');
logToFile(`Configuration location: ${claudeConfigPath}`);
logToFile('\nTo use the server:\n1. Restart Claude if it\'s currently running\n2. The server will be available as "desktop-commander" in Claude\'s MCP server list');
await restartClaude();
await trackEvent('npx_setup_complete');
// Safe shutdown
if (client) {
try {
await client.shutdown();
} catch (error) {
// Ignore shutdown errors
}
}
} catch (error) {
await trackEvent('npx_setup_final_error', { error: error.message });
logToFile(`Error updating Claude configuration: ${error}`, true);
// Safe shutdown
if (client) {
try {
await client.shutdown();
} catch (error) {
// Ignore shutdown errors
}
}
process.exit(1);
}
}
// Allow direct execution
if (process.argv.length >= 2 && process.argv[1] === fileURLToPath(import.meta.url)) {
setup().catch(error => {
logToFile(`Fatal error: ${error}`, true);
process.exit(1);
});
}