Skip to main content
Glama
AI-Safe Terminal MCP Server

AI-Safe Terminal MCP Server

README.md
# AI-Safe Terminal MCP Server

**Prevent AI tool calls from hanging with automatic command safety and smart execution strategies.**

## ๐ŸŒŸ Overview

This MCP (Model Context Protocol) server automatically intercepts and enhances terminal command execution for AI assistants, providing:

- **Automatic Hang Prevention** - No more frozen AI sessions waiting for commands
- **Smart Command Classification** - Routes test/build/long commands to background execution  
- **Cross-Platform Support** - Works on macOS, Linux, and Windows
- **Transparent Operation** - Zero configuration required for AI assistants
- **Comprehensive Logging** - Full context for debugging and monitoring

## ๐Ÿš€ Quick Start

### 1. Installation

```bash
# Clone or extract this project
cd mcp-ai-terminal

# Install Python dependencies
pip install -r requirements.txt

# Install system-wide terminal backends
chmod +x install-ai-terminal.sh
./install-ai-terminal.sh
```

### 2. Start MCP Server

```bash
# Start the MCP server
python mcp-ai-terminal-server.py --port 8000

# Or use the launcher script
./start-mcp-server.sh
```

### 3. Configure AI Client

Add to your AI client's MCP configuration:

```json
{
  "mcpServers": {
    "ai-safe-terminal": {
      "command": "python",
      "args": ["/path/to/mcp-ai-terminal-server.py"],
      "env": {}
    }
  }
}
```

## ๐Ÿ› ๏ธ Architecture

```
AI Assistant
     โ†“
MCP Server (This Project)
     โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Smart Command Classification           โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  Quick Commands โ†’ 8s timeout           โ”‚
โ”‚  Test Commands  โ†’ Background execution โ”‚
โ”‚  Build Commands โ†’ Background execution โ”‚
โ”‚  Long Commands  โ†’ Background execution โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
     โ†“
Cross-Platform Backends
โ”œโ”€โ”€ Unix/macOS: unified-terminal-system.sh
โ”œโ”€โ”€ Windows: unified-terminal-system.ps1
โ””โ”€โ”€ Enhanced: freeze-resistant-terminal.sh
```

## ๐ŸŽฏ Key Features

### Automatic Command Classification
- **Test Commands**: `pytest`, `mvn test`, `npm test` โ†’ Background
- **Build Commands**: `make`, `gradle build`, `npm run build` โ†’ Background  
- **Long Commands**: `git clone`, `npm install`, `docker build` โ†’ Background
- **Quick Commands**: `ls`, `git status`, `cat file.txt` โ†’ 8s timeout

### Hang Prevention Mechanisms
- **Strict Timeouts**: Commands killed after safe thresholds
- **Background Jobs**: Long commands run without blocking AI
- **Freeze Detection**: Monitors output and CPU usage
- **Process Tree Cleanup**: Ensures no zombie processes
- **Graceful Termination**: SIGTERM โ†’ SIGKILL escalation

### Cross-Platform Support
- **macOS**: Native bash with timeout fallbacks
- **Linux**: Full GNU coreutils support
- **Windows**: PowerShell jobs with native timeout handling

## ๐Ÿ“š API Reference

### Tools Provided

#### `run_command_safe`
Execute terminal commands with automatic safety measures.

```json
{
  "command": "mvn clean test",
  "cwd": "/path/to/project", 
  "force_background": false,
  "timeout": 8
}
```

#### `check_command_status`
Monitor background command progress.

```json
{
  "show_output": true
}
```

#### `get_terminal_context`
Retrieve recent terminal activity for debugging.

```json
{
  "lines": 50
}
```

## ๐Ÿงช Testing

### Run Test Suite
```bash
# Test all components
./test-mcp-system.sh

# Test specific scenarios
./test-hang-prevention.sh
./test-background-execution.sh
./test-cross-platform.sh
```

### Manual Testing
```bash
# Test quick command (should complete in <8s)
python mcp-ai-terminal-server.py test-quick "echo 'Hello World'"

# Test background command (should return immediately)
python mcp-ai-terminal-server.py test-background "sleep 30"

# Test freeze detection (should terminate automatically)
python mcp-ai-terminal-server.py test-freeze "while true; do echo ping; sleep 1; done"
```

## ๐Ÿ“ Project Structure

```
mcp-ai-terminal/
โ”œโ”€โ”€ README.md                           # This file
โ”œโ”€โ”€ requirements.txt                    # Python dependencies
โ”œโ”€โ”€ mcp-ai-terminal-server.py          # Main MCP server
โ”œโ”€โ”€ start-mcp-server.sh                # Server launcher
โ”œโ”€โ”€ install-ai-terminal.sh             # System installation
โ”œโ”€โ”€ backends/
โ”‚   โ”œโ”€โ”€ unified-terminal-system.sh     # Unix/macOS backend
โ”‚   โ”œโ”€โ”€ unified-terminal-system.ps1    # Windows backend
โ”‚   โ”œโ”€โ”€ freeze-resistant-terminal.sh   # Enhanced freeze detection
โ”‚   โ””โ”€โ”€ ai-terminal                    # Universal launcher
โ”œโ”€โ”€ tests/
โ”‚   โ”œโ”€โ”€ test-mcp-system.sh            # Full system tests
โ”‚   โ”œโ”€โ”€ test-hang-prevention.sh       # Hang prevention tests
โ”‚   โ””โ”€โ”€ test-cross-platform.sh        # Platform compatibility tests
โ”œโ”€โ”€ docs/
โ”‚   โ”œโ”€โ”€ ARCHITECTURE.md               # Technical architecture
โ”‚   โ”œโ”€โ”€ CROSS-PLATFORM-GUIDE.md      # Platform-specific guide
โ”‚   โ”œโ”€โ”€ MCP-INTEGRATION.md            # MCP client integration
โ”‚   โ””โ”€โ”€ TROUBLESHOOTING.md            # Common issues and solutions
โ””โ”€โ”€ examples/
    โ”œโ”€โ”€ example-ai-client-config.json # Sample MCP configuration
    โ”œโ”€โ”€ demo-commands.sh              # Example command scenarios
    โ””โ”€โ”€ benchmark-performance.sh      # Performance testing
```

## ๐Ÿ”ง Configuration

### Environment Variables
```bash
export AI_TERMINAL_TIMEOUT=8          # Default timeout for quick commands
export AI_TERMINAL_BG_TIMEOUT=300     # Timeout for background commands  
export AI_TERMINAL_OUTPUT_DIR=/tmp/ai-terminal-outputs
export AI_TERMINAL_LOG_LEVEL=INFO
```

### Custom Command Classification
Edit `mcp-ai-terminal-server.py` to customize command patterns:

```python
self.test_patterns = ["test", "spec", "check", "verify"]
self.build_patterns = ["build", "compile", "package", "deploy"]
self.long_patterns = ["install", "download", "clone", "sync"]
```

## ๐Ÿšจ Safety Features

### Timeout Protection
- **Quick Commands**: 8 second maximum execution time
- **Background Commands**: Run independently, never block AI
- **Freeze Detection**: Automatic termination of unresponsive processes

### Resource Management
- **Process Cleanup**: Automatic cleanup of terminated processes
- **Output Limiting**: Prevents memory exhaustion from large outputs
- **Disk Space**: Automatic cleanup of old log files

### Cross-Platform Reliability
- **Timeout Fallbacks**: Perl-based timeouts on macOS when `gtimeout` unavailable
- **Windows Jobs**: PowerShell background jobs with native timeout support
- **Signal Handling**: Proper process termination across all platforms

## ๐Ÿค Integration Examples

### MCP Config
```json
{
  "mcpServers": {
    "ai-safe-terminal": {
      "command": "python3",
      "args": ["/Users/you/.local/bin/mcp-ai-terminal-server.py"]
    }
  }
}
```

## ๐Ÿ“Š Performance

### Benchmark Results
- **Quick Commands**: <100ms overhead
- **Background Commands**: <50ms startup time
- **Freeze Detection**: <3s response time
- **Memory Usage**: <10MB for server + backends

### Scalability
- **Concurrent Commands**: Up to 50 background jobs
- **Log Retention**: Automatic cleanup after 7 days
- **Platform Support**: Tested on 12+ OS configurations

## ๐Ÿ› Troubleshooting

### Common Issues

#### "MCP server not responding"
```bash
# Check if server is running
ps aux | grep mcp-ai-terminal-server

# Check logs
tail -f /tmp/ai-terminal-outputs/mcp-server.log
```

#### "Commands still hanging"
```bash
# Verify backend installation
ai-terminal help

# Test freeze detection
./backends/freeze-resistant-terminal.sh test-freeze
```

#### "Cross-platform issues"
```bash
# Test platform detection
python -c "import platform; print(platform.system())"

# Verify backend scripts
ls -la backends/
```

See `docs/TROUBLESHOOTING.md` for detailed solutions.

## ๐Ÿ”„ Development

### Contributing
1. Fork the repository
2. Create feature branch: `git checkout -b feature/amazing-feature`
3. Run tests: `./tests/test-mcp-system.sh`
4. Commit changes: `git commit -m 'Add amazing feature'`
5. Push branch: `git push origin feature/amazing-feature`
6. Open Pull Request

### Testing New Features
```bash
# Add new test case
echo 'test_my_feature() { ... }' >> tests/test-mcp-system.sh

# Run specific test
./tests/test-mcp-system.sh test_my_feature

# Validate across platforms
./tests/test-cross-platform.sh
```

## ๐Ÿ“œ License

MIT License - see LICENSE file for details.

## ๐Ÿ™ Acknowledgments

- **MCP Protocol**: Model Context Protocol specification
- **Cross-Platform Testing**: Community feedback from macOS, Linux, and Windows users
- **AI Safety Research**: Insights from AI tool call reliability studies

---

**Ready to eliminate AI command hanging forever? Start with the Quick Start guide above!** ๐Ÿš€