Commit b4feee1
Changed files (1)
cmd
bash
cmd/bash/DESIGN.md
@@ -1,215 +1,504 @@
-# MCP Bash Server โ DESIGN.md
+# Bash MCP Server Design
-## ๐ Overview
+## Overview
-This server is part of the [Model Context Protocol (MCP)](https://github.com/xlgmokha/mcp) ecosystem. It exposes a safe and sandboxed Bash shell environment over HTTP so that AI agents can run shell commands, receive outputs, and reason about systems programmatically without unrestricted access to the host system.
+The Bash MCP server provides AI coding agents with direct shell command execution capabilities through the Model Context Protocol. This server enables agents to perform any system operation that doesn't require sudo privileges, making it a powerful tool for development, automation, and system interaction.
----
+## Design Principles
-## ๐งฑ Goals
+### 1. **Unrestricted Access**
+- Execute any shell command that doesn't require sudo
+- No command filtering or sandboxing (by design)
+- Full access to filesystem within user permissions
+- Complete environment variable access
-- Accept Bash command requests from agents
-- Run them in a sandboxed, time-limited environment
-- Return structured results: stdout, stderr, exit code, and duration
-- Be safe by default, and extensible for future improvements (containers, persistent sessions)
+### 2. **Minimal Resource Usage**
+- Lazy loading of all components
+- No background processes or persistent state
+- Minimal memory footprint (<5MB)
+- Efficient command execution without overhead
----
+### 3. **MCP Protocol Compliance**
+- Standard JSON-RPC 2.0 over stdio
+- Proper tool definitions with JSON schemas
+- Resource discovery for system information
+- Clean error handling and responses
-## ๐ Directory Structure
+### 4. **Performance First**
+- Fast startup (<2ms)
+- Streaming output support for long-running commands
+- Configurable timeouts
+- Asynchronous execution where beneficial
+## Architecture
+
+```
+AI Agent โ JSON-RPC โ Bash Server โ Shell Execution โ System
+ โ
+ Environment Management
+ โ
+ Output Processing
```
-mcp/
-โโโ cmd/
-โ โโโ bash/
-โ โโโ main.go # Entrypoint HTTP server
-โโโ pkg/
-โ โโโ bash/
-โ โโโ server.go # Handles command execution
-โโโ go.mod
-````
+## Tool Specifications
----
+### Core Execution Tools
-## ๐ HTTP API
+#### `bash_exec`
+**Primary command execution tool**
-### POST `/run`
+```json
+{
+ "name": "bash_exec",
+ "description": "Execute a shell command and return output",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "command": {
+ "type": "string",
+ "description": "Shell command to execute"
+ },
+ "working_dir": {
+ "type": "string",
+ "description": "Working directory for command execution (optional)"
+ },
+ "timeout": {
+ "type": "number",
+ "description": "Timeout in seconds (default: 30, max: 300)"
+ },
+ "capture_stderr": {
+ "type": "boolean",
+ "description": "Include stderr in output (default: true)"
+ },
+ "env": {
+ "type": "object",
+ "description": "Additional environment variables"
+ }
+ },
+ "required": ["command"]
+ }
+}
+```
-#### Request
+**Response Format:**
+```json
+{
+ "stdout": "command output",
+ "stderr": "error output",
+ "exit_code": 0,
+ "execution_time_ms": 150,
+ "working_dir": "/current/directory",
+ "command": "ls -la"
+}
+```
+
+#### `bash_exec_stream`
+**Streaming command execution for long-running processes**
```json
{
- "command": "ls -al",
- "timeout_seconds": 5
+ "name": "bash_exec_stream",
+ "description": "Execute command with real-time output streaming",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "command": {"type": "string"},
+ "working_dir": {"type": "string"},
+ "timeout": {"type": "number"},
+ "buffer_size": {"type": "number", "description": "Stream buffer size in bytes"}
+ },
+ "required": ["command"]
+ }
}
-````
+```
-* `command` (string): Shell command to run.
-* `timeout_seconds` (int): Optional. Max seconds to allow execution. Default: 5.
+### Documentation Tools
-#### Response
+#### `man_page`
+**Access system manual pages**
```json
{
- "stdout": "total 0\n-rw-r--r-- file1\n",
- "stderr": "",
- "exit_code": 0,
- "duration_ms": 13
+ "name": "man_page",
+ "description": "Get manual page for a command",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "command": {"type": "string", "description": "Command to get manual for"},
+ "section": {"type": "string", "description": "Manual section (1-8)"}
+ },
+ "required": ["command"]
+ }
}
```
----
-
-## ๐ง Internal API
+#### `which_command`
+**Locate command binaries**
-```go
-type CommandRequest struct {
- Command string
- TimeoutSeconds int
+```json
+{
+ "name": "which_command",
+ "description": "Find the location of a command",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "command": {"type": "string"}
+ },
+ "required": ["command"]
+ }
}
+```
-type CommandResult struct {
- Stdout string
- Stderr string
- ExitCode int
- DurationMs int64
+#### `command_help`
+**Get command help information**
+
+```json
+{
+ "name": "command_help",
+ "description": "Get help text for a command (--help flag)",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "command": {"type": "string"}
+ },
+ "required": ["command"]
+ }
}
+```
+
+### Environment Management Tools
-func RunCommand(ctx context.Context, req CommandRequest) (CommandResult, error)
+#### `get_env`
+**Access environment variables**
+
+```json
+{
+ "name": "get_env",
+ "description": "Get environment variable value",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "variable": {"type": "string", "description": "Environment variable name"},
+ "all": {"type": "boolean", "description": "Return all environment variables"}
+ }
+ }
+}
```
-* Executes a shell command using Go's `os/exec`.
-* Handles timeout using `context.WithTimeout`.
-* Returns captured output and metadata.
+#### `get_working_dir`
+**Get current working directory**
----
+```json
+{
+ "name": "get_working_dir",
+ "description": "Get the current working directory",
+ "inputSchema": {"type": "object"}
+}
+```
-## ๐ Security & Sandbox Plan
+#### `set_working_dir`
+**Change working directory for subsequent commands**
-**Initial Implementation (MVP):**
+```json
+{
+ "name": "set_working_dir",
+ "description": "Set working directory for future commands",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "directory": {"type": "string"}
+ },
+ "required": ["directory"]
+ }
+}
+```
-* Use a per-request working directory under a configured root (e.g. `/tmp/mcp/bash-<uuid>`)
-* Timeout enforcement
-* Drop privileges by running under a non-root user
-* Optional input validation for dangerous commands
+### System Information Tools
-**Future Options:**
+#### `system_info`
+**Get system information**
-* Use `nsjail`, `firejail`, or containers (`podman`, `docker`)
-* CPU and memory limits
-* Disk quotas and file write limits
-* Per-agent execution UID
+```json
+{
+ "name": "system_info",
+ "description": "Get basic system information",
+ "inputSchema": {"type": "object"}
+}
+```
----
+**Returns:**
+```json
+{
+ "hostname": "server.local",
+ "os": "Linux",
+ "architecture": "x86_64",
+ "kernel": "5.15.0",
+ "shell": "/bin/bash",
+ "user": "username",
+ "home": "/home/username",
+ "path": "/usr/bin:/bin:/usr/local/bin"
+}
+```
-## โ๏ธ Configuration
+#### `process_info`
+**Get information about running processes**
-| Method | Variable/Flag | Description | Default |
-| ---------------- | ------------------------ | ---------------------------------------------- | --------------- |
-| CLI flag | `--workdir=/path/to/dir` | Root directory for sandboxed command execution | `/tmp/mcp/bash` |
-| Environment var | `MCP_BASH_ROOT_DIR` | Fallback if flag not provided | `/tmp/mcp/bash` |
-| Internal default | (hardcoded fallback) | Used if neither flag nor env var is set | `/tmp/mcp/bash` |
+```json
+{
+ "name": "process_info",
+ "description": "Get process information (ps command wrapper)",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "format": {"type": "string", "description": "ps format string (default: aux)"},
+ "filter": {"type": "string", "description": "grep filter for processes"}
+ }
+ }
+}
+```
-> **Note:** The CLI flag takes precedence over the environment variable.
+## Resources
----
+### System Resources
+- **URI Format**: `bash://system/info`
+- **Description**: Live system information and environment state
+- **Content**: JSON with current system status
-## โ
MVP Checklist
+### Command History Resource
+- **URI Format**: `bash://history/recent`
+- **Description**: Recent command execution history
+- **Content**: JSON array of recent commands with metadata
-* [ ] Basic HTTP server using `net/http`
-* [ ] POST `/run` endpoint
-* [ ] Timeout via `context.WithTimeout`
-* [ ] Use `exec.CommandContext` to run the command
-* [ ] Capture and return stdout, stderr, exit code, and timing
-* [ ] Create temporary working directory per request under the configured root
-* [ ] Add unit and integration tests
-* [ ] Support `--workdir` CLI flag and `MCP_BASH_ROOT_DIR` env var
+### Environment Resource
+- **URI Format**: `bash://env/all`
+- **Description**: Complete environment variables
+- **Content**: JSON object with all environment variables
----
+## Implementation Details
-## ๐งช Testing
+### Server Structure
-**Unit Tests:**
+```go
+type BashServer struct {
+ *mcp.Server
+ workingDir string
+ commandHistory []CommandRecord
+ mu sync.RWMutex
+}
-* Mock command runner
-* Validate request parsing, output formatting
+type CommandRecord struct {
+ Timestamp time.Time `json:"timestamp"`
+ Command string `json:"command"`
+ WorkingDir string `json:"working_dir"`
+ ExitCode int `json:"exit_code"`
+ Duration int64 `json:"duration_ms"`
+ OutputSize int `json:"output_size_bytes"`
+}
+```
-**Integration Tests:**
+### Command Execution
-* Execute safe commands (`echo`, `ls`)
-* Validate timeout behavior
-* Capture output correctness
+```go
+type ExecutionOptions struct {
+ Command string `json:"command"`
+ WorkingDir string `json:"working_dir,omitempty"`
+ Timeout int `json:"timeout,omitempty"`
+ Env map[string]string `json:"env,omitempty"`
+ CaptureStderr bool `json:"capture_stderr"`
+}
-**Security Tests:**
+type ExecutionResult struct {
+ Stdout string `json:"stdout"`
+ Stderr string `json:"stderr"`
+ ExitCode int `json:"exit_code"`
+ ExecutionTime int64 `json:"execution_time_ms"`
+ WorkingDir string `json:"working_dir"`
+ Command string `json:"command"`
+}
+```
-* Try `yes > /dev/null`
-* Try fork bomb: `:(){ :|:& };:`
-* Try `rm -rf /` (should be blocked or jailed)
+### Resource Management
----
+```go
+// Lazy loading - no persistent state
+func (bs *BashServer) registerResources() {
+ // Register lightweight resource placeholders
+ systemResource := mcp.Resource{
+ URI: "bash://system/info",
+ Name: "System Information",
+ Description: "Live system information and environment state",
+ MimeType: "application/json",
+ }
+ bs.Server.RegisterResourceWithDefinition(systemResource, bs.HandleSystemResource)
+}
+```
-## ๐ฆ Dependencies
+### Streaming Implementation
-* Go stdlib:
+```go
+type StreamingExecution struct {
+ cmd *exec.Cmd
+ stdout io.ReadCloser
+ stderr io.ReadCloser
+ done chan error
+}
- * `os/exec`, `context`, `net/http`, `encoding/json`, `time`, `io/ioutil`, `flag`
-* Optional:
+func (bs *BashServer) executeStreaming(options ExecutionOptions) (*StreamingExecution, error) {
+ // Non-blocking command execution with streaming output
+ // Real-time stdout/stderr streaming via channels
+}
+```
- * `github.com/google/uuid`
- * `github.com/gorilla/mux` (for extensible routing)
+## Security Considerations (Future)
----
+### Current Design (Unrestricted)
+- No command filtering
+- No sandboxing
+- Full filesystem access (within user permissions)
+- No sudo prevention (relies on system configuration)
-## ๐งฌ Future Work
+### Future Security Options
+- Command whitelist/blacklist patterns
+- Working directory restrictions
+- Resource usage limits
+- Audit logging
+- Timeout enforcement
+- Network access controls
-* [ ] Persistent shell sessions (`cd`, variables, etc.)
-* [ ] Command history and working memory
-* [ ] Streaming I/O for interactive commands
-* [ ] File upload API to allow scripts/data to be passed in
-* [ ] gRPC API
+## Performance Characteristics
----
+### Resource Usage
+- **Memory**: <5MB baseline
+- **CPU**: Minimal overhead, direct process execution
+- **Startup**: <2ms
+- **Command Overhead**: <1ms per execution
-## โจ Example Usage
+### Scalability
+- Stateless execution model
+- No connection pooling required
+- Concurrent command execution support
+- Configurable resource limits
-Start server with flag:
+## Configuration
+### Environment Variables
```bash
-go run ./cmd/bash --workdir=/home/mokhax/src
+BASH_MCP_DEFAULT_TIMEOUT=30 # Default command timeout
+BASH_MCP_MAX_TIMEOUT=300 # Maximum allowed timeout
+BASH_MCP_MAX_HISTORY=100 # Command history size
+BASH_MCP_WORKING_DIR=/tmp # Default working directory
```
-Or using environment variable:
-
+### Command Line Flags
```bash
-export MCP_BASH_ROOT_DIR=/srv/mcp/tmp
-go run ./cmd/bash
+mcp-bash [options]
+ --default-timeout int Default command timeout in seconds (default: 30)
+ --max-timeout int Maximum command timeout in seconds (default: 300)
+ --history-size int Command history size (default: 100)
+ --working-dir string Default working directory (default: current)
```
-Run a command:
+## Example Usage Patterns
+### Development Workflow
```bash
-curl -X POST http://localhost:8080/run \
- -H "Content-Type: application/json" \
- -d '{"command": "ls -al", "timeout_seconds": 3}'
+# Project setup
+git clone https://github.com/user/project.git
+cd project
+npm install
+npm test
+
+# Build and deploy
+make build
+docker build -t myapp .
+docker run -p 3000:3000 myapp
```
----
-
-## ๐ง Why Bash?
-
-* Ideal for scripting, file system exploration, automation
-* Agents can use familiar Unix semantics
-* Can be secured and sandboxed effectively
-* Supports future composability (e.g., running other MCP servers via CLI tools)
-
----
-
-## ๐งฉ Integration Notes
-
-This server can be coordinated with other `mcp` services (e.g. `git`, `fs`, `edit`) via a central orchestrator or CLI client. Each server is standalone, stateless, and focused on one domain of control.
+### System Administration
+```bash
+# Process monitoring
+ps aux | grep nginx
+netstat -tulpn | grep :80
+systemctl status nginx
+
+# Log analysis
+tail -f /var/log/nginx/error.log
+grep "ERROR" /var/log/app/*.log
+```
----
+### File Operations
+```bash
+# Complex file operations
+find . -name "*.log" -mtime +7 -delete
+tar -czf backup.tar.gz --exclude='node_modules' .
+rsync -av src/ backup/src/
+```
-**Author:** [mo khan](https://github.com/xlgmokha)
-**Project:** [MCP](https://github.com/xlgmokha/mcp)
-**License:** MIT
+## Integration with Other MCP Servers
+
+### Complementary Usage
+- **Filesystem MCP**: High-level file operations
+- **Bash MCP**: Complex shell operations and automation
+- **Git MCP**: Git-specific operations
+- **Bash MCP**: Advanced git workflows and scripting
+
+### Resource Sharing
+- Bash server can invoke other MCP tools indirectly
+- Shared working directory concepts
+- Environment variable coordination
+
+## Future Enhancements
+
+### Phase 1 Additions
+- Command completion suggestions
+- Interactive shell session support
+- Background process management
+- Signal handling (SIGINT, SIGTERM)
+
+### Phase 2 Additions
+- Command history search and replay
+- Macro/script execution
+- Pipeline composition tools
+- Performance monitoring
+
+### Phase 3 Additions
+- Multi-server orchestration
+- Distributed command execution
+- Advanced streaming capabilities
+- Custom shell environments
+
+## Testing Strategy
+
+### Unit Tests
+- Command execution validation
+- Error handling verification
+- Resource management testing
+- Performance benchmarking
+
+### Integration Tests
+- Real command execution
+- Timeout handling
+- Working directory management
+- Environment variable handling
+
+### Performance Tests
+- Concurrent execution limits
+- Memory usage under load
+- Command execution overhead
+- Streaming performance
+
+## Deployment Considerations
+
+### Minimal Setup
+- Single binary deployment
+- No external dependencies
+- Standard stdio interface
+- Environment-based configuration
+
+### Production Readiness
+- Process supervision (systemd, supervisor)
+- Log rotation and management
+- Resource monitoring
+- Graceful shutdown handling
+
+This design provides maximum flexibility and power while maintaining the minimal resource usage and lazy loading principles. The unrestricted nature allows for comprehensive AI agent capabilities while keeping the door open for future security enhancements based on observed usage patterns.