├── .gitignore
├── .gitattributes
├── .prettierrc
├── tsconfig.json
├── package.json
├── LICENSE.md
├── src
├── config.ts
└── index.ts
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | build/
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | package-lock.json binary
2 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "semi": true,
3 | "singleQuote": true,
4 | "tabWidth": 2,
5 | "printWidth": 100
6 | }
7 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2022",
4 | "module": "Node16",
5 | "moduleResolution": "Node16",
6 | "outDir": "./build",
7 | "rootDir": "./src",
8 | "strict": true,
9 | "esModuleInterop": true,
10 | "skipLibCheck": true,
11 | "forceConsistentCasingInFileNames": true
12 | },
13 | "include": ["src/**/*"],
14 | "exclude": ["node_modules"]
15 | }
16 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "mcp-shell",
3 | "version": "0.1.3",
4 | "description": "Secure shell server for the Model Context Protocol. Integrates with Claude Desktop.",
5 | "type": "module",
6 | "bin": {
7 | "mcp-shell": "build/index.js"
8 | },
9 | "files": [
10 | "build/**/*"
11 | ],
12 | "scripts": {
13 | "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"",
14 | "prepare": "npm run build",
15 | "watch": "tsc --watch",
16 | "inspector": "npx @modelcontextprotocol/inspector build/index.js"
17 | },
18 | "author": "High Dimensional Research",
19 | "license": "MIT",
20 | "dependencies": {
21 | "@modelcontextprotocol/sdk": "^0.6.0",
22 | "@types/command-exists": "^1.2.3",
23 | "command-exists": "^1.2.9",
24 | "execa": "^9.5.1"
25 | },
26 | "devDependencies": {
27 | "@types/node": "^20.11.24",
28 | "husky": "^9.1.7",
29 | "lint-staged": "^15.2.10",
30 | "typescript": "^5.3.3"
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | Copyright 2024 Ishmail Inc. dba High Dimensional Research
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4 |
5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6 |
7 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8 |
9 |
--------------------------------------------------------------------------------
/src/config.ts:
--------------------------------------------------------------------------------
1 | import fs from 'fs';
2 | import path from 'path';
3 | import os from 'os';
4 |
5 | function getConfigPath() {
6 | switch (process.platform) {
7 | case 'darwin':
8 | return path.join(
9 | os.homedir(),
10 | 'Library',
11 | 'Application Support',
12 | 'Claude',
13 | 'claude_desktop_config.json',
14 | );
15 | case 'win32':
16 | return path.join(process.env.APPDATA || '', 'Claude', 'claude_desktop_config.json');
17 | default:
18 | throw new Error('Unsupported platform');
19 | }
20 | }
21 |
22 | export function updateConfig(debug = false) {
23 | const isNpx = Boolean(
24 | process.argv[1].includes('/_npx/') ||
25 | process.env.npm_command === 'exec' ||
26 | process.env._?.includes('/_npx/'),
27 | );
28 | if (!isNpx && !debug) {
29 | console.error({"error": 'Not running via npx'});
30 | return;
31 | }
32 |
33 | const scriptPath = process.argv[1];
34 | const configPath = getConfigPath();
35 |
36 | try {
37 | let config: { mcpServers?: { 'shell-server'?: { command: string, args?: string[] } } } = {};
38 | try {
39 | config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
40 | } catch (err) {
41 | console.log('Creating new config file');
42 | }
43 |
44 | config.mcpServers = config.mcpServers || {};
45 |
46 | if (process.platform === 'win32') {
47 | config.mcpServers['shell-server'] = {
48 | command: "C:\\Program Files\\nodejs\\node.exe",
49 | args: [scriptPath]
50 | }
51 | } else {
52 | config.mcpServers['shell-server'] = {
53 | command: `${debug ? 'node' : 'npx'}`,
54 | args: debug ? [scriptPath] : ['mcp-shell']
55 | };
56 | }
57 |
58 | const configDir = path.dirname(configPath);
59 | if (!fs.existsSync(configDir)) {
60 | fs.mkdirSync(configDir, { recursive: true });
61 | }
62 |
63 | fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
64 | console.log('Updated config at:', configPath);
65 | console.log('Added server with command:', scriptPath);
66 | } catch (err) {
67 | console.error('Error updating config:', err);
68 | process.exit(1);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Shell MCP Server
2 |
3 | A Node.js implementation of the Model Context Protocol (MCP) that provides secure shell command execution capabilities. This server allows AI models to execute shell commands in a controlled environment with built-in security measures. Easily integrates with [Claude Desktop](https://claude.ai/download) for connecting Claude with your shell.
4 |
5 |
6 |
7 |
8 |
9 | ## Features
10 |
11 | - MCP-compliant server implementation
12 | - Secure command execution with blacklist protection
13 | - Command existence validation
14 | - Standard I/O based transport
15 | - Error handling and graceful shutdown
16 |
17 | ## Installation
18 |
19 | Run `npx mcp-shell`.
20 |
21 | To add it to Claude Desktop, run `npx mcp-shell config`. Or add `npx -y mcp-shell` to your config manually.
22 |
23 | Start (or restart) [Claude Desktop](https://claude.ai/download) and you should see the MCP tool listed on the landing page.
24 |
25 | ## Security Features
26 |
27 | The server implements several security measures:
28 |
29 | 1. Command Blacklisting
30 |
31 | - Prevents execution of dangerous system commands
32 | - Blocks access to critical system modifications
33 | - Protects against file system destruction
34 | - Prevents privilege escalation
35 |
36 | 2. Command Validation
37 | - Verifies command existence before execution
38 | - Validates against the blacklist
39 | - Returns clear error messages for invalid commands
40 |
41 | ## Available Tools
42 |
43 | The server provides one tool:
44 |
45 | ### run_command
46 |
47 | Executes a shell command and returns its output.
48 |
49 | **Input Schema:**
50 |
51 | ```json
52 | {
53 | "type": "object",
54 | "properties": {
55 | "command": { "type": "string" }
56 | }
57 | }
58 | ```
59 |
60 | **Response:**
61 |
62 | - Success: Command output as plain text
63 | - Error: Error message as plain text
64 |
65 | ## Blacklisted Commands
66 |
67 | The following command categories are blocked for security:
68 |
69 | - File System Destruction Commands (rm, rmdir, del)
70 | - Disk/Filesystem Commands (format, mkfs, dd)
71 | - Permission/Ownership Commands (chmod, chown)
72 | - Privilege Escalation Commands (sudo, su)
73 | - Code Execution Commands (exec, eval)
74 | - System Communication Commands (write, wall)
75 | - System Control Commands (shutdown, reboot, init)
76 |
77 | ## Error Handling
78 |
79 | The server includes comprehensive error handling:
80 |
81 | - Command not found errors
82 | - Blacklisted command errors
83 | - Execution errors
84 | - MCP protocol errors
85 | - Graceful shutdown on SIGINT
86 |
87 | ## Implementation Details
88 |
89 | The server is built using:
90 |
91 | - Model Context Protocol SDK
92 | - StdioServerTransport for communication
93 | - execa for command execution
94 | - command-exists for command validation
95 |
96 | ## Development
97 |
98 | To modify the security settings, you can:
99 |
100 | 1. Edit the `BLACKLISTED_COMMANDS` set to adjust blocked commands
101 | 2. Modify the `validateCommand` function to add additional validation rules
102 | 3. Enhance the command parsing logic in the `CallToolRequestSchema` handler
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | import { Server } from '@modelcontextprotocol/sdk/server/index.js';
4 | import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5 | import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
6 | import { execa } from 'execa';
7 | import commandExists from 'command-exists';
8 | import { updateConfig } from './config.js';
9 |
10 | interface CommandResult {
11 | stdout: string;
12 | stderr: string;
13 | }
14 |
15 | // Dangerous commands that should never be allowed
16 | const BLACKLISTED_COMMANDS = new Set([
17 | // File System Destruction Commands
18 | 'rm', // Remove files/directories - Could delete critical system or user files
19 | 'rmdir', // Remove directories - Could delete important directories
20 | 'del', // Windows delete command - Same risks as rm
21 |
22 | // Disk/Filesystem Commands
23 | 'format', // Formats entire disks/partitions - Could destroy all data on drives
24 | 'mkfs', // Make filesystem - Could reformat drives and destroy data
25 | 'dd', // Direct disk access - Can overwrite raw disks, often called "disk destroyer"
26 |
27 | // Permission/Ownership Commands
28 | 'chmod', // Change file permissions - Could make critical files accessible or inaccessible
29 | 'chown', // Change file ownership - Could transfer ownership of sensitive files
30 |
31 | // Privilege Escalation Commands
32 | 'sudo', // Superuser do - Allows running commands with elevated privileges
33 | 'su', // Switch user - Could be used to gain unauthorized user access
34 |
35 | // Code Execution Commands
36 | 'exec', // Execute commands - Could run arbitrary commands with shell's privileges
37 | 'eval', // Evaluate strings as code - Could execute malicious code injection
38 |
39 | // System Communication Commands
40 | 'write', // Write to other users' terminals - Could be used for harassment/phishing
41 | 'wall', // Write to all users - Could be used for system-wide harassment
42 |
43 | // System Control Commands
44 | 'shutdown', // Shut down the system - Denial of service
45 | 'reboot', // Restart the system - Denial of service
46 | 'init', // System initialization control - Could disrupt system state
47 |
48 | // Additional High-Risk Commands
49 | 'mkfs', // Duplicate of above, filesystem creation - Data destruction risk
50 | ]);
51 |
52 | // Example validation function
53 | function validateCommand(baseCommand: string): boolean {
54 | return !BLACKLISTED_COMMANDS.has(baseCommand);
55 | }
56 |
57 | class ShellServer {
58 | private server: Server;
59 |
60 | constructor() {
61 | this.server = new Server(
62 | {
63 | name: 'shell-server',
64 | version: '0.1.0',
65 | },
66 | { capabilities: { resources: {}, tools: {} } },
67 | );
68 |
69 | this.setupErrorHandling();
70 | this.setupHandlers();
71 | }
72 |
73 | private setupErrorHandling(): void {
74 | this.server.onerror = (error) => {
75 | console.error('[MCP Error]', error);
76 | };
77 |
78 | process.on('SIGINT', async () => {
79 | await this.server.close();
80 | process.exit(0);
81 | });
82 | }
83 |
84 | private setupHandlers(): void {
85 | this.setupToolHandlers();
86 | }
87 |
88 | private setupToolHandlers(): void {
89 | this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
90 | tools: [
91 | {
92 | name: 'run_command',
93 | description: 'Run a shell command',
94 | inputSchema: {
95 | type: 'object',
96 | properties: {
97 | command: { type: 'string' },
98 | },
99 | },
100 | },
101 | ],
102 | }));
103 |
104 | this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
105 | if (request.params.name !== 'run_command') {
106 | throw new Error(`Unknown tool: ${request.params.name}`);
107 | }
108 |
109 | const command = request.params.arguments?.command as string;
110 | try {
111 | const baseCommand = command.trim().split(/\s+/)[0];
112 | if (!(await commandExists(baseCommand))) {
113 | throw new Error(`Command not found: ${baseCommand}`);
114 | }
115 |
116 | if (!validateCommand(baseCommand)) {
117 | throw new Error(`Command not allowed: ${baseCommand}`);
118 | }
119 |
120 | const { stdout, stderr } = await execa(command, [], {
121 | shell: true,
122 | env: process.env,
123 | });
124 |
125 | return {
126 | content: [{ type: 'text', text: stdout || stderr, mimeType: 'text/plain' }],
127 | };
128 | } catch (error) {
129 | return {
130 | content: [
131 | {
132 | type: 'text',
133 | text: String(error),
134 | mimeType: 'text/plain',
135 | },
136 | ],
137 | };
138 | }
139 | });
140 | }
141 |
142 | async run(): Promise {
143 | const transport = new StdioServerTransport();
144 | await this.server.connect(transport);
145 |
146 | // Although this is just an informative message, we must log to stderr,
147 | // to avoid interfering with MCP communication that happens on stdout
148 | console.error('MCP server running on stdio');
149 | }
150 | }
151 |
152 | async function main() {
153 | // Get command line arguments
154 | const args = process.argv.slice(2);
155 |
156 | // setup in claude desktop
157 | if (args.includes('config')) {
158 | const debug = args.includes('--debug');
159 | updateConfig(debug);
160 | }
161 |
162 | // start server
163 | const server = new ShellServer();
164 | await server.run();
165 | }
166 |
167 | main().catch((error) => {
168 | console.error('Server error:', error);
169 | process.exit(1);
170 | });
171 |
--------------------------------------------------------------------------------