A secure, context-aware Model Context Protocol (MCP) server for shell command execution with comprehensive logging and AI optimizations.
MCP-Exec is a TypeScript-based MCP server that provides intelligent shell command execution capabilities for AI assistants like Claude Desktop, Claude Code, and Augment Code. It combines multi-layered security, context preservation, RFC 5424 compliant logging, and enhanced output formatting to create a powerful tool for AI-assisted development and system administration.
The server implements the Model Context Protocol specification with STDIO transport, providing comprehensive tools for secure shell interaction while maintaining session state and providing AI-optimized output formatting with real-time logging capabilities.
- Long-running processes - Start and maintain interactive shells, REPLs, and other persistent processes
- Session management - Support for up to 10 concurrent interactive sessions (configurable)
- Bidirectional communication - Send commands and receive output from active sessions
- Session persistence - Sessions remain active until explicitly terminated or timeout
- Command history tracking - All session interactions are logged and tracked
- Configurable Security Levels: Strict, moderate, and permissive modes
- Command Validation: Pattern-based dangerous command detection and blocking
- Interactive Confirmation: Approval prompts for high-risk operations
- Resource Limits: Memory, file size, and process restrictions
- Directory Controls: Configurable allowed/blocked directory access
- Sandboxing: Isolated execution environments with restricted permissions
- Industry Standard: Logging severity level based on RFC 5424
- MCP Logging Capability: Real-time log streaming to MCP clients via
notifications/message - Dynamic Log Control: Clients can set minimum log level using
logging/setLevel - Comprehensive Coverage: Detailed logging throughout all system components
- Rate Limiting: Configurable rate limiting to prevent message flooding
- Context-Rich: Detailed context information for enhanced debugging
- Session Management: Maintains state across multiple AI interactions
- Working Directory Tracking: Preserves directory changes between commands
- Environment Variables: Persistent environment state management
- Command History: Detailed history with relationships and AI context
- File System Monitoring: Tracks changes and side effects
- Rich Markdown Display: Beautiful formatting optimized for Claude Desktop
- Structured Data Parsing: Automatic detection of JSON, YAML, CSV formats
- Visual Indicators: Icons, emojis, and color coding for quick recognition
- AI-Optimized Summaries: Intelligent output summarization and suggestions
- Error Categorization: Clear error messages with actionable suggestions
- Windows, macOS, Linux: Full cross-platform compatibility
- Shell Detection: Automatic platform-specific shell selection
- Path Handling: Proper path resolution across operating systems
- Immutable Logging: Cryptographically signed audit trails
- Real-time Monitoring: Live monitoring with configurable alerts
- Multiple Export Formats: JSON, CSV, XML export capabilities
- Compliance Reporting: Detailed audit reports for security compliance
- Privacy Controls: Configurable sensitive data redaction
# Clone the repository
git clone https://github.com/bensons/mcp-exec.git
cd mcp-exec
# Install dependencies
npm install
# Build the project
npm run buildThe automated setup script will configure Claude Desktop for you:
npm run setup-claudeThis script:
- Detects your operating system (macOS, Linux, Windows)
- Locates the Claude Desktop configuration file
- Adds the MCP-Exec server configuration
- Sets up default security settings
If you prefer manual setup, add this to your Claude Desktop configuration:
{
"mcpServers": {
"mcp-exec": {
"command": "node",
"args": ["/path/to/mcp-exec/dist/index.js"]
}
}
}The server uses sensible defaults and can be customized with environment variables if needed. For custom configuration, add an env section:
{
"mcpServers": {
"mcp-exec": {
"command": "node",
"args": ["/path/to/mcp-exec/dist/index.js"],
"env": {
"MCP_EXEC_SECURITY_LEVEL": "strict",
"MCP_EXEC_CONFIRM_DANGEROUS": "true",
"MCP_EXEC_MCP_LOG_LEVEL": "warning"
}
}
}
}- Restart Claude Desktop to load the MCP server
- Test the integration by asking Claude to execute a simple command
- Explore the tools - try asking Claude to show command history or change directories
In the Claude desktop app, it's possible to configure individual tools to "Allow unsupervised" execution or to "Always ask permission" for tool use.
- Click the Connect apps button on the "New chat" screen
- Click the "..." button next to the MCP-Exec tool
- Choose Tools and settings
- Set each tool based on your personal comfort level
Caution
#YOLO mode may bring about Skynet. I, for one, embrace our AI overlords.
The server provides comprehensive MCP tools organized into categories:
execute_command- Execute one-shot shell commands with full security validation and enhanced output formattingconfirm_command- Interactive confirmation system for dangerous operations
start_interactive_session- Start new interactive shell sessions for persistent processesstart_terminal_session- Start PTY-based terminal sessions with browser viewing capabilitysend_to_session- Send commands to existing interactive sessionsread_session_output- Read buffered output from interactive sessionslist_sessions- List all active sessions with status informationkill_session- Terminate specific sessionsget_session_status- Get detailed status of a specific session
toggle_terminal_viewer- Enable/disable browser-based terminal viewingget_terminal_viewer_status- Check terminal viewer configuration and status
get_context- Retrieve current execution context and environment detailsget_history- View formatted command execution history with AI contextset_working_directory- Change and persist working directory across sessions
update_security_config- Modify security settings and policies (legacy)get_security_status- View current security configuration and restrictionsget_pending_confirmations- View pending dangerous command confirmationsmanage_blocked_commands- Add, remove, or list blocked commandsmanage_allowed_directories- Add, remove, or list allowed directoriesupdate_resource_limits- Modify memory, file size, and process limits
get_intent_summary- Analyze command patterns and user intentsuggest_next_commands- AI-powered suggestions for follow-up commands
generate_audit_report- Create detailed audit reports with filteringexport_logs- Export audit logs in multiple formats (JSON, CSV, XML)get_alerts- View security alerts and operational warningsacknowledge_alert- Acknowledge and dismiss security alertsget_audit_config- View current audit configurationupdate_audit_config- Modify audit settings and log levels (legacy)update_mcp_logging- Configure MCP client notification settingsupdate_audit_logging- Modify audit logging and monitoring settings
get_configuration- Retrieve current configuration for any section or all sectionsupdate_configuration- Update configuration settings for any sectionreset_configuration- Reset configuration to default valuesget_configuration_history- View history of configuration changesrollback_configuration- Rollback to a previous configuration state
update_session_limits- Adjust session limits and timeoutsupdate_terminal_viewer- Configure terminal viewer service settingsupdate_output_formatting- Modify output processing and formattingupdate_display_options- Adjust display and presentation settingsupdate_context_config- Configure context preservation settingsupdate_lifecycle_config- Modify server lifecycle behavior
Choose the appropriate security level for your use case:
- Use Case: Production environments, shared systems
- Behavior: Blocks most dangerous operations, requires explicit approval
- Commands Blocked: File deletions, system modifications, network operations
- Confirmation: Required for all medium and high-risk commands
- Use Case: Development environments, personal systems
- Behavior: Balanced security with confirmation prompts
- Commands Blocked: Only highly dangerous operations (rm -rf /, format, etc.)
- Confirmation: Required for high-risk commands only
- Use Case: Advanced users, isolated environments
- Behavior: Minimal restrictions, maximum flexibility
- Commands Blocked: Only system-destroying operations
- Confirmation: Optional, can be disabled
The server supports comprehensive configuration through environment variables with the MCP_EXEC_ prefix:
MCP_EXEC_SECURITY_LEVEL=permissive # strict|moderate|permissive
MCP_EXEC_CONFIRM_DANGEROUS=false # Require confirmation for dangerous commands
MCP_EXEC_ALLOWED_DIRECTORIES="cwd,/tmp" # Comma-separated allowed directories
MCP_EXEC_BLOCKED_COMMANDS="rm -rf /,format" # Comma-separated blocked commands
MCP_EXEC_TIMEOUT=300000 # Command timeout in milliseconds
MCP_EXEC_MAX_MEMORY=1024 # Maximum memory usage in MB
MCP_EXEC_MAX_FILE_SIZE=100 # Maximum file size in MB
MCP_EXEC_MAX_PROCESSES=10 # Maximum number of processes
MCP_EXEC_SANDBOXING_ENABLED=false # Enable sandboxing
MCP_EXEC_NETWORK_ACCESS=true # Allow network access
MCP_EXEC_FILESYSTEM_ACCESS=full # read-only|restricted|full# Audit Logging
MCP_EXEC_AUDIT_ENABLED=true # Enable audit logging
MCP_EXEC_AUDIT_LOG_LEVEL=debug # emergency|alert|critical|error|warning|notice|info|debug
MCP_EXEC_AUDIT_RETENTION=30 # Days to retain logs
# MCP Client Logging
MCP_EXEC_MCP_LOGGING_ENABLED=true # Enable MCP client notifications
MCP_EXEC_MCP_LOG_LEVEL=info # Minimum level for notifications
MCP_EXEC_MCP_RATE_LIMIT=60 # Max messages per minute
MCP_EXEC_MCP_QUEUE_SIZE=100 # Max queued messages
MCP_EXEC_MCP_INCLUDE_CONTEXT=true # Include context data# Interactive Sessions
MCP_EXEC_MAX_SESSIONS=10 # Maximum concurrent sessions
MCP_EXEC_SESSION_TIMEOUT=1800000 # Session timeout (30 minutes)
MCP_EXEC_SESSION_BUFFER_SIZE=1000 # Session output buffer size
# Server Lifecycle
MCP_EXEC_INACTIVITY_TIMEOUT=0 # Inactivity timeout in ms (0 = disabled, recommended for MCP)
MCP_EXEC_SHUTDOWN_TIMEOUT=5000 # Graceful shutdown timeout (5 seconds)
MCP_EXEC_ENABLE_HEARTBEAT=true # Enable connection monitoring
# Output Formatting
MCP_EXEC_FORMAT_STRUCTURED=true # Format output in structured format
MCP_EXEC_STRIP_ANSI=true # Strip ANSI escape codes
MCP_EXEC_SUMMARIZE_VERBOSE=true # Summarize verbose output
MCP_EXEC_ENABLE_AI_OPTIMIZATIONS=true # Enable AI-powered optimizations
MCP_EXEC_MAX_OUTPUT_LENGTH=10000 # Maximum output length in bytes
MCP_EXEC_USE_MARKDOWN=true # Use Markdown formattingThe server provides comprehensive runtime configuration management through MCP tools, allowing you to modify settings without restarting the server. This system supports configuration history tracking, automatic component reinitialization, and rollback capabilities.
The dynamic configuration system supports the following configuration sections:
security- Security settings, blocked commands, resource limitslogging- Audit and MCP logging configurationsessions- Interactive session managementoutput- Output formatting and processingdisplay- Display and presentation optionscontext- Context preservation and historylifecycle- Server lifecycle managementterminalViewer- Terminal viewer service configuration
get_configuration- Retrieve current configuration for any sectionupdate_configuration- Update configuration settings for any sectionreset_configuration- Reset configuration to default valuesget_configuration_history- View history of configuration changesrollback_configuration- Rollback to a previous configuration state
manage_blocked_commands- Add, remove, or list blocked commandsmanage_allowed_directories- Add, remove, or list allowed directoriesupdate_resource_limits- Modify memory, file size, and process limits
update_mcp_logging- Configure MCP client notification settingsupdate_audit_logging- Modify audit logging and monitoring settings
update_session_limits- Adjust session limits and timeoutsupdate_terminal_viewer- Configure terminal viewer service settings
update_output_formatting- Modify output processing and formattingupdate_display_options- Adjust display and presentation settings
update_context_config- Configure context preservation settingsupdate_lifecycle_config- Modify server lifecycle behavior
// Change security level to strict
{
"tool": "update_configuration",
"arguments": {
"section": "security",
"settings": {
"level": "strict",
"confirmDangerous": true
}
}
}
// Add blocked commands
{
"tool": "manage_blocked_commands",
"arguments": {
"action": "add",
"commands": ["rm -rf /", "format", "dd if=/dev/zero"]
}
}
// Update resource limits
{
"tool": "update_resource_limits",
"arguments": {
"maxMemoryUsage": 2048,
"maxFileSize": 200,
"maxProcesses": 20
}
}// Update MCP logging settings
{
"tool": "update_mcp_logging",
"arguments": {
"minLevel": "debug",
"rateLimitPerMinute": 120,
"maxQueueSize": 200,
"includeContext": true
}
}
// Update audit logging
{
"tool": "update_audit_logging",
"arguments": {
"retention": 60,
"monitoringEnabled": true,
"desktopNotifications": true,
"alertRetention": 14,
"maxAlertsPerHour": 200
}
}// Update session limits
{
"tool": "update_session_limits",
"arguments": {
"maxInteractiveSessions": 20,
"sessionTimeout": 3600000,
"outputBufferSize": 2000
}
}
// Configure terminal viewer
{
"tool": "update_terminal_viewer",
"arguments": {
"port": 4000,
"host": "0.0.0.0",
"enableAuth": true,
"authToken": "your-secure-token",
"maxSessions": 20,
"sessionTimeout": 3600000,
"bufferSize": 20000
}
}// Update output formatting
{
"tool": "update_output_formatting",
"arguments": {
"formatStructured": false,
"stripAnsi": false,
"enableAiOptimizations": false,
"maxOutputLength": 20000,
"summarizeVerbose": false
}
}
// Update display options
{
"tool": "update_display_options",
"arguments": {
"showCommandHeader": false,
"showExecutionTime": false,
"showExitCode": false,
"formatCodeBlocks": false,
"includeMetadata": false,
"includeSuggestions": false,
"useMarkdown": false,
"colorizeOutput": true
}
}// Update context configuration
{
"tool": "update_context_config",
"arguments": {
"preserveWorkingDirectory": false,
"sessionPersistence": false,
"maxHistorySize": 2000
}
}
// Update lifecycle settings
{
"tool": "update_lifecycle_config",
"arguments": {
"inactivityTimeout": 600000,
"gracefulShutdownTimeout": 10000,
"enableHeartbeat": false
}
}The server maintains a comprehensive history of all configuration changes with detailed tracking:
interface ConfigurationHistoryEntry {
id: string;
timestamp: Date;
section: string;
changes: Record<string, any>;
previousValues: Record<string, any>;
user?: string;
}// View configuration history
{
"tool": "get_configuration_history",
"arguments": {
"limit": 10
}
}
// Rollback to a previous configuration
{
"tool": "rollback_configuration",
"arguments": {
"changeId": "uuid-of-previous-change"
}
}When configuration changes are made, the server automatically reinitializes affected components:
- Security Manager: Recreated when security settings change
- Context Manager: Recreated when context settings change
- MCP Logger: Recreated when MCP logging settings change
- Audit Logger: Recreated when audit settings change
- Display Formatter: Recreated when display settings change
- Terminal Session Manager: Recreated when session/terminal settings change
- Shell Executor: Recreated when output settings change
The new dynamic configuration system is backward compatible with existing tools:
update_security_config- Still supported (legacy)update_audit_config- Still supported (legacy)toggle_terminal_viewer- Still supported (legacy)
New tools provide more granular control and better integration with the configuration system.
You can also modify settings at runtime using the legacy update_security_config tool:
// Example: Update security level
{
"securityLevel": "strict",
"confirmDangerous": true,
"blockedCommands": ["rm -rf", "format", "dd if="],
"allowedDirectories": ["/home/user/safe", "/tmp"]
}The server implements a comprehensive logging system that complies with RFC 5424 (Syslog Protocol) severity levels and supports the MCP logging specification for real-time client notifications.
The logging system supports all 8 RFC 5424 severity levels:
| Level | Numeric | Name | Description | Use Cases |
|---|---|---|---|---|
| 0 | emergency |
System is unusable | Complete system failures | Critical security breaches, system corruption |
| 1 | alert |
Action must be taken immediately | Data corruption, security violations | Resource exhaustion, immediate intervention needed |
| 2 | critical |
Critical conditions | Component failures affecting functionality | Database failures, critical security validations |
| 3 | error |
Error conditions | Command execution failures, network errors | Configuration errors, execution failures |
| 4 | warning |
Warning conditions | Deprecated features, resource limits approaching | Recoverable errors, potential issues |
| 5 | notice |
Normal but significant condition | Configuration changes, session events | Security policy changes, important state changes |
| 6 | info |
Informational messages | Operation progress, status updates | Command execution success, general information |
| 7 | debug |
Debug-level messages | Function entry/exit, detailed execution flow | Variable values, detailed debugging information |
The server implements the MCP logging specification, enabling real-time log streaming to MCP clients:
- Client Notifications: Sends log messages to MCP clients via
notifications/message - Dynamic Log Levels: Clients can set minimum log level using
logging/setLevel - Rate Limiting: Configurable rate limiting to prevent message flooding (60 messages/minute default)
- Message Queuing: Queues messages when client is not connected (100 message buffer)
- Context Inclusion: Optional context data for enhanced debugging
Set the minimum log level for client notifications:
{
"method": "logging/setLevel",
"params": {
"level": "warning"
}
}Valid levels: emergency, alert, critical, error, warning, notice, info, debug
mcp-server: Server lifecycle and configuration eventssecurity-validator: Security policy enforcement and violationscommand-executor: Command execution, success, and failurescontext-manager: State management and session changesconnection-monitor: Client connection and transport events
Use dedicated session tools to start interactive processes:
{
"tool": "start_interactive_session",
"command": "python3",
"args": ["-i"],
"aiContext": "Starting Python REPL for data analysis"
}{
"tool": "start_terminal_session",
"command": "bash",
"enableViewer": true,
"terminalSize": {"cols": 120, "rows": 30}
}Both return a session ID for subsequent interactions.
Use the session ID to send commands to the interactive process:
{
"tool": "send_to_session",
"sessionId": "your-session-id-here",
"input": "print('Hello from Python!')"
}// List all active sessions
{ "tool": "list_sessions" }
// Read buffered output from a session
{ "tool": "read_session_output", "sessionId": "your-session-id" }
// Get detailed session status
{ "tool": "get_session_status", "sessionId": "your-session-id" }
// Terminate a session
{ "tool": "kill_session", "sessionId": "your-session-id" }Configure session limits and timeouts in your environment:
# Maximum concurrent sessions (default: 10)
MCP_EXEC_MAX_SESSIONS=10
# Session timeout in milliseconds (default: 30 minutes)
MCP_EXEC_SESSION_TIMEOUT=1800000
# Output buffer size per session (default: 1000 lines)
MCP_EXEC_SESSION_BUFFER_SIZE=1000npm run build # Compile TypeScript to JavaScript
npm run dev # Run in development mode with tsx
npm run watch # Auto-reload development server with nodemon
npm run start # Run the compiled server from dist/
npm run clean # Remove the dist directoryThe project includes comprehensive test suites organized in the tests/ directory:
# Core Tests
npm test # Build verification test
npm run test:server # MCP server functionality test
npm run test:lifecycle # Server lifecycle management test
# Feature Tests
npm run test:ssh # SSH command execution test
npm run test:all # Run all test suites
# Individual Tests
node tests/test-mcp-server.js # Basic server functionality
node tests/test-enhanced-output.js # Output formatting
node tests/test-ssh-comprehensive.js # SSH command testing
node tests/test-enhanced-logging.js # RFC 5424 logging and MCP notifications
node tests/test-execute-command-no-session.js # One-shot command execution
node tests/test-session-separation.js # Session functionality separation
node tests/test-mcp-annotations.js # MCP tool annotations structure compliance
node tests/test-dynamic-configuration.js # Dynamic configuration systemThe test-dynamic-configuration.js test suite provides comprehensive verification of:
- Configuration Retrieval - Getting current configuration
- Configuration Updates - Modifying various settings
- Security Management - Blocked commands and directories
- Resource Limits - Memory, file size, and process limits
- Logging Configuration - MCP and audit logging settings
- Session Management - Session limits and timeouts
- Output Formatting - Output processing settings
- Display Options - Presentation settings
- Context Management - Context preservation settings
- Lifecycle Configuration - Server lifecycle settings
- Configuration History - Change tracking and history
- List Operations - Listing blocked commands and directories
Test results typically show 12/15 tests passed (80% success rate) with all core functionality verified.
The codebase follows a modular architecture with clear separation of concerns:
src/
├── index.ts # MCP server entry point - handles all tool registrations and request routing
├── core/
│ ├── executor.ts # Command execution engine with cross-platform support
│ └── interactive-session-manager.ts # Interactive session management for long-running processes
├── security/
│ ├── manager.ts # Security validation, sandboxing, and policy enforcement
│ └── confirmation.ts # Interactive confirmation system for dangerous commands
├── context/
│ └── manager.ts # Session persistence and state management
├── audit/
│ ├── logger.ts # RFC 5424 compliant audit logging system
│ ├── mcp-logger.ts # MCP client notification logging
│ └── monitoring.ts # Real-time monitoring and alert management
├── terminal/
│ ├── session-manager.ts # PTY-based terminal session management
│ ├── viewer-service.ts # Browser-based terminal viewing
│ └── static/ # Static assets for terminal viewer
├── utils/
│ ├── output-processor.ts # AI-optimized output parsing and formatting
│ └── intent-tracker.ts # Command intent analysis and suggestions
└── types/
└── index.ts # Shared TypeScript type definitions with RFC 5424 log levels
-
MCP Tool Registration: All tools are registered in
index.tsusing the MCP SDK's server.tool() method. Each tool has schema validation using Zod. -
Security Layers: The security system uses a multi-tier approach:
- Pattern matching for dangerous commands in
security/manager.ts - Configurable security levels (strict/moderate/permissive)
- Optional confirmation system for high-risk operations
- Pattern matching for dangerous commands in
-
Interactive Sessions: The
core/interactive-session-manager.tsprovides:- Long-running process management with configurable limits
- Bidirectional communication with active sessions
- Output buffering and session lifecycle management
- Automatic cleanup of expired sessions
-
Context Preservation: The
context/manager.tsmaintains:- Working directory state across commands
- Environment variables
- Command history with relationships (including session interactions)
- File system change tracking
-
AI Optimizations: The output processor in
utils/output-processor.tsintelligently:- Detects and parses structured data (JSON, YAML, CSV)
- Removes noise from outputs (progress bars, ANSI codes)
- Provides command-specific formatting
-
Audit System: Comprehensive logging in
audit/with:- Immutable append-only logs
- Real-time monitoring with configurable alert rules
- Multiple export formats (JSON, CSV, XML)
-
Dynamic Configuration: The configuration system provides:
- Runtime configuration management without server restarts
- Configuration history tracking with rollback capability
- Automatic component reinitialization on changes
- Schema validation for all configuration updates
- Backward compatibility with legacy configuration tools
The server uses STDIO transport and implements comprehensive MCP tools with logging capability:
- Core execution:
execute_command,confirm_command - Interactive sessions:
start_interactive_session,start_terminal_session,send_to_session,read_session_output,list_sessions,kill_session,get_session_status - Terminal viewer:
toggle_terminal_viewer,get_terminal_viewer_status - Context management:
get_context,get_history,set_working_directory - Security management:
update_security_config,get_security_status,get_pending_confirmations - AI assistance:
get_intent_summary,suggest_next_commands - Audit and monitoring:
generate_audit_report,export_logs,get_alerts,acknowledge_alert,get_audit_config,update_audit_config - MCP logging:
logging/setLevelhandler for dynamic log level control
The dynamic configuration system provides runtime flexibility:
- Modify settings without server restart
- Real-time blocked command management
- Flexible resource limit adjustment
- Configurable logging levels
- Customizable output formatting
- Flexible display options
- Adaptive session management
- All configuration changes are validated using Zod schemas
- Type checking ensures data integrity
- Previous values are preserved for rollback capability
- All configuration changes are logged with timestamps
- Change history is maintained for accountability
- Rollback capability allows reverting problematic changes
- Configuration changes only affect relevant components
- Server stability is maintained during configuration updates
- Graceful error handling prevents configuration corruption
MIT License - see LICENSE file for details.