Skip to main content

Terminal Control MCP Server

Project description

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:

# 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

From PyPI (Recommended)

# Install directly from PyPI
pip install terminal-control-mcp

From Source

# Clone the repository
git clone https://github.com/your-username/terminal-control-mcp.git
cd terminal-control-mcp

# Create virtual environment (choose one)
python -m venv .venv          # Using standard venv
# OR
uv venv                       # Using uv (faster)

# Activate virtual environment
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:

    # From PyPI (recommended)
    pip install terminal-control-mcp
    
    # OR from source (if you cloned the repository)
    pip install .
    
  2. Add the MCP server:

    # 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:

    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:

{
  "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

# 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

# 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

# Default shell and timeout
export TERMINAL_CONTROL_DEFAULT_SHELL=bash
export TERMINAL_CONTROL_SESSION_TIMEOUT=30

Terminal Configuration

# 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:

[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:

# 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:

[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

# 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

# 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:

# 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

# 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

# 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

# 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:
    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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

terminal_control_mcp-1.0.1.tar.gz (69.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

terminal_control_mcp-1.0.1-py3-none-any.whl (49.8 kB view details)

Uploaded Python 3

File details

Details for the file terminal_control_mcp-1.0.1.tar.gz.

File metadata

  • Download URL: terminal_control_mcp-1.0.1.tar.gz
  • Upload date:
  • Size: 69.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for terminal_control_mcp-1.0.1.tar.gz
Algorithm Hash digest
SHA256 8254165779459016f8acf4d541760b91a2d03efeee22d8e9a778c4d8746d02af
MD5 55e9c25716da046851bbf45137c361c7
BLAKE2b-256 2b2556f3878ea7a785ffc185018f096454c735b1c7d10a7103926b3f1483613d

See more details on using hashes here.

File details

Details for the file terminal_control_mcp-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for terminal_control_mcp-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 0e827df9238fd74cb503b8b16e2d624ca998bbb2b5b2ceb446427045bf35d7d7
MD5 6b506c4d1db671a679cd01106b540d41
BLAKE2b-256 72cf109ef8e91acd3c12b8ad4b10c352035760bb31354e1b7b36342df8606670

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page