# Terminal Control MCP Server
A modern MCP server that enables AI agents to control terminal sessions through persistent tmux-based sessions. Features real-time web interface for direct user access, comprehensive security controls, and support for interactive terminal programs including debuggers, SSH connections, and database clients.
## โจ Features
### ๐ฅ๏ธ **Tmux-Based Terminal Control**
- **Reliable Backend**: Built on tmux and libtmux for stable terminal multiplexing
- **Session Persistence**: Long-running sessions with automatic cleanup and monitoring
- **Raw Stream Capture**: Direct terminal output via tmux pipe-pane
- **Agent-Controlled**: AI agents manage timing and interaction flow without automatic timeouts
- **Flexible Content Modes**: Get screen, history, since-input, or tail output for optimal workflow control
- **Dual Access**: Both agent (MCP tools) and user (web browser) can interact simultaneously
### ๐ **Optional Web Interface**
- **Real-time Terminal**: Live xterm.js terminal emulator with WebSocket updates
- **Session URLs**: Direct browser access to any terminal session
- **Zero Setup**: Automatic web server startup with configurable networking
- **Manual Control**: Send commands directly without interrupting agent workflows
- **Session Management**: View all active sessions and their status
### ๐ก๏ธ **Comprehensive Security**
- **Command Filtering**: Block dangerous operations (`rm -rf /`, `sudo`, disk formatting, etc.)
- **Path Protection**: Restrict access to user directories only
- **Rate Limiting**: 60 calls/minute with session limits (max 50 concurrent)
- **Audit Logging**: Complete security event tracking
- **Input Validation**: Multi-layer validation for all inputs
- **Configurable Levels**: Off, low, medium, high protection levels
## ๐ Quick Start
### System Requirements
This package requires `tmux` for terminal multiplexing:
```bash
# Ubuntu/Debian
sudo apt update && sudo apt install -y tmux
# macOS
brew install tmux
# CentOS/RHEL/Fedora
sudo yum install tmux # or sudo dnf install tmux
```
**Python Requirements**: Python 3.11 or later
### Installation
```bash
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # Linux/macOS
# .venv\Scripts\activate # Windows
# Install the package
pip install .
# Or install in development mode
pip install -e ".[dev]"
```
### Configuration
The server supports configuration through TOML files and environment variables:
#### **Claude Code (Anthropic)**
1. **Install the package** (required for console script):
```bash
pip install .
```
2. **Add the MCP server**:
```bash
# Recommended: User scope (available across all projects)
claude mcp add terminal-control -s user terminal-control-mcp
# Alternative: Project scope (current project only)
claude mcp add terminal-control terminal-control-mcp
```
3. **Verify installation**:
```bash
claude mcp list
```
The MCP server will be automatically launched by Claude Code when needed. The web interface starts automatically (if enabled) for direct session access.
#### **Other MCP Clients**
For other MCP clients, add to your configuration:
```json
{
"mcpServers": {
"terminal-control": {
"command": "terminal-control-mcp",
"cwd": "/path/to/working/directory"
}
}
}
```
## ๐ง Configuration
### **Configuration Methods**
The server supports two configuration methods:
1. **TOML Configuration File** (recommended): `terminal-control.toml`
2. **Environment Variables**: Override TOML settings for deployment
### **Configuration Options**
#### **Web Server**
```bash
# Enable/disable web interface (default: false)
export TERMINAL_CONTROL_WEB_ENABLED=false
# Web server networking
export TERMINAL_CONTROL_WEB_HOST=0.0.0.0 # Default: bind to all interfaces
export TERMINAL_CONTROL_WEB_PORT=8080 # Default port
export TERMINAL_CONTROL_WEB_AUTO_PORT=true # Automatic unique port selection
export TERMINAL_CONTROL_EXTERNAL_HOST=server.example.com # External hostname for URLs
```
**Web Interface Modes:**
- **Enabled** (`web_enabled=true`): Real-time web interface with xterm.js terminal emulator
- **Disabled** (`web_enabled=false`): Automatically opens system terminal windows attached to tmux sessions
#### **Security**
```bash
# Security level (default: high)
export TERMINAL_CONTROL_SECURITY_LEVEL=high # off, low, medium, high
# Rate limiting and session limits
export TERMINAL_CONTROL_MAX_CALLS_PER_MINUTE=60
export TERMINAL_CONTROL_MAX_SESSIONS=50
```
**Security Levels:**
- **`off`**: No validation (โ ๏ธ **USE WITH EXTREME CAUTION**)
- **`low`**: Basic input validation only
- **`medium`**: Standard protection (blocks common dangerous commands)
- **`high`**: Full protection (comprehensive validation and filtering)
#### **Session Configuration**
```bash
# Default shell and timeout
export TERMINAL_CONTROL_DEFAULT_SHELL=bash
export TERMINAL_CONTROL_SESSION_TIMEOUT=30
```
#### **Terminal Configuration**
```bash
# Terminal dimensions
export TERMINAL_CONTROL_TERMINAL_WIDTH=120
export TERMINAL_CONTROL_TERMINAL_HEIGHT=30
# Performance tuning
export TERMINAL_CONTROL_TERMINAL_POLLING_INTERVAL=0.05
export TERMINAL_CONTROL_TERMINAL_SEND_INPUT_DELAY=0.1
# Process timeouts
export TERMINAL_CONTROL_TERMINAL_CLOSE_TIMEOUT=5.0
export TERMINAL_CONTROL_TERMINAL_PROCESS_CHECK_TIMEOUT=1.0
```
**Terminal Emulator Support:**
The system automatically detects and uses available terminal emulators in order of preference:
- **GNOME/GTK**: gnome-terminal
- **KDE**: konsole
- **XFCE**: xfce4-terminal
- **Elementary OS**: io.elementary.terminal
- **Generic**: x-terminal-emulator, xterm
- **macOS**: Terminal (via `open -a Terminal`)
- **Modern terminals**: alacritty, kitty, terminator
**Custom Terminal Emulator Configuration:**
You can customize terminal emulator preferences through the `[terminal]` section in `terminal-control.toml`:
```toml
[terminal]
# Terminal dimensions and performance settings
width = 120
height = 30
close_timeout = 5.0
process_check_timeout = 1.0
polling_interval = 0.05
send_input_delay = 0.1
# Custom terminal emulator configuration (ordered by preference)
emulators = [
{ name = "my-terminal", command = ["my-terminal", "--exec"] },
{ name = "gnome-terminal", command = ["gnome-terminal", "--"] },
{ name = "konsole", command = ["konsole", "-e"] },
# ... other terminals
]
```
#### **Multi-Instance Port Management**
**Automatic Port Selection:**
When multiple server instances run simultaneously, ports are automatically selected to avoid conflicts:
```bash
# Automatic port selection (default: enabled)
export TERMINAL_CONTROL_WEB_AUTO_PORT=true
# How it works:
# - Base port: 9000-9999 range
# - Selection: hash(working_dir + process_id) % 1000 + 9000
# - Consistent: Same directory always gets same port
```
### **TOML Configuration Example**
Create `terminal-control.toml` in your project root:
```toml
[web]
enabled = false # Use terminal windows instead of web interface
host = "0.0.0.0"
port = 8080
auto_port = true # Automatic unique port selection
[security]
level = "high"
max_calls_per_minute = 60
max_sessions = 50
[session]
default_shell = "bash"
timeout = 30
[terminal]
width = 120
height = 30
close_timeout = 5.0
process_check_timeout = 1.0
polling_interval = 0.05
send_input_delay = 0.1
[logging]
level = "INFO"
```
## ๐ ๏ธ MCP Tools (5 Tools)
The server provides 5 MCP tools for complete terminal session lifecycle management:
### **Session Management**
#### **`list_terminal_sessions`**
List all active terminal sessions with status information.
**Returns:**
- Session IDs, commands, and states
- Creation timestamps and last activity
- Total session count (max 50)
- Web interface URLs (if enabled)
#### **`exit_terminal`**
Terminate and cleanup a terminal session.
**Parameters:**
- `session_id`: Session ID to destroy
**Features:**
- **Bidirectional cleanup**: Sessions destroyed when agents call `exit_terminal` OR when users type `exit`
- **Automatic monitoring**: Dead sessions detected and cleaned up every 5 seconds
- **Terminal window management**: Closes associated terminal windows when web interface is disabled
### **Content Retrieval**
#### **`get_screen_content`**
Get terminal content with precise control over output format.
**Parameters:**
- `session_id`: Session to get content from
- `content_mode`: Content retrieval mode
- `"screen"` (default): Current visible screen only
- `"since_input"`: Output since last input command
- `"history"`: Full terminal history
- `"tail"`: Last N lines (requires `line_count`)
- `line_count`: Number of lines for tail mode
**Returns:**
- Terminal content based on mode
- Process running status
- ISO timestamp for agent timing decisions
### **Input Control**
#### **`send_input`**
Send input to terminal sessions.
**Parameters:**
- `session_id`: Target session
- `input_text`: Text to send (supports escape sequences)
**Important:** Newlines are NOT automatically added. For command execution, explicitly include `\n` (e.g., `"ls\n"`, `"python\n"`).
**Features:**
- Raw input support with escape sequences
- No automatic timeouts (agent-controlled timing)
- Parallel user input possible via web interface
### **Session Creation**
#### **`open_terminal`**
Create new terminal sessions.
**Parameters:**
- `shell`: Shell to use (bash, zsh, fish, sh, etc.)
- `working_directory`: Starting directory (optional)
- `environment`: Environment variables (optional)
**Returns:**
- Unique session ID
- Initial screen content
- Web interface URL (if enabled)
- Process startup status
**Features:**
- Universal shell support
- Environment and directory control
- Immediate screen content availability
## ๐ Usage Examples
### **Basic Commands**
```bash
# Natural language requests to Claude:
"Start a Python session and show me what's on screen"
"List all my active terminal sessions"
"What's currently showing in the terminal?"
"Type 'print(2+2)' in the Python session"
"Close that debugging session"
```
### **Interactive Programs**
```bash
# Complex interactive workflows:
"Start a Python REPL and help me debug this script"
"SSH into the server and check disk space"
"Connect to MySQL and show me the database tables"
"Run the debugger and set breakpoints in the main function"
"Start a docker container and explore the filesystem"
```
### **Debugging Workflow**
Using the included `examples/example_debug.py`:
```bash
# 1. Start debugging session
"Debug the file examples/example_debug.py and show me the code"
# 2. Explore and set breakpoints
"Show me the source code around the current line"
"Set a breakpoint where the bug occurs"
# 3. Investigate the problem
"Step through the buggy loop and show variable values"
"What variables do we have here? Show their values"
# 4. Clean up
"We found the bug! Clean up this debugging session"
```
**Pro tip:** If you set `web_enabled=true` in your configuration, you can also access the debugging session directly in your browser for real-time interaction.
### **Web Interface Usage**
When web interface is enabled:
1. Agent creates session: `"Starting debugger session..."`
2. Agent provides URL: `"You can also access it at http://localhost:9123/session/abc123"`
3. User opens URL in browser for direct interaction
4. Both agent and user can send commands simultaneously
## ๐ Web Interface
### **Real-Time Terminal Access**
- **Live output**: See exactly what agents see in real-time
- **Manual input**: Send commands directly without agent awareness
- **WebSocket updates**: Automatic screen refreshes
- **Session overview**: View all active sessions at once
### **Session URLs**
- **Individual sessions**: `http://localhost:8080/session/{session_id}`
- **Session overview**: `http://localhost:8080/`
- **Direct browser access**: No additional software required
- **Transparent to agents**: Manual interaction doesn't interfere with agent control
## ๐ Security
### **Defense-in-Depth Approach**
- **Command filtering**: Blocks dangerous operations (`rm -rf /`, `sudo`, `dd`, etc.)
- **Path restrictions**: Commands run in specified directories only
- **Input validation**: Multi-layer validation for all inputs
- **Environment protection**: Protects critical variables (`PATH`, `LD_PRELOAD`, etc.)
- **Rate limiting**: Prevents abuse with configurable limits
- **Audit logging**: Complete security event tracking
### **Agent-Controlled Philosophy**
- **Maximum flexibility**: Security balanced with functionality
- **User responsibility**: Security managed by user and agent choices
- **Transparent operation**: All commands create persistent sessions
- **No hidden automation**: Agents control all timing and interaction
## ๐ Project Structure
```
terminal-control-mcp/
โโโ src/terminal_control_mcp/
โ โโโ main.py # FastMCP server with 5 MCP tools
โ โโโ session_manager.py # Session lifecycle management
โ โโโ interactive_session.py # Tmux/libtmux process control
โ โโโ terminal_utils.py # Terminal window management
โ โโโ web_server.py # FastAPI web interface
โ โโโ security.py # Multi-layer security validation
โ โโโ config.py # TOML configuration handling
โ โโโ models.py # Pydantic request/response models
โ โโโ templates/ # Web interface templates
โ โ โโโ index.html # Session overview page
โ โ โโโ session.html # Individual session interface
โ โโโ static/ # Web interface assets
โ โโโ css/ # Stylesheets
โ โโโ js/ # JavaScript modules
โโโ tests/ # Comprehensive test suite
โ โโโ test_security_manager.py
โ โโโ test_execute_command.py
โ โโโ test_session_lifecycle.py
โ โโโ test_mcp_integration.py
โโโ examples/
โ โโโ example_debug.py # Sample debugging script
โโโ logs/interactions/ # Session interaction logs
โโโ CLAUDE.md # Development guidance
โโโ terminal-control.toml # TOML configuration
โโโ pyproject.toml # Python packaging configuration
```
## ๐งช Development
### **Testing**
```bash
# Run all tests
pytest tests/
# Run specific test categories
pytest -m unit # Unit tests
pytest -m integration # Integration tests
pytest -m security # Security tests
# Run with coverage
pytest --cov=src/terminal_control_mcp tests/
```
### **Code Quality**
```bash
# Type checking
mypy src/ --ignore-missing-imports
# Linting and formatting
ruff check src/ tests/
black src/ tests/
# Check for dead code
vulture src/
```
### **Development Installation**
```bash
# Install with development dependencies
pip install -e ".[dev]"
# Test basic functionality
python tests/conftest.py
```
## ๐ Development Status
- โ
**Tmux Integration**: Complete libtmux-based terminal control
- โ
**Web Interface**: Real-time xterm.js with WebSocket synchronization
- โ
**Agent Control**: 5 MCP tools for complete session management
- โ
**Security Layer**: Multi-layer validation and audit logging
- โ
**TOML Configuration**: Structured configuration with environment overrides
- โ
**Type Safety**: Full Pydantic models and mypy coverage
- โ
**Test Coverage**: Comprehensive test suite with multiple categories
- โ
**Production Ready**: Reliable session management with proper cleanup
## ๐ License
MIT License - see LICENSE file for details.
## ๐ค Contributing
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes and add tests
4. Ensure all tests pass:
```bash
ruff check src/ tests/ && mypy src/ --ignore-missing-imports && pytest tests/
```
5. Commit your changes (`git commit -m 'Add amazing feature'`)
6. Push to the branch (`git push origin feature/amazing-feature`)
7. Open a Pull Request
## ๐ Acknowledgments
- Built on the [Model Context Protocol (MCP)](https://github.com/anthropics/mcp) by Anthropic
- Uses [libtmux](https://libtmux.git-pull.com/) for reliable terminal multiplexing
- Powered by [FastAPI](https://fastapi.tiangolo.com/) and [xterm.js](https://xtermjs.org/) for the web interface
Raw data
{
"_id": null,
"home_page": null,
"name": "terminal-control-mcp",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.11",
"maintainer_email": null,
"keywords": "mcp, terminal, control, debugging, ssh, database",
"author": null,
"author_email": "Mark Wernsdorfer <wernsdorfer@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/23/32/93a755479739f98a4175a5dd55d59b44c460585d57232b57dd05e60b844c/terminal_control_mcp-1.0.0.tar.gz",
"platform": null,
"description": "# Terminal Control MCP Server\n\nA modern MCP server that enables AI agents to control terminal sessions through persistent tmux-based sessions. Features real-time web interface for direct user access, comprehensive security controls, and support for interactive terminal programs including debuggers, SSH connections, and database clients.\n\n## \u2728 Features\n\n### \ud83d\udda5\ufe0f **Tmux-Based Terminal Control**\n- **Reliable Backend**: Built on tmux and libtmux for stable terminal multiplexing\n- **Session Persistence**: Long-running sessions with automatic cleanup and monitoring\n- **Raw Stream Capture**: Direct terminal output via tmux pipe-pane\n- **Agent-Controlled**: AI agents manage timing and interaction flow without automatic timeouts\n- **Flexible Content Modes**: Get screen, history, since-input, or tail output for optimal workflow control\n- **Dual Access**: Both agent (MCP tools) and user (web browser) can interact simultaneously\n\n### \ud83c\udf10 **Optional Web Interface**\n- **Real-time Terminal**: Live xterm.js terminal emulator with WebSocket updates\n- **Session URLs**: Direct browser access to any terminal session\n- **Zero Setup**: Automatic web server startup with configurable networking\n- **Manual Control**: Send commands directly without interrupting agent workflows\n- **Session Management**: View all active sessions and their status\n\n### \ud83d\udee1\ufe0f **Comprehensive Security**\n- **Command Filtering**: Block dangerous operations (`rm -rf /`, `sudo`, disk formatting, etc.)\n- **Path Protection**: Restrict access to user directories only\n- **Rate Limiting**: 60 calls/minute with session limits (max 50 concurrent)\n- **Audit Logging**: Complete security event tracking\n- **Input Validation**: Multi-layer validation for all inputs\n- **Configurable Levels**: Off, low, medium, high protection levels\n\n## \ud83d\ude80 Quick Start\n\n### System Requirements\n\nThis package requires `tmux` for terminal multiplexing:\n\n```bash\n# Ubuntu/Debian\nsudo apt update && sudo apt install -y tmux\n\n# macOS\nbrew install tmux\n\n# CentOS/RHEL/Fedora\nsudo yum install tmux # or sudo dnf install tmux\n```\n\n**Python Requirements**: Python 3.11 or later\n\n### Installation\n\n```bash\n# Create virtual environment\npython -m venv .venv\nsource .venv/bin/activate # Linux/macOS\n# .venv\\Scripts\\activate # Windows\n\n# Install the package\npip install .\n\n# Or install in development mode\npip install -e \".[dev]\"\n```\n\n### Configuration\n\nThe server supports configuration through TOML files and environment variables:\n\n#### **Claude Code (Anthropic)**\n\n1. **Install the package** (required for console script):\n ```bash\n pip install .\n ```\n\n2. **Add the MCP server**:\n ```bash\n # Recommended: User scope (available across all projects)\n claude mcp add terminal-control -s user terminal-control-mcp\n \n # Alternative: Project scope (current project only)\n claude mcp add terminal-control terminal-control-mcp\n ```\n\n3. **Verify installation**:\n ```bash\n claude mcp list\n ```\n\nThe MCP server will be automatically launched by Claude Code when needed. The web interface starts automatically (if enabled) for direct session access.\n\n#### **Other MCP Clients**\n\nFor other MCP clients, add to your configuration:\n\n```json\n{\n \"mcpServers\": {\n \"terminal-control\": {\n \"command\": \"terminal-control-mcp\",\n \"cwd\": \"/path/to/working/directory\"\n }\n }\n}\n```\n\n## \ud83d\udd27 Configuration\n\n### **Configuration Methods**\n\nThe server supports two configuration methods:\n\n1. **TOML Configuration File** (recommended): `terminal-control.toml`\n2. **Environment Variables**: Override TOML settings for deployment\n\n### **Configuration Options**\n\n#### **Web Server**\n```bash\n# Enable/disable web interface (default: false)\nexport TERMINAL_CONTROL_WEB_ENABLED=false\n\n# Web server networking\nexport TERMINAL_CONTROL_WEB_HOST=0.0.0.0 # Default: bind to all interfaces\nexport TERMINAL_CONTROL_WEB_PORT=8080 # Default port\nexport TERMINAL_CONTROL_WEB_AUTO_PORT=true # Automatic unique port selection\nexport TERMINAL_CONTROL_EXTERNAL_HOST=server.example.com # External hostname for URLs\n```\n\n**Web Interface Modes:**\n- **Enabled** (`web_enabled=true`): Real-time web interface with xterm.js terminal emulator\n- **Disabled** (`web_enabled=false`): Automatically opens system terminal windows attached to tmux sessions\n\n#### **Security**\n```bash\n# Security level (default: high)\nexport TERMINAL_CONTROL_SECURITY_LEVEL=high # off, low, medium, high\n\n# Rate limiting and session limits\nexport TERMINAL_CONTROL_MAX_CALLS_PER_MINUTE=60\nexport TERMINAL_CONTROL_MAX_SESSIONS=50\n```\n\n**Security Levels:**\n- **`off`**: No validation (\u26a0\ufe0f **USE WITH EXTREME CAUTION**)\n- **`low`**: Basic input validation only\n- **`medium`**: Standard protection (blocks common dangerous commands)\n- **`high`**: Full protection (comprehensive validation and filtering)\n\n#### **Session Configuration**\n```bash\n# Default shell and timeout\nexport TERMINAL_CONTROL_DEFAULT_SHELL=bash\nexport TERMINAL_CONTROL_SESSION_TIMEOUT=30\n```\n\n#### **Terminal Configuration**\n```bash\n# Terminal dimensions\nexport TERMINAL_CONTROL_TERMINAL_WIDTH=120\nexport TERMINAL_CONTROL_TERMINAL_HEIGHT=30\n\n# Performance tuning\nexport TERMINAL_CONTROL_TERMINAL_POLLING_INTERVAL=0.05\nexport TERMINAL_CONTROL_TERMINAL_SEND_INPUT_DELAY=0.1\n\n# Process timeouts\nexport TERMINAL_CONTROL_TERMINAL_CLOSE_TIMEOUT=5.0\nexport TERMINAL_CONTROL_TERMINAL_PROCESS_CHECK_TIMEOUT=1.0\n```\n\n**Terminal Emulator Support:**\nThe system automatically detects and uses available terminal emulators in order of preference:\n- **GNOME/GTK**: gnome-terminal\n- **KDE**: konsole \n- **XFCE**: xfce4-terminal\n- **Elementary OS**: io.elementary.terminal\n- **Generic**: x-terminal-emulator, xterm\n- **macOS**: Terminal (via `open -a Terminal`)\n- **Modern terminals**: alacritty, kitty, terminator\n\n**Custom Terminal Emulator Configuration:**\nYou can customize terminal emulator preferences through the `[terminal]` section in `terminal-control.toml`:\n\n```toml\n[terminal]\n# Terminal dimensions and performance settings\nwidth = 120\nheight = 30\nclose_timeout = 5.0\nprocess_check_timeout = 1.0\npolling_interval = 0.05\nsend_input_delay = 0.1\n\n# Custom terminal emulator configuration (ordered by preference)\nemulators = [\n { name = \"my-terminal\", command = [\"my-terminal\", \"--exec\"] },\n { name = \"gnome-terminal\", command = [\"gnome-terminal\", \"--\"] },\n { name = \"konsole\", command = [\"konsole\", \"-e\"] },\n # ... other terminals\n]\n```\n\n#### **Multi-Instance Port Management**\n\n**Automatic Port Selection:**\nWhen multiple server instances run simultaneously, ports are automatically selected to avoid conflicts:\n\n```bash\n# Automatic port selection (default: enabled)\nexport TERMINAL_CONTROL_WEB_AUTO_PORT=true\n\n# How it works:\n# - Base port: 9000-9999 range\n# - Selection: hash(working_dir + process_id) % 1000 + 9000\n# - Consistent: Same directory always gets same port\n```\n\n### **TOML Configuration Example**\n\nCreate `terminal-control.toml` in your project root:\n\n```toml\n[web]\nenabled = false # Use terminal windows instead of web interface\nhost = \"0.0.0.0\"\nport = 8080\nauto_port = true # Automatic unique port selection\n\n[security]\nlevel = \"high\"\nmax_calls_per_minute = 60\nmax_sessions = 50\n\n[session]\ndefault_shell = \"bash\"\ntimeout = 30\n\n[terminal]\nwidth = 120\nheight = 30\nclose_timeout = 5.0\nprocess_check_timeout = 1.0\npolling_interval = 0.05\nsend_input_delay = 0.1\n\n[logging]\nlevel = \"INFO\"\n```\n\n## \ud83d\udee0\ufe0f MCP Tools (5 Tools)\n\nThe server provides 5 MCP tools for complete terminal session lifecycle management:\n\n### **Session Management**\n\n#### **`list_terminal_sessions`**\nList all active terminal sessions with status information.\n\n**Returns:**\n- Session IDs, commands, and states\n- Creation timestamps and last activity\n- Total session count (max 50)\n- Web interface URLs (if enabled)\n\n#### **`exit_terminal`**\nTerminate and cleanup a terminal session.\n\n**Parameters:**\n- `session_id`: Session ID to destroy\n\n**Features:**\n- **Bidirectional cleanup**: Sessions destroyed when agents call `exit_terminal` OR when users type `exit`\n- **Automatic monitoring**: Dead sessions detected and cleaned up every 5 seconds\n- **Terminal window management**: Closes associated terminal windows when web interface is disabled\n\n### **Content Retrieval**\n\n#### **`get_screen_content`**\nGet terminal content with precise control over output format.\n\n**Parameters:**\n- `session_id`: Session to get content from\n- `content_mode`: Content retrieval mode\n - `\"screen\"` (default): Current visible screen only\n - `\"since_input\"`: Output since last input command\n - `\"history\"`: Full terminal history\n - `\"tail\"`: Last N lines (requires `line_count`)\n- `line_count`: Number of lines for tail mode\n\n**Returns:**\n- Terminal content based on mode\n- Process running status\n- ISO timestamp for agent timing decisions\n\n### **Input Control**\n\n#### **`send_input`**\nSend input to terminal sessions.\n\n**Parameters:**\n- `session_id`: Target session\n- `input_text`: Text to send (supports escape sequences)\n\n**Important:** Newlines are NOT automatically added. For command execution, explicitly include `\\n` (e.g., `\"ls\\n\"`, `\"python\\n\"`).\n\n**Features:**\n- Raw input support with escape sequences\n- No automatic timeouts (agent-controlled timing)\n- Parallel user input possible via web interface\n\n### **Session Creation**\n\n#### **`open_terminal`**\nCreate new terminal sessions.\n\n**Parameters:**\n- `shell`: Shell to use (bash, zsh, fish, sh, etc.)\n- `working_directory`: Starting directory (optional)\n- `environment`: Environment variables (optional)\n\n**Returns:**\n- Unique session ID\n- Initial screen content\n- Web interface URL (if enabled)\n- Process startup status\n\n**Features:**\n- Universal shell support\n- Environment and directory control\n- Immediate screen content availability\n\n## \ud83d\udcda Usage Examples\n\n### **Basic Commands**\n\n```bash\n# Natural language requests to Claude:\n\"Start a Python session and show me what's on screen\"\n\"List all my active terminal sessions\"\n\"What's currently showing in the terminal?\"\n\"Type 'print(2+2)' in the Python session\"\n\"Close that debugging session\"\n```\n\n### **Interactive Programs**\n\n```bash\n# Complex interactive workflows:\n\"Start a Python REPL and help me debug this script\"\n\"SSH into the server and check disk space\"\n\"Connect to MySQL and show me the database tables\"\n\"Run the debugger and set breakpoints in the main function\"\n\"Start a docker container and explore the filesystem\"\n```\n\n### **Debugging Workflow**\n\nUsing the included `examples/example_debug.py`:\n\n```bash\n# 1. Start debugging session\n\"Debug the file examples/example_debug.py and show me the code\"\n\n# 2. Explore and set breakpoints\n\"Show me the source code around the current line\"\n\"Set a breakpoint where the bug occurs\"\n\n# 3. Investigate the problem\n\"Step through the buggy loop and show variable values\"\n\"What variables do we have here? Show their values\"\n\n# 4. Clean up\n\"We found the bug! Clean up this debugging session\"\n```\n\n**Pro tip:** If you set `web_enabled=true` in your configuration, you can also access the debugging session directly in your browser for real-time interaction.\n\n### **Web Interface Usage**\n\nWhen web interface is enabled:\n1. Agent creates session: `\"Starting debugger session...\"`\n2. Agent provides URL: `\"You can also access it at http://localhost:9123/session/abc123\"`\n3. User opens URL in browser for direct interaction\n4. Both agent and user can send commands simultaneously\n\n## \ud83c\udf10 Web Interface\n\n### **Real-Time Terminal Access**\n- **Live output**: See exactly what agents see in real-time\n- **Manual input**: Send commands directly without agent awareness\n- **WebSocket updates**: Automatic screen refreshes\n- **Session overview**: View all active sessions at once\n\n### **Session URLs**\n- **Individual sessions**: `http://localhost:8080/session/{session_id}`\n- **Session overview**: `http://localhost:8080/`\n- **Direct browser access**: No additional software required\n- **Transparent to agents**: Manual interaction doesn't interfere with agent control\n\n## \ud83d\udd12 Security\n\n### **Defense-in-Depth Approach**\n- **Command filtering**: Blocks dangerous operations (`rm -rf /`, `sudo`, `dd`, etc.)\n- **Path restrictions**: Commands run in specified directories only\n- **Input validation**: Multi-layer validation for all inputs\n- **Environment protection**: Protects critical variables (`PATH`, `LD_PRELOAD`, etc.)\n- **Rate limiting**: Prevents abuse with configurable limits\n- **Audit logging**: Complete security event tracking\n\n### **Agent-Controlled Philosophy**\n- **Maximum flexibility**: Security balanced with functionality\n- **User responsibility**: Security managed by user and agent choices\n- **Transparent operation**: All commands create persistent sessions\n- **No hidden automation**: Agents control all timing and interaction\n\n## \ud83d\udcc1 Project Structure\n\n```\nterminal-control-mcp/\n\u251c\u2500\u2500 src/terminal_control_mcp/\n\u2502 \u251c\u2500\u2500 main.py # FastMCP server with 5 MCP tools\n\u2502 \u251c\u2500\u2500 session_manager.py # Session lifecycle management\n\u2502 \u251c\u2500\u2500 interactive_session.py # Tmux/libtmux process control\n\u2502 \u251c\u2500\u2500 terminal_utils.py # Terminal window management\n\u2502 \u251c\u2500\u2500 web_server.py # FastAPI web interface\n\u2502 \u251c\u2500\u2500 security.py # Multi-layer security validation\n\u2502 \u251c\u2500\u2500 config.py # TOML configuration handling\n\u2502 \u251c\u2500\u2500 models.py # Pydantic request/response models\n\u2502 \u251c\u2500\u2500 templates/ # Web interface templates\n\u2502 \u2502 \u251c\u2500\u2500 index.html # Session overview page\n\u2502 \u2502 \u2514\u2500\u2500 session.html # Individual session interface\n\u2502 \u2514\u2500\u2500 static/ # Web interface assets\n\u2502 \u251c\u2500\u2500 css/ # Stylesheets\n\u2502 \u2514\u2500\u2500 js/ # JavaScript modules\n\u251c\u2500\u2500 tests/ # Comprehensive test suite\n\u2502 \u251c\u2500\u2500 test_security_manager.py\n\u2502 \u251c\u2500\u2500 test_execute_command.py\n\u2502 \u251c\u2500\u2500 test_session_lifecycle.py\n\u2502 \u2514\u2500\u2500 test_mcp_integration.py\n\u251c\u2500\u2500 examples/\n\u2502 \u2514\u2500\u2500 example_debug.py # Sample debugging script\n\u251c\u2500\u2500 logs/interactions/ # Session interaction logs\n\u251c\u2500\u2500 CLAUDE.md # Development guidance\n\u251c\u2500\u2500 terminal-control.toml # TOML configuration\n\u2514\u2500\u2500 pyproject.toml # Python packaging configuration\n```\n\n## \ud83e\uddea Development\n\n### **Testing**\n\n```bash\n# Run all tests\npytest tests/\n\n# Run specific test categories\npytest -m unit # Unit tests\npytest -m integration # Integration tests\npytest -m security # Security tests\n\n# Run with coverage\npytest --cov=src/terminal_control_mcp tests/\n```\n\n### **Code Quality**\n\n```bash\n# Type checking\nmypy src/ --ignore-missing-imports\n\n# Linting and formatting\nruff check src/ tests/\nblack src/ tests/\n\n# Check for dead code\nvulture src/\n```\n\n### **Development Installation**\n\n```bash\n# Install with development dependencies\npip install -e \".[dev]\"\n\n# Test basic functionality\npython tests/conftest.py\n```\n\n## \ud83d\ude80 Development Status\n\n- \u2705 **Tmux Integration**: Complete libtmux-based terminal control\n- \u2705 **Web Interface**: Real-time xterm.js with WebSocket synchronization\n- \u2705 **Agent Control**: 5 MCP tools for complete session management\n- \u2705 **Security Layer**: Multi-layer validation and audit logging\n- \u2705 **TOML Configuration**: Structured configuration with environment overrides\n- \u2705 **Type Safety**: Full Pydantic models and mypy coverage\n- \u2705 **Test Coverage**: Comprehensive test suite with multiple categories\n- \u2705 **Production Ready**: Reliable session management with proper cleanup\n\n## \ud83d\udcc4 License\n\nMIT License - see LICENSE file for details.\n\n## \ud83e\udd1d Contributing\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Make your changes and add tests\n4. Ensure all tests pass: \n ```bash\n ruff check src/ tests/ && mypy src/ --ignore-missing-imports && pytest tests/\n ```\n5. Commit your changes (`git commit -m 'Add amazing feature'`)\n6. Push to the branch (`git push origin feature/amazing-feature`)\n7. Open a Pull Request\n\n## \ud83d\ude4f Acknowledgments\n\n- Built on the [Model Context Protocol (MCP)](https://github.com/anthropics/mcp) by Anthropic\n- Uses [libtmux](https://libtmux.git-pull.com/) for reliable terminal multiplexing\n- Powered by [FastAPI](https://fastapi.tiangolo.com/) and [xterm.js](https://xtermjs.org/) for the web interface\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Terminal Control MCP Server",
"version": "1.0.0",
"project_urls": {
"Documentation": "https://github.com/wehnsdaefflae/terminal-control-mcp/blob/main/README.md",
"Homepage": "https://github.com/wehnsdaefflae/terminal-control-mcp",
"Issues": "https://github.com/wehnsdaefflae/terminal-control-mcp/issues",
"Repository": "https://github.com/wehnsdaefflae/terminal-control-mcp"
},
"split_keywords": [
"mcp",
" terminal",
" control",
" debugging",
" ssh",
" database"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "0834cbdd0066bde47b7e50a7477fa5bcdbed2a3cf76d300ae27f405d55a32fb8",
"md5": "e1a853622ca5084f5de66b91df7bfd3e",
"sha256": "842336f5b06b2fa670098ec444731d8374fb6b41c19a35a4a665e18255fc7c50"
},
"downloads": -1,
"filename": "terminal_control_mcp-1.0.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "e1a853622ca5084f5de66b91df7bfd3e",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.11",
"size": 49641,
"upload_time": "2025-07-29T19:17:52",
"upload_time_iso_8601": "2025-07-29T19:17:52.406958Z",
"url": "https://files.pythonhosted.org/packages/08/34/cbdd0066bde47b7e50a7477fa5bcdbed2a3cf76d300ae27f405d55a32fb8/terminal_control_mcp-1.0.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "233293a755479739f98a4175a5dd55d59b44c460585d57232b57dd05e60b844c",
"md5": "a1f6cadfd5c3f5da45a710164b463465",
"sha256": "5f4e0f98a9fd82d9cee806eef8d0dd30433cf48255e14da350b417ceaaeca330"
},
"downloads": -1,
"filename": "terminal_control_mcp-1.0.0.tar.gz",
"has_sig": false,
"md5_digest": "a1f6cadfd5c3f5da45a710164b463465",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.11",
"size": 68917,
"upload_time": "2025-07-29T19:17:55",
"upload_time_iso_8601": "2025-07-29T19:17:55.001641Z",
"url": "https://files.pythonhosted.org/packages/23/32/93a755479739f98a4175a5dd55d59b44c460585d57232b57dd05e60b844c/terminal_control_mcp-1.0.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-07-29 19:17:55",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "wehnsdaefflae",
"github_project": "terminal-control-mcp",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "terminal-control-mcp"
}