brianczapiga/mcp-terminal
If you are the rightful owner of mcp-terminal and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.
A Python MCP server for integrating AI tools with macOS Terminal sessions.
Terminal MCP Server
A Python MCP (Model Context Protocol) server that allows AI tools (like Goose or Void) to collaborate with macOS Terminal sessions. The server provides tools to list, monitor, and control Terminal windows and tabs through AppleScript integration.
Features
- Session Management: List all Terminal windows and tabs with detailed information
- Content Retrieval: Get current screen contents with configurable line limits
- Input Control: Send commands or keystrokes to active sessions
- Multiple Modes: Support for focus, recent-output, and manual modes
- Buffer Management: Rolling buffer for scroll-back functionality
- Dual Terminal Support: Primary support for Apple Terminal with iTerm2 fallback
- Production Ready: Error handling, logging, and graceful degradation
Installation
Prerequisites
- macOS (required for AppleScript integration)
- Python 3.10 or higher
- Terminal.app or iTerm2 installed
Setup
-
Clone or download the project:
git clone https://github.com/brianczapiga/mcp-terminal.git cd mcp-terminal -
Set up virtual environment and install dependencies:
# Option 1: Using Makefile (recommended) make setup # Option 2: Manual setup python -m venv venv source venv/bin/activate pip install -r requirements.txt -
For development setup (optional):
make dev-setup -
Grant necessary permissions:
- Go to System Preferences → Security & Privacy → Privacy
- Add Terminal.app (or iTerm2) to Accessibility permissions
- This allows the server to control your terminal applications
Usage
Starting the Server
The MCP server uses stdio transport for secure communication with AI tools:
# Option 1: Using Makefile (recommended)
make run
# Option 2: Manual execution
source venv/bin/activate
python terminal_mcp_server.py
The server will automatically detect whether you're using Apple Terminal or iTerm2.
Available MCP Capabilities
The server provides the standard MCP discovery endpoints:
Tools - Interactive terminal operations
list_sessions()- List all Terminal sessions (windows/tabs)set_active_session(session_id)- Select active sessionget_screen(lines=100, mode="focus")- Get screen contentssend_input(text, execute=True, session_id=None)- Send commands/keystrokesscroll_back(pages=1, session_id=None)- Access older content
Resources - Terminal session content
- URI Format:
terminal://session/{session_id} - MIME Type:
text/plain - Content: Current terminal session output
- Metadata: Session information (window_id, tab_id, tty_device, etc.)
Prompts - AI assistance templates
terminal_session_summary- Generate session summariesterminal_command_suggestion- Suggest next commandsterminal_troubleshooting- Analyze session for issues
Tool Details
list_sessions()
Lists all Terminal sessions (windows/tabs) with their information.
Returns:
session_id: Unique identifier for the sessionwindow_id: Terminal window IDtab_id: Tab ID within the windowname: Session name/titletty_device: Associated TTY device (if available)is_active: Whether the session is currently activelast_activity: Timestamp of last activity
set_active_session(session_id)
Manually select which session the AI should watch/control.
Parameters:
session_id: The session ID to set as active
get_screen(lines=100, mode="focus")
Get the current screen contents of terminal sessions.
Parameters:
lines: Number of lines to retrieve (default: 100)mode: Session selection modefocus(default): Use the last focused sessionrecent-output: Find session with most recent TTY activitymanual: Use currently set active session
send_input(text, execute=True, session_id=None)
Send input (commands or keystrokes) to the terminal.
Parameters:
text: Text to send to the terminalexecute: Whether to execute the command (press Enter) (default: true)session_id: Session ID to send to (uses active if not specified)
scroll_back(pages=1, session_id=None)
Scroll back to get older content from the terminal buffer.
Parameters:
pages: Number of pages to scroll back (default: 1)session_id: Session ID to scroll back (uses active if not specified)
Connecting to AI Tools
Goose Integration
-
Add the server to your Goose configuration (see
examples/goose_config.json):{ "tools": [ { "name": "terminal-mcp", "type": "mcp", "config": { "command": "python", "args": ["terminal_mcp_server.py"], "cwd": "/path/to/mcp-terminal", "env": { "PYTHONPATH": "/path/to/mcp-terminal" } } } ] } -
Restart Goose to load the new tool configuration.
Void Integration
-
Configure Void to use the MCP server (see
examples/void_config.yaml):tools: - name: terminal-mcp type: mcp config: command: python args: [terminal_mcp_server.py] cwd: /path/to/mcp-terminal env: PYTHONPATH: /path/to/mcp-terminal -
Restart Void to apply the configuration.
Other MCP-Compatible Tools
The server follows the MCP specification and should work with any MCP-compatible AI tool. The server uses stdio transport for secure communication, ensuring that only the parent AI tool process can interact with the terminal.
Example Usage Scenarios
1. Monitoring Active Development
# List all sessions
sessions = await list_sessions()
# Set focus to the most active session
await set_active_session(sessions[0]["session_id"])
# Get current screen content
content = await get_screen(lines=50, mode="focus")
# Send a command
await send_input("ls -la", execute=True)
2. Multi-Session Management
# Get content from all visible sessions
all_content = await get_all_terminal_info()
# Find session with recent output
recent_content = await get_screen(mode="recent-output")
3. Command Review Mode
# Type a command without executing
await send_input("rm -rf /important/directory", execute=False)
# Let user review, then execute
await send_input("", execute=True) # Just press Enter
Architecture
TerminalManager Class
The core class that abstracts terminal operations:
- Session Detection: Automatically detects Apple Terminal vs iTerm2
- AppleScript Integration: Uses
osascriptfor terminal control - Buffer Management: Maintains rolling buffers for scroll-back
- Error Handling: Graceful degradation when operations fail
MCP Server
Built with FastMCP for easy integration:
- Async Operations: All tools are async for better performance
- Type Safety: Uses Pydantic models for request/response validation
- Error Reporting: Comprehensive error messages and logging
Troubleshooting
Common Issues
-
Permission Denied Errors:
- Ensure Terminal.app/iTerm2 has Accessibility permissions
- Check System Preferences → Security & Privacy → Privacy → Accessibility
-
No Sessions Found:
- Make sure Terminal.app or iTerm2 is running
- Check that you have at least one terminal window open
-
AppleScript Timeout:
- The server has a 10-second timeout for AppleScript operations
- Complex terminal operations may take longer
-
iTerm2 Not Detected:
- Ensure iTerm2 is properly installed and running
- The server falls back to Apple Terminal if iTerm2 is not available
Debug Mode
Enable debug logging by modifying the logging level in the script:
logging.basicConfig(level=logging.DEBUG)
Health Check
The server provides a health check endpoint:
curl http://localhost:8000/health
Security Considerations
Input Injection Safety
⚠️ IMPORTANT: This server can send arbitrary commands to your terminal, which could be dangerous if the AI tool is compromised or makes poor decisions.
Security Features:
- Readonly Mode: Set
MCP_TERMINAL_READONLY=1to disable all input injection - stdio transport: Only the parent AI tool process can communicate with the server
- AppleScript permissions: Requires user permission and Accessibility access
- No network exposure: All communication is through stdin/stdout
- Terminal control limited: Only to the user's own terminal sessions
Recommended Security Practices
-
Use Readonly Mode by Default:
export MCP_TERMINAL_READONLY=1 python terminal_mcp_server.py -
Review Commands Before Execution:
- Don't blanket trust AI tools to run commands
- Review suggested commands before approval
- Use the AI tool's built-in approval mechanisms
-
Enable Input Injection Only When Needed:
# Only enable when you need input injection export MCP_TERMINAL_READONLY=0 python terminal_mcp_server.py -
Monitor Terminal Activity:
- Keep an eye on your terminal when input injection is enabled
- Be aware of what commands are being executed
Security Warnings
- Commands like
rm -rf /,sudo, or other destructive operations are possible - Malicious AI tools or compromised clients could execute dangerous commands
- Always review and approve commands before execution
- Consider using readonly mode for production or sensitive environments
Development
Adding New Tools
- Define the tool function with
@server.tool()decorator - Create Pydantic models for request/response
- Add error handling and logging
- Update documentation
Testing
# Run all tests
make test
# Run specific test file
pytest tests/test_terminal_mcp_server.py
# Run with coverage
pytest --cov=terminal_mcp_server tests/
# Run only unit tests (skip integration tests)
pytest -m "not slow" tests/
Development
This project was developed using Cursor, an AI-powered code editor, demonstrating modern AI-assisted development workflows. The codebase was primarily "vibe coded" - a collaborative process between human developer and AI assistant.
The project follows standard Python development practices and is fully maintainable by human developers.
Code Quality
# Format code
make format
# Run linting
make lint
# Run all checks (lint, format, test)
make check
# Clean up generated files
make clean
Adding New Tools
- Define the tool function with
@server.tool()decorator - Create Pydantic models for request/response
- Add error handling and logging
- Update documentation
License
This project is licensed under the MIT License - see the file for details.
Contributing
We welcome contributions! Please see our for details on how to:
- Report bugs
- Suggest enhancements
- Submit pull requests
- Follow our coding standards
Code of Conduct
This project adheres to the Contributor Covenant Code of Conduct. Please read for details.
Support
For issues and questions:
- Check the troubleshooting section
- Review the logs for error messages
- Open an issue on the GitHub repository
- Ensure you're running on macOS with proper permissions
Changelog
See for a list of changes and version history.