# 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: -------------------------------------------------------------------------------- ``` 3.12 ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- ```markdown # Shell MCP Server 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. ## Available Tools - `execute_command` - Execute a shell command and return its output - Required arguments: - `command` (string): Shell command to execute - Returns: - Command result containing: - `command`: The executed command - `output`: Combined stdout and stderr output - `return_code`: Command execution return code ## Installation ### Using uv (recommended) When using [`uv`](https://docs.astral.sh/uv/) no specific installation is needed. We will use [`uvx`](https://docs.astral.sh/uv/guides/tools/) to directly run *mcp-server-shell*. ### Using PIP Alternatively you can install `mcp-server-shell` via pip: ```bash pip install mcp-server-shell ``` After installation, you can run it as a script using: ```bash python -m mcp_server_shell ``` ## Configuration ### Configure for Claude.app Add to your Claude settings: <details> <summary>Using uvx</summary> ```json "mcpServers": { "shell": { "command": "uvx", "args": ["mcp-server-shell"] } } ``` </details> <details> <summary>Using pip installation</summary> ```json "mcpServers": { "shell": { "command": "python", "args": ["-m", "mcp_server_shell"] } } ``` </details> ### Configure for Zed Add to your Zed settings.json: <details> <summary>Using uvx</summary> ```json "context_servers": { "mcp-server-shell": { "command": "uvx", "args": ["mcp-server-shell"] } }, ``` </details> <details> <summary>Using pip installation</summary> ```json "context_servers": { "mcp-server-shell": { "command": "python", "args": ["-m", "mcp_server_shell"] } }, ``` </details> ## Example Interactions Execute a shell command: ```json { "name": "execute_command", "arguments": { "command": "ls -la" } } ``` Response: ```json { "command": "ls -la", "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 ..", "return_code": 0 } ``` ## Debugging You can use the MCP inspector to debug the server. For uvx installations: ```bash npx @modelcontextprotocol/inspector uvx mcp-server-shell ``` Or if you've installed the package in a specific directory or are developing on it: ```bash cd path/to/servers/src/shell npx @modelcontextprotocol/inspector uv run mcp-server-shell ``` ## Examples of Questions for Claude 1. "What files are in the current directory?" 2. "Show me the contents of the README.md file" 3. "What's the current system date?" 4. "Check if Python is installed and show its version" ## Security Considerations ⚠️ **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. ## Contributing 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. For examples of other MCP servers and implementation patterns, see: https://github.com/modelcontextprotocol/servers Pull requests are welcome! Feel free to contribute new ideas, bug fixes, or enhancements to make mcp-server-shell even more powerful and useful. ## License 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 import asyncio from .server import serve def main(): asyncio.run(serve()) if __name__ == "__main__": main() ``` -------------------------------------------------------------------------------- /src/mcp_server_shell/__init__.py: -------------------------------------------------------------------------------- ```python from .server import serve def main(): """MCP Shell Server - Execute shell commands through MCP""" import argparse import asyncio parser = argparse.ArgumentParser( description="give a model the ability to execute shell commands" ) args = parser.parse_args() asyncio.run(serve()) if __name__ == "__main__": main() ``` -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- ```toml [project] name = "mcp-server-shell" version = "0.1.0" description = "A Model Context Protocol server providing shell command execution capabilities for LLMs" readme = "README.md" requires-python = ">=3.10" keywords = ["shell", "command", "mcp", "llm"] license = { text = "MIT" } classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", ] dependencies = [ "mcp>=1.0.0", "pydantic>=2.0.0", ] [project.scripts] mcp-server-shell = "mcp_server_shell.server:serve" [build-system] requires = ["hatchling"] build-backend = "hatchling.build" [tool.uv] dev-dependencies = [ "pyright>=1.1.389", "pytest>=8.3.3", "ruff>=0.8.1", ] ``` -------------------------------------------------------------------------------- /src/mcp_server_shell/server.py: -------------------------------------------------------------------------------- ```python from enum import Enum import json from typing import Sequence import subprocess from mcp.server import Server from mcp.server.stdio import stdio_server from mcp.types import Tool, TextContent, ImageContent, EmbeddedResource from mcp.shared.exceptions import McpError from pydantic import BaseModel import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) class ShellTools(str, Enum): EXECUTE_COMMAND = "execute_command" class CommandResult(BaseModel): command: str output: str return_code: int class ShellServer: def execute_command(self, command: str) -> CommandResult: """Execute a shell command and return the result""" logger.info(f"Executing command: {command}") try: result = subprocess.run( command, shell=True, capture_output=True, text=True ) logger.debug(f"Command output: {result.stdout + result.stderr}") return CommandResult( command=command, output=result.stdout + result.stderr, return_code=result.returncode ) except Exception as e: logger.error(f"Command execution failed: {str(e)}") raise McpError(f"Command execution failed: {str(e)}") async def serve() -> None: logger.info("Starting MCP shell server...") server = Server("mcp-shell") shell_server = ShellServer() @server.list_tools() async def list_tools() -> list[Tool]: """List available shell tools.""" logger.debug("Listing available tools") return [ Tool( name=ShellTools.EXECUTE_COMMAND.value, display_name="Execute Shell Command", description="Execute a shell command and return its output", inputSchema={ "type": "object", "properties": { "command": { "type": "string", "description": "Shell command to execute", } }, "required": ["command"], }, ), ] @server.call_tool() async def call_tool( name: str, arguments: dict ) -> Sequence[TextContent | ImageContent | EmbeddedResource]: """Handle tool calls for shell command execution.""" logger.info(f"Tool call received: {name} with arguments: {arguments}") try: if name == ShellTools.EXECUTE_COMMAND.value: command = arguments.get("command") if not command: raise ValueError("Missing required argument: command") result = shell_server.execute_command(command) return [ TextContent(type="text", text=json.dumps(result.model_dump(), indent=2)) ] else: raise ValueError(f"Unknown tool: {name}") except Exception as e: raise ValueError(f"Error executing shell command: {str(e)}") logger.info("Initializing server...") options = server.create_initialization_options() async with stdio_server() as (read_stream, write_stream): logger.info("Server started and ready to handle requests") await server.run(read_stream, write_stream, options) ```