# Directory Structure ``` ├── .python-version ├── pyproject.toml ├── README.md ├── src │ └── mcp_server_shell │ ├── __init__.py │ ├── __main__.py │ ├── __pycache__ │ │ ├── __init__.cpython-312.pyc │ │ ├── __main__.cpython-312.pyc │ │ └── server.cpython-312.pyc │ └── server.py └── uv.lock ``` # Files -------------------------------------------------------------------------------- /.python-version: -------------------------------------------------------------------------------- ``` 1 | 3.12 2 | ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- ```markdown 1 | # Shell MCP Server 2 | 3 | A Model Context Protocol server that provides shell command execution capabilities. This server enables LLMs to execute shell commands and receive their output in a controlled manner. 4 | 5 | ## Available Tools 6 | 7 | - `execute_command` - Execute a shell command and return its output 8 | - Required arguments: 9 | - `command` (string): Shell command to execute 10 | - Returns: 11 | - Command result containing: 12 | - `command`: The executed command 13 | - `output`: Combined stdout and stderr output 14 | - `return_code`: Command execution return code 15 | 16 | ## Installation 17 | 18 | ### Using uv (recommended) 19 | 20 | When using [`uv`](https://docs.astral.sh/uv/) no specific installation is needed. We will 21 | use [`uvx`](https://docs.astral.sh/uv/guides/tools/) to directly run *mcp-server-shell*. 22 | 23 | ### Using PIP 24 | 25 | Alternatively you can install `mcp-server-shell` via pip: 26 | 27 | ```bash 28 | pip install mcp-server-shell 29 | ``` 30 | 31 | After installation, you can run it as a script using: 32 | 33 | ```bash 34 | python -m mcp_server_shell 35 | ``` 36 | 37 | ## Configuration 38 | 39 | ### Configure for Claude.app 40 | 41 | Add to your Claude settings: 42 | 43 | <details> 44 | <summary>Using uvx</summary> 45 | 46 | ```json 47 | "mcpServers": { 48 | "shell": { 49 | "command": "uvx", 50 | "args": ["mcp-server-shell"] 51 | } 52 | } 53 | ``` 54 | </details> 55 | 56 | <details> 57 | <summary>Using pip installation</summary> 58 | 59 | ```json 60 | "mcpServers": { 61 | "shell": { 62 | "command": "python", 63 | "args": ["-m", "mcp_server_shell"] 64 | } 65 | } 66 | ``` 67 | </details> 68 | 69 | ### Configure for Zed 70 | 71 | Add to your Zed settings.json: 72 | 73 | <details> 74 | <summary>Using uvx</summary> 75 | 76 | ```json 77 | "context_servers": { 78 | "mcp-server-shell": { 79 | "command": "uvx", 80 | "args": ["mcp-server-shell"] 81 | } 82 | }, 83 | ``` 84 | </details> 85 | 86 | <details> 87 | <summary>Using pip installation</summary> 88 | 89 | ```json 90 | "context_servers": { 91 | "mcp-server-shell": { 92 | "command": "python", 93 | "args": ["-m", "mcp_server_shell"] 94 | } 95 | }, 96 | ``` 97 | </details> 98 | 99 | ## Example Interactions 100 | 101 | Execute a shell command: 102 | ```json 103 | { 104 | "name": "execute_command", 105 | "arguments": { 106 | "command": "ls -la" 107 | } 108 | } 109 | ``` 110 | Response: 111 | ```json 112 | { 113 | "command": "ls -la", 114 | "output": "total 24\ndrwxr-xr-x 5 user group 160 Jan 1 12:00 .\ndrwxr-xr-x 3 user group 96 Jan 1 12:00 ..", 115 | "return_code": 0 116 | } 117 | ``` 118 | 119 | ## Debugging 120 | 121 | You can use the MCP inspector to debug the server. For uvx installations: 122 | 123 | ```bash 124 | npx @modelcontextprotocol/inspector uvx mcp-server-shell 125 | ``` 126 | 127 | Or if you've installed the package in a specific directory or are developing on it: 128 | 129 | ```bash 130 | cd path/to/servers/src/shell 131 | npx @modelcontextprotocol/inspector uv run mcp-server-shell 132 | ``` 133 | 134 | ## Examples of Questions for Claude 135 | 136 | 1. "What files are in the current directory?" 137 | 2. "Show me the contents of the README.md file" 138 | 3. "What's the current system date?" 139 | 4. "Check if Python is installed and show its version" 140 | 141 | ## Security Considerations 142 | 143 | ⚠️ **Warning**: This server executes shell commands directly on your system. Use with caution and implement appropriate security measures to prevent unauthorized or dangerous command execution. 144 | 145 | ## Contributing 146 | 147 | We encourage contributions to help expand and improve mcp-server-shell. Whether you want to add new features, enhance security, or improve documentation, your input is valuable. 148 | 149 | For examples of other MCP servers and implementation patterns, see: 150 | https://github.com/modelcontextprotocol/servers 151 | 152 | Pull requests are welcome! Feel free to contribute new ideas, bug fixes, or enhancements to make mcp-server-shell even more powerful and useful. 153 | 154 | ## License 155 | 156 | mcp-server-shell is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository. ``` -------------------------------------------------------------------------------- /src/mcp_server_shell/__main__.py: -------------------------------------------------------------------------------- ```python 1 | import asyncio 2 | from .server import serve 3 | 4 | def main(): 5 | asyncio.run(serve()) 6 | 7 | if __name__ == "__main__": 8 | main() ``` -------------------------------------------------------------------------------- /src/mcp_server_shell/__init__.py: -------------------------------------------------------------------------------- ```python 1 | from .server import serve 2 | 3 | 4 | def main(): 5 | """MCP Shell Server - Execute shell commands through MCP""" 6 | import argparse 7 | import asyncio 8 | 9 | parser = argparse.ArgumentParser( 10 | description="give a model the ability to execute shell commands" 11 | ) 12 | 13 | args = parser.parse_args() 14 | asyncio.run(serve()) 15 | 16 | 17 | if __name__ == "__main__": 18 | main() ``` -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- ```toml 1 | [project] 2 | name = "mcp-server-shell" 3 | version = "0.1.0" 4 | description = "A Model Context Protocol server providing shell command execution capabilities for LLMs" 5 | readme = "README.md" 6 | requires-python = ">=3.10" 7 | keywords = ["shell", "command", "mcp", "llm"] 8 | license = { text = "MIT" } 9 | classifiers = [ 10 | "Development Status :: 4 - Beta", 11 | "Intended Audience :: Developers", 12 | "License :: OSI Approved :: MIT License", 13 | "Programming Language :: Python :: 3", 14 | "Programming Language :: Python :: 3.10", 15 | ] 16 | dependencies = [ 17 | "mcp>=1.0.0", 18 | "pydantic>=2.0.0", 19 | ] 20 | 21 | [project.scripts] 22 | mcp-server-shell = "mcp_server_shell.server:serve" 23 | 24 | [build-system] 25 | requires = ["hatchling"] 26 | build-backend = "hatchling.build" 27 | 28 | [tool.uv] 29 | dev-dependencies = [ 30 | "pyright>=1.1.389", 31 | "pytest>=8.3.3", 32 | "ruff>=0.8.1", 33 | ] 34 | ``` -------------------------------------------------------------------------------- /src/mcp_server_shell/server.py: -------------------------------------------------------------------------------- ```python 1 | from enum import Enum 2 | import json 3 | from typing import Sequence 4 | import subprocess 5 | from mcp.server import Server 6 | from mcp.server.stdio import stdio_server 7 | from mcp.types import Tool, TextContent, ImageContent, EmbeddedResource 8 | from mcp.shared.exceptions import McpError 9 | from pydantic import BaseModel 10 | import logging 11 | 12 | logging.basicConfig( 13 | level=logging.INFO, 14 | format='%(asctime)s - %(levelname)s - %(message)s' 15 | ) 16 | logger = logging.getLogger(__name__) 17 | 18 | class ShellTools(str, Enum): 19 | EXECUTE_COMMAND = "execute_command" 20 | 21 | class CommandResult(BaseModel): 22 | command: str 23 | output: str 24 | return_code: int 25 | 26 | class ShellServer: 27 | def execute_command(self, command: str) -> CommandResult: 28 | """Execute a shell command and return the result""" 29 | logger.info(f"Executing command: {command}") 30 | try: 31 | result = subprocess.run( 32 | command, 33 | shell=True, 34 | capture_output=True, 35 | text=True 36 | ) 37 | logger.debug(f"Command output: {result.stdout + result.stderr}") 38 | return CommandResult( 39 | command=command, 40 | output=result.stdout + result.stderr, 41 | return_code=result.returncode 42 | ) 43 | except Exception as e: 44 | logger.error(f"Command execution failed: {str(e)}") 45 | raise McpError(f"Command execution failed: {str(e)}") 46 | 47 | async def serve() -> None: 48 | logger.info("Starting MCP shell server...") 49 | server = Server("mcp-shell") 50 | shell_server = ShellServer() 51 | 52 | @server.list_tools() 53 | async def list_tools() -> list[Tool]: 54 | """List available shell tools.""" 55 | logger.debug("Listing available tools") 56 | return [ 57 | Tool( 58 | name=ShellTools.EXECUTE_COMMAND.value, 59 | display_name="Execute Shell Command", 60 | description="Execute a shell command and return its output", 61 | inputSchema={ 62 | "type": "object", 63 | "properties": { 64 | "command": { 65 | "type": "string", 66 | "description": "Shell command to execute", 67 | } 68 | }, 69 | "required": ["command"], 70 | }, 71 | ), 72 | ] 73 | 74 | @server.call_tool() 75 | async def call_tool( 76 | name: str, arguments: dict 77 | ) -> Sequence[TextContent | ImageContent | EmbeddedResource]: 78 | """Handle tool calls for shell command execution.""" 79 | logger.info(f"Tool call received: {name} with arguments: {arguments}") 80 | try: 81 | if name == ShellTools.EXECUTE_COMMAND.value: 82 | command = arguments.get("command") 83 | if not command: 84 | raise ValueError("Missing required argument: command") 85 | 86 | result = shell_server.execute_command(command) 87 | return [ 88 | TextContent(type="text", text=json.dumps(result.model_dump(), indent=2)) 89 | ] 90 | else: 91 | raise ValueError(f"Unknown tool: {name}") 92 | 93 | except Exception as e: 94 | raise ValueError(f"Error executing shell command: {str(e)}") 95 | 96 | logger.info("Initializing server...") 97 | options = server.create_initialization_options() 98 | async with stdio_server() as (read_stream, write_stream): 99 | logger.info("Server started and ready to handle requests") 100 | await server.run(read_stream, write_stream, options) ```