-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathindex.ts
More file actions
609 lines (553 loc) · 19.8 KB
/
Copy pathindex.ts
File metadata and controls
609 lines (553 loc) · 19.8 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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { execSync } from "child_process";
import { platform } from "os";
// Detect operating system
const isWindows = platform() === 'win32';
// Create server instance
const server = new McpServer({
name: "windows-command-line",
version: "0.3.0",
});
// Helper function to handle command execution based on platform
function executeCommand(command: string, options: any = {}) {
if (isWindows) {
return execSync(command, options);
} else {
// Log warning for non-Windows environments
console.error(`Warning: Running in a non-Windows environment (${platform()}). Windows commands may not work.`);
// For testing purposes on non-Windows platforms
try {
// For Linux/MacOS, we'll strip cmd.exe and powershell.exe references
let modifiedCmd = command;
// Replace cmd.exe /c with empty string
modifiedCmd = modifiedCmd.replace(/cmd\.exe\s+\/c\s+/i, '');
// Replace powershell.exe -Command with empty string or a compatible command
modifiedCmd = modifiedCmd.replace(/powershell\.exe\s+-Command\s+("|')/i, '');
// Remove trailing quotes if we removed powershell -Command
if (modifiedCmd !== command) {
modifiedCmd = modifiedCmd.replace(/("|')$/, '');
}
console.error(`Attempting to execute modified command: ${modifiedCmd}`);
return execSync(modifiedCmd, options);
} catch (error) {
console.error(`Error executing modified command: ${error}`);
return Buffer.from(`This tool requires a Windows environment. Current platform: ${platform()}`);
}
}
}
// Register the list_running_processes tool
server.tool(
"list_running_processes",
"List all running processes on the system. Can be filtered by providing an optional filter string that will match against process names.",
{
filter: z.string().optional().describe("Optional filter string to match against process names"),
},
async ({ filter }) => {
try {
let cmd;
if (isWindows) {
cmd = "powershell.exe -Command \"Get-Process";
if (filter) {
// Add filter if provided
cmd += ` | Where-Object { $_.ProcessName -like '*${filter}*' }`;
}
cmd += " | Select-Object Id, ProcessName, CPU, WorkingSet, Description | Format-Table -AutoSize | Out-String\"";
} else {
// Fallback for Unix systems
cmd = "ps aux";
if (filter) {
cmd += ` | grep -i ${filter}`;
}
}
const stdout = executeCommand(cmd);
return {
content: [
{
type: "text",
text: stdout.toString(),
},
],
};
} catch (error) {
return {
isError: true,
content: [
{
type: "text",
text: `Error listing processes: ${error}`,
},
],
};
}
}
);
// Register the get_system_info tool
server.tool(
"get_system_info",
"Retrieve system information including OS, hardware, and user details. Can provide basic or full details.",
{
detail: z.enum(["basic", "full"]).default("basic").describe("Level of detail"),
},
async ({ detail }) => {
try {
let cmd;
if (isWindows) {
cmd = "powershell.exe -Command \"";
if (detail === "basic") {
cmd += "$OS = Get-CimInstance Win32_OperatingSystem; " +
"$CS = Get-CimInstance Win32_ComputerSystem; " +
"$Processor = Get-CimInstance Win32_Processor; " +
"Write-Output 'OS: ' $OS.Caption $OS.Version; " +
"Write-Output 'Computer: ' $CS.Manufacturer $CS.Model; " +
"Write-Output 'CPU: ' $Processor.Name; " +
"Write-Output 'Memory: ' [math]::Round($OS.TotalVisibleMemorySize/1MB, 2) 'GB'";
} else {
cmd += "$OS = Get-CimInstance Win32_OperatingSystem; " +
"$CS = Get-CimInstance Win32_ComputerSystem; " +
"$Processor = Get-CimInstance Win32_Processor; " +
"$Disk = Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3'; " +
"$Network = Get-CimInstance Win32_NetworkAdapterConfiguration | Where-Object {$_.IPAddress -ne $null}; " +
"Write-Output '=== OPERATING SYSTEM ==='; " +
"Write-Output ('OS: ' + $OS.Caption + ' ' + $OS.Version); " +
"Write-Output ('Architecture: ' + $OS.OSArchitecture); " +
"Write-Output ('Install Date: ' + $OS.InstallDate); " +
"Write-Output ('Last Boot: ' + $OS.LastBootUpTime); " +
"Write-Output (''; '=== HARDWARE ==='); " +
"Write-Output ('Manufacturer: ' + $CS.Manufacturer); " +
"Write-Output ('Model: ' + $CS.Model); " +
"Write-Output ('Serial Number: ' + (Get-CimInstance Win32_BIOS).SerialNumber); " +
"Write-Output ('Processor: ' + $Processor.Name); " +
"Write-Output ('Cores: ' + $Processor.NumberOfCores); " +
"Write-Output ('Logical Processors: ' + $Processor.NumberOfLogicalProcessors); " +
"Write-Output ('Memory: ' + [math]::Round($OS.TotalVisibleMemorySize/1MB, 2) + ' GB'); " +
"Write-Output (''; '=== STORAGE ==='); " +
"foreach($drive in $Disk) { " +
"Write-Output ('Drive ' + $drive.DeviceID + ' - ' + [math]::Round($drive.Size/1GB, 2) + ' GB (Free: ' + [math]::Round($drive.FreeSpace/1GB, 2) + ' GB)') " +
"}; " +
"Write-Output (''; '=== NETWORK ==='); " +
"foreach($adapter in $Network) { " +
"Write-Output ('Adapter: ' + $adapter.Description); " +
"Write-Output (' IP Address: ' + ($adapter.IPAddress[0])); " +
"Write-Output (' MAC Address: ' + $adapter.MACAddress); " +
"Write-Output (' Gateway: ' + ($adapter.DefaultIPGateway -join ', ')); " +
"}";
}
cmd += "\"";
} else {
// Fallback for Unix systems
if (detail === "basic") {
cmd = "uname -a && lscpu | grep 'Model name' && free -h | head -n 2";
} else {
cmd = "uname -a && lscpu && free -h && df -h && ip addr";
}
}
const stdout = executeCommand(cmd);
return {
content: [
{
type: "text",
text: stdout.toString(),
},
],
};
} catch (error) {
return {
isError: true,
content: [
{
type: "text",
text: `Error retrieving system info: ${error}`,
},
],
};
}
}
);
// Register the get_network_info tool
server.tool(
"get_network_info",
"Retrieve network configuration information including IP addresses, adapters, and DNS settings. Can be filtered to a specific interface.",
{
networkInterface: z.string().optional().describe("Optional interface name to filter results"),
},
async ({ networkInterface }) => {
try {
let cmd;
if (isWindows) {
cmd = "powershell.exe -Command \"";
if (networkInterface) {
cmd += "$adapters = Get-NetAdapter | Where-Object { $_.Name -like '*" + networkInterface + "*' }; ";
} else {
cmd += "$adapters = Get-NetAdapter; ";
}
cmd += "foreach($adapter in $adapters) { " +
"Write-Output ('======== ' + $adapter.Name + ' (' + $adapter.Status + ') ========'); " +
"Write-Output ('Interface Description: ' + $adapter.InterfaceDescription); " +
"Write-Output ('MAC Address: ' + $adapter.MacAddress); " +
"Write-Output ('Link Speed: ' + $adapter.LinkSpeed); " +
"$ipconfig = Get-NetIPConfiguration -InterfaceIndex $adapter.ifIndex; " +
"Write-Output ('IP Address: ' + ($ipconfig.IPv4Address.IPAddress -join ', ')); " +
"Write-Output ('Subnet: ' + ($ipconfig.IPv4Address.PrefixLength -join ', ')); " +
"Write-Output ('Gateway: ' + ($ipconfig.IPv4DefaultGateway.NextHop -join ', ')); " +
"Write-Output ('DNS Servers: ' + ($ipconfig.DNSServer.ServerAddresses -join ', ')); " +
"Write-Output ''; " +
"}\"";
} else {
// Fallback for Unix systems
if (networkInterface) {
cmd = `ip addr show ${networkInterface}`;
} else {
cmd = "ip addr";
}
}
const stdout = executeCommand(cmd);
return {
content: [
{
type: "text",
text: stdout.toString(),
},
],
};
} catch (error) {
return {
isError: true,
content: [
{
type: "text",
text: `Error retrieving network info: ${error}`,
},
],
};
}
}
);
// Register the get_scheduled_tasks tool
server.tool(
"get_scheduled_tasks",
"Retrieve information about scheduled tasks on the system. Can query all tasks or get detailed status of a specific task.",
{
action: z.enum(["query", "status"]).default("query").describe("Action to perform"),
taskName: z.string().optional().describe("Name of the specific task (optional)"),
},
async ({ action, taskName }) => {
if (!isWindows) {
return {
content: [
{
type: "text",
text: "The scheduled tasks tool is only available on Windows. Current platform: " + platform(),
},
],
};
}
try {
let cmd = "powershell.exe -Command \"";
if (action === "query") {
if (taskName) {
cmd += "Get-ScheduledTask -TaskName '" + taskName + "' | Format-List TaskName, State, Description, Author, LastRunTime, NextRunTime, LastTaskResult";
} else {
cmd += "Get-ScheduledTask | Select-Object TaskName, State, Description | Format-Table -AutoSize | Out-String";
}
} else if (action === "status" && taskName) {
cmd += "Get-ScheduledTask -TaskName '" + taskName + "' | Format-List *; " +
"Get-ScheduledTaskInfo -TaskName '" + taskName + "' | Format-List *";
} else {
return {
isError: true,
content: [
{
type: "text",
text: "For 'status' action, taskName parameter is required",
},
],
};
}
cmd += "\"";
const stdout = executeCommand(cmd);
return {
content: [
{
type: "text",
text: stdout.toString(),
},
],
};
} catch (error) {
return {
isError: true,
content: [
{
type: "text",
text: `Error retrieving scheduled tasks: ${error}`,
},
],
};
}
}
);
// Register the get_service_info tool
server.tool(
"get_service_info",
"Retrieve information about Windows services. Can query all services or get detailed status of a specific service.",
{
action: z.enum(["query", "status"]).default("query").describe("Action to perform"),
serviceName: z.string().optional().describe("Service name to get info about (optional)"),
},
async ({ action, serviceName }) => {
if (!isWindows) {
return {
content: [
{
type: "text",
text: "The service info tool is only available on Windows. Current platform: " + platform(),
},
],
};
}
try {
let cmd = "powershell.exe -Command \"";
if (action === "query") {
if (serviceName) {
cmd += "Get-Service -Name '" + serviceName + "' | Format-List Name, DisplayName, Status, StartType, Description";
} else {
cmd += "Get-Service | Select-Object Name, DisplayName, Status, StartType | Format-Table -AutoSize | Out-String";
}
} else if (action === "status" && serviceName) {
cmd += "Get-Service -Name '" + serviceName + "' | Format-List *; " +
"Get-CimInstance -ClassName Win32_Service -Filter \"Name='" + serviceName + "'\" | Format-List *";
} else {
return {
isError: true,
content: [
{
type: "text",
text: "For 'status' action, serviceName parameter is required",
},
],
};
}
cmd += "\"";
const stdout = executeCommand(cmd);
return {
content: [
{
type: "text",
text: stdout.toString(),
},
],
};
} catch (error) {
return {
isError: true,
content: [
{
type: "text",
text: `Error retrieving service info: ${error}`,
},
],
};
}
}
);
// Register the list_allowed_commands tool
server.tool(
"list_allowed_commands",
"List all commands that are allowed to be executed by this server. This helps understand what operations are permitted.",
{},
async () => {
try {
if (isWindows) {
return {
content: [
{
type: "text",
text: "The following commands are allowed to be executed by this server:\n\n" +
"- powershell.exe: Used for most system operations\n" +
"- cmd.exe: Used for simple command execution\n\n" +
"Note: All commands are executed with the same privileges as the user running this server."
},
],
};
} else {
return {
content: [
{
type: "text",
text: "Running on non-Windows platform: " + platform() + "\n\n" +
"Standard Unix/Linux commands are available, but Windows-specific commands like powershell.exe and cmd.exe are not available in this environment.\n\n" +
"The following commands should work:\n" +
"- ls: List directory contents\n" +
"- ps: List processes\n" +
"- uname: Print system information\n" +
"- ip: Show network information\n\n" +
"Note: All commands are executed with the same privileges as the user running this server."
},
],
};
}
} catch (error) {
return {
isError: true,
content: [
{
type: "text",
text: `Error listing allowed commands: ${error}`,
},
],
};
}
}
);
// Register the execute_command tool
server.tool(
"execute_command",
"Execute a Windows command and return its output. Only commands in the allowed list can be executed. This tool should be used for running simple commands like 'dir', 'echo', etc.",
{
command: z.string().describe("The command to execute"),
workingDir: z.string().optional().describe("Working directory for the command"),
timeout: z.number().default(30000).describe("Timeout in milliseconds"),
},
async ({ command, workingDir, timeout }) => {
try {
// Security check: Ensure only allowed commands are executed
const commandLower = command.toLowerCase();
// Block potentially dangerous commands
const dangerousPatterns = [
'net user', 'net localgroup', 'netsh', 'format', 'rd /s', 'rmdir /s',
'del /f', 'reg delete', 'shutdown', 'taskkill', 'sc delete', 'bcdedit',
'cacls', 'icacls', 'takeown', 'diskpart', 'cipher /w', 'schtasks /create',
'rm -rf', 'sudo', 'chmod', 'chown', 'passwd', 'mkfs', 'dd'
];
// Check for dangerous patterns
if (dangerousPatterns.some(pattern => commandLower.includes(pattern.toLowerCase()))) {
return {
isError: true,
content: [
{
type: "text",
text: "Command contains potentially dangerous operations and cannot be executed.",
},
],
};
}
const options: any = { timeout };
if (workingDir) {
options.cwd = workingDir;
}
let cmdToExecute;
if (isWindows) {
cmdToExecute = `cmd.exe /c ${command}`;
} else {
// For non-Windows, try to execute the command directly
cmdToExecute = command;
}
const stdout = executeCommand(cmdToExecute, options);
return {
content: [
{
type: "text",
text: stdout.toString() || 'Command executed successfully (no output)',
},
],
};
} catch (error) {
return {
isError: true,
content: [
{
type: "text",
text: `Error executing command: ${error}`,
},
],
};
}
}
);
// Register the execute_powershell tool
server.tool(
"execute_powershell",
"Execute a PowerShell script and return its output. This allows for more complex operations and script execution. PowerShell must be in the allowed commands list.",
{
script: z.string().describe("PowerShell script to execute"),
workingDir: z.string().optional().describe("Working directory for the script"),
timeout: z.number().default(30000).describe("Timeout in milliseconds"),
},
async ({ script, workingDir, timeout }) => {
if (!isWindows) {
return {
content: [
{
type: "text",
text: "The PowerShell execution tool is only available on Windows. Current platform: " + platform(),
},
],
};
}
try {
// Security check: Ensure no dangerous operations
const scriptLower = script.toLowerCase();
// Block potentially dangerous commands
const dangerousPatterns = [
'new-user', 'add-user', 'remove-item -recurse -force', 'format-volume',
'reset-computer', 'stop-computer', 'restart-computer', 'stop-process -force',
'remove-item -force', 'set-executionpolicy', 'invoke-webrequest',
'start-bitstransfer', 'set-location', 'invoke-expression', 'iex', '& {',
'invoke-command', 'new-psdrive', 'remove-psdrive', 'enable-psremoting',
'new-service', 'remove-service', 'set-service'
];
// Check for dangerous patterns
if (dangerousPatterns.some(pattern => scriptLower.includes(pattern.toLowerCase()))) {
return {
isError: true,
content: [
{
type: "text",
text: "Script contains potentially dangerous operations and cannot be executed.",
},
],
};
}
const options: any = { timeout };
if (workingDir) {
options.cwd = workingDir;
}
const stdout = executeCommand(`powershell.exe -Command "${script}"`, options);
return {
content: [
{
type: "text",
text: stdout.toString() || 'PowerShell script executed successfully (no output)',
},
],
};
} catch (error) {
return {
isError: true,
content: [
{
type: "text",
text: `Error executing PowerShell script: ${error}`,
},
],
};
}
}
);
// Start the server
async function main() {
// Log platform information on startup
console.error(`Starting Windows Command Line MCP Server on platform: ${platform()}`);
if (!isWindows) {
console.error("Warning: This server is designed for Windows environments. Some features may not work on " + platform());
}
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Windows Command Line MCP Server running on stdio");
}
main().catch((error) => {
console.error("Fatal error in main():", error);
process.exit(1);
});