Preventing AI agents from executing destructive terminal commands
Terminal Guardian MCP is a production-grade Model Context Protocol server that provides secure, sandboxed terminal access for AI assistants like Claude. It includes a risk analysis engine that categorizes commands as safe, warning, dangerous, or blocked, and offers features like git commit generation, workspace templates, process management, environment variable inspection, network diagnostics, filesystem access, and Docker integration.
Article intelligence
Key points
- Terminal Guardian MCP provides safe terminal access for AI assistants through risk analysis and sandboxing.
- Commands are classified into four risk levels: SAFE, WARNING, DANGEROUS, and BLOCKED.
- It includes 21 tools across 7 domains including terminal execution, git analysis, network diagnostics, and Docker management.
- Features like AI commit message generation and workspace templates enhance developer productivity.
Why it matters
This matters because terminal Guardian MCP provides safe terminal access for AI assistants through risk analysis and sandboxing.
Technical impact
May affect model selection, inference cost, product capability, and evaluation benchmarks.
Notifications You must be signed in to change notification settings
Fork 0
Star 6
BranchesTags
Open more actions menu
Folders and files
NameName
Last commit message
Last commit date
Latest commit
History
19 Commits
19 Commits
.github/workflows
.github/workflows
docs/assets
docs/assets
src
src
tests
tests
.gitignore
.gitignore
.npmignore
.npmignore
.prettierrc
.prettierrc
Dockerfile
Dockerfile
LICENSE
LICENSE
README.md
README.md
docker-compose.yml
docker-compose.yml
eslint.config.js
eslint.config.js
package-lock.json
package-lock.json
package.json
package.json
terminal-guardian-mcp-1.0.0.tgz
terminal-guardian-mcp-1.0.0.tgz
terminal-guardian-mcp-1.0.2.tgz
terminal-guardian-mcp-1.0.2.tgz
terminal-guardian.config.json
terminal-guardian.config.json
tsconfig.json
tsconfig.json
vitest.config.ts
vitest.config.ts
Repository files navigation
💡 Demo shows the core analysis engine. In real use, this runs automatically when Claude executes terminal commands via MCP — no CLI needed.
Terminal Guardian MCP
Secure, sandboxed terminal access for AI assistants via the Model Context Protocol
Features · Quick Start · Claude Desktop · Tools · Security · Configuration · Windows · Roadmap
Overview
Terminal Guardian MCP is a production-grade Model Context Protocol server that gives AI assistants like Claude safe, controlled, and auditable access to your terminal. Every command is analyzed for risk, logged with full context, and executed inside configurable safety boundaries.
Built for developers who want to leverage AI in their workflows without compromising system integrity.
AI Assistant → Terminal Guardian MCP → Risk Analysis → Sandboxed Execution → Structured Result
⚠️ This server provides real terminal access. Configure it carefully. Review the Security Philosophy before deploying.
Features
🛡️ Risk Analysis Engine
Every command passes through a multi-layer safety analysis before execution:
Risk Level Example Commands Behavior
SAFE ls, git status, npm list Executed immediately
WARNING rm -rf ./dist, docker stop app Requires explicit confirmation
DANGEROUS sudo apt-get, curl | bash Blocked by default
BLOCKED rm -rf /, shutdown, fork bombs Always blocked, always logged
⚡ Secure Terminal Execution
Shell command execution with full stdout/stderr capture
Configurable per-command timeouts (default: 30s, max: 5m)
SIGTERM → SIGKILL escalation for hanging processes
Working directory isolation within workspace root
Output size limits to prevent memory exhaustion
Cross-platform: auto-detects bash, sh, PowerShell, or cmd
🤖 AI Commit Message Generator (new in v1.3)
Analyzes git diff and generates Conventional Commits suggestions via Claude
Returns 1–5 suggestions with type, scope, subject, body, and breaking change flags
Three styles: conventional, simple, detailed
Automatically truncates large diffs to keep API costs low
Requires ANTHROPIC_API_KEY environment variable
📦 Workspace Templates (new in v1.3)
Scaffold new projects instantly from 8 production-ready templates:
Template ID Stack
node-typescript Node.js + TypeScript + ESLint + Vitest
node-javascript Node.js ESM
python-fastapi FastAPI + Pydantic v2 + pytest
python-cli Typer + Rich
react-vite React 18 + Vite + TypeScript
nextjs Next.js 15 App Router + TypeScript
express-api Express + Zod + TypeScript
mcp-server MCP Server starter (TypeScript)
🔎 Process Management
List all running processes with CPU, memory, PID, and command
Filter by name or command substring, sort by CPU / memory / PID / name
Terminate processes by PID with signal control (SIGTERM / SIGKILL / SIGINT / SIGHUP)
Protected PID list — system processes (init, systemd, launchd, PID 0/1) can never be killed
SIGKILL requires confirmed: true as an additional safety gate
🔐 Environment Variables
Inspect environment variables with automatic secret masking
Secrets are never revealed in full — shown as sk**...xy format
Auto-detects secrets by key name (API_KEY, TOKEN, PASSWORD, DATABASE_URL, SECRET, ...)
Auto-detects secrets by value shape (base64 blobs, JWTs, GitHub/Stripe/Slack/OpenAI tokens)
Filter by key name, category (secret, path, system, runtime, unknown), or fetch specific keys
🌐 Network Diagnostics
Ping — check host reachability and measure round-trip latency, cross-platform
HTTP requests — GET/POST/PUT/PATCH/DELETE/HEAD with headers, body, redirect control; response body capped at 512KB
DNS lookup — resolve hostnames via dig → nslookup → Node.js DNS fallback
Private/loopback addresses blocked by default (127.x, 10.x, 192.168.x, ::1, link-local)
Only http:// and https:// allowed — file://, ftp://, ldap:// and others are blocked
📁 Filesystem Access
File listing, reading, and content search
Configurable workspace root with path traversal prevention
Glob pattern matching for targeted file searches
Project structure analysis with language detection
🐳 Docker Integration (optional)
List and inspect containers
Read container logs with timestamp support
Real-time resource stats (CPU, memory, network, block I/O)
Execute commands inside containers (docker_exec) with confirmation gate
Container restart with confirmation gate
Disabled by default — opt-in via config
🌿 Git Repository Analysis
Full git status with staged/unstaged/untracked breakdown
Diff viewer with per-file additions/deletions
Commit history with author, date, and refs
Branch listing (local + remote)
Read-only by default (push/commit require explicit opt-in)
📊 Session Logging
Structured JSON logs via pino
Every command, tool call, and security event is recorded
Configurable log levels and output destinations
Optional output logging (disabled by default for privacy)
🔒 Rate Limiting
Per-minute and per-hour request limits
In-memory bucket algorithm with automatic reset
Clear error messages with retry-after hints
Quick Start
Prerequisites
Node.js ≥ 18.0.0
npm or yarn
Install from npm
npm install -g terminal-guardian-mcp
Install from source
git clone https://github.com/7Majesty-M/terminal-guardian-mcp.git cd terminal-guardian-mcp npm install npm run build
Run directly
terminal-guardian-mcp
or from source:
node dist/index.js
Claude Desktop Integration
Add Terminal Guardian to your Claude Desktop configuration:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\Claude\claude_desktop_config.json
Linux: ~/.config/Claude/claude_desktop_config.json
{ "mcpServers": { "terminal-guardian": { "command": "npx", "args": ["terminal-guardian-mcp"], "env": { "GUARDIAN_CONFIG": "/path/to/your/terminal-guardian.config.json", "ANTHROPIC_API_KEY": "sk-ant-..." } } } }
ANTHROPIC_API_KEY is only required for the git_suggest_commit tool. All other tools work without it.
Or if installed globally:
{ "mcpServers": { "terminal-guardian": { "command": "terminal-guardian-mcp", "env": { "GUARDIAN_CONFIG": "/absolute/path/to/terminal-guardian.config.json" } } } }
After saving, restart Claude Desktop. You should see Terminal Guardian appear in the tools list.
MCP Tools
Terminal Guardian exposes 21 tools across 7 domains.
Terminal
run_command
Execute a shell command with full safety analysis.
{ "command": "npm run build", "cwd": "./my-project", "timeout": 60000, "confirmed": false }
Returns:
{ "success": true, "data": { "command": "npm run build", "exitCode": 0, "stdout": "...", "stderr": "", "duration": 4230, "timedOut": false, "workingDir": "/workspace/my-project", "timestamp": "2024-01-15T10:30:00.000Z", "riskAssessment": { "level": "SAFE", "score": 5, "reasons": ["No dangerous patterns detected"], "blocked": false } } }
analyze_command
Analyze a command without running it.
{ "command": "rm -rf ./old-build" }
Returns:
{ "level": "WARNING", "score": 40, "reasons": ["Recursive deletion — verify target path carefully"], "requiresConfirmation": true, "blocked": false, "recommendation": "Review this command carefully before proceeding." }
Git
git_status
{ "path": "." }
git_diff
{ "staged": false, "file": "src/api.ts" }
git_log
{ "limit": 20 }
git_suggest_commit ✨
Generate AI-powered commit message suggestions from your staged diff.
{ "staged": true, "count": 3, "style": "conventional" }
Returns:
{ "suggestions": [ { "message": "feat(auth): add JWT refresh token rotation\n\nImplements automatic rotation on each use\nto prevent token reuse attacks.", "type": "feat", "scope": "auth", "subject": "add JWT refresh token rotation", "breaking": false, "confidence": "high" } ], "model": "claude-sonnet-4-20250514", "tokensUsed": 312, "diffSummary": "Added refresh token rotation to AuthService", "truncated": false }
Workspace Templates
list_templates
List all available project templates with optional tag filtering.
{ "tag": "python" }
Returns:
[ { "id": "python-fastapi", "name": "Python FastAPI", "tags": ["python", "api", "backend"], "fileCount": 6, "postInstall": ["python -m venv .venv", "pip install -r requirements.txt"] }, { "id": "python-cli", "name": "Python CLI Tool", "tags": ["python", "cli"], "fileCount": 4 } ]
apply_template ✨
Scaffold a new project from a template. Safe — cannot write outside workspace root.
{ "templateId": "mcp-server", "projectName": "my-mcp-tool", "targetDir": "./projects/my-mcp-tool" }
Returns:
{ "templateId": "mcp-server", "projectName": "my-mcp-tool", "targetDir": "/workspace/projects/my-mcp-tool", "filesCreated": ["package.json", "tsconfig.json", "src/index.ts", "claude_desktop_config.example.json", ".gitignore", "README.md"], "filesSkipped": [], "postInstall": ["npm install", "npm run build"] }
Processes
list_processes
{ "filter": "node", "sortBy": "memory", "limit": 20 }
kill_process
{ "pid": 12345, "signal": "SIGTERM" }
"signal": "SIGKILL" requires "confirmed": true.
Environment
get_env
{ "keys": ["NODE_ENV", "PORT", "DATABASE_URL"] }
Secret masking:
Original Shown as
sk-proj-abc123...xyz sk**...yz
postgres://user:pass@host/db po**...db
eyJhbGci... (JWT) ey**...
ab ****
Network
ping
{ "host": "api.github.com", "count": 4 }
http_request
{ "url": "https://api.github.com/zen", "method": "GET", "headers": { "Accept": "application/json" } }
dns_lookup
{ "host": "github.com" }
Filesystem
list_files
{ "path": "./src", "recursive": true }
read_file
{ "path": "./src/index.ts" }
search_files
{ "query": "TODO", "path": "./src", "pattern": "**/*.ts" }
Docker (requires docker.enabled: true)
docker_ps · docker_logs · docker_stats · docker_exec
{ "container": "my-app", "command": ["node", "--version"], "confirmed": true }
Architecture
terminal-guardian-mcp/ ├── src/ │ ├── index.ts # MCP server entrypoint & tool routing (21 tools) │ ├── types/index.ts # Shared TypeScript types │ ├── config/loader.ts # Config file loading with deep merge │ ├── security/ │ │ ├── riskAnalyzer.ts # Multi-layer command risk analysis engine │ │ └── rateLimiter.ts # Per-minute/hour request throttling │ ├── tools/ │ │ ├── executor.ts # Cross-platform shell execution engine │ │ ├── processManager.ts # Process listing and safe termination │ │ └── schemas.ts # Zod input validation schemas │ ├── system/ │ │ └── envManager.ts # Env vars with automatic secret masking │ ├── network/ │ │ └── diagnostics.ts # Ping, HTTP requests, DNS lookup │ ├── filesystem/ │ │ └── manager.ts # Safe file access with path enforcement │ ├── docker/ │ │ └── manager.ts # Dockerode integration + container exec │ ├── git/ │ │ ├── manager.ts # Git operations via child_process │ │ └── commitGenerator.ts # AI commit message generation (Anthropic API) │ ├── workspace/ │ │ └── templates.ts # Project scaffolding — 8 templates │ └── logging/ │ └── logger.ts # Pino-based structured logging ├── tests/ # Vitest unit tests (136 tests) ├── .github/workflows/ # CI/CD pipeline (Node 18/20/22) ├── Dockerfile
[truncated for AI cost control]