7Majesty-M/terminal-guardian-mcp

GitHub: 7Majesty-M/terminal-guardian-mcp

该工具为 AI 助手提供沙盒化、可审计的终端访问能力,通过多层风险分析确保命令执行安全可控。

Stars: 7 | Forks: 1

Terminal Guardian MCP ## 🎬 实时演示 Terminal Guardian Demo
# Terminal Guardian MCP **通过 Model Context Protocol 为 AI 助手提供安全、沙盒化的终端访问** [![CI](https://static.pigsec.cn/wp-content/uploads/repos/cas/ad/ad5834178f7599af9fdda11629d49cae07f2997beec49821b2920eff5bfd50e7.svg)](https://github.com/7Majesty-M/terminal-guardian-mcp/actions) [![npm version](https://img.shields.io/npm/v/terminal-guardian-mcp?label=npm)](https://www.npmjs.com/package/terminal-guardian-mcp) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Node.js](https://img.shields.io/badge/Node.js-18%2B-green.svg)](https://nodejs.org) [![TypeScript](https://img.shields.io/badge/TypeScript-5.6-blue.svg)](https://www.typescriptlang.org) [![MCP Compatible](https://img.shields.io/badge/MCP-Compatible-purple.svg)](https://modelcontextprotocol.io) [功能](#features) · [快速开始](#quick-start) · [Claude Desktop](#claude-desktop-integration) · [工具](#mcp-tools) · [安全性](#security-philosophy) · [配置](#configuration) · [Windows](#windows-support) · [路线图](#roadmap)
## 概述 **Terminal Guardian MCP** 是一个生产级的 [Model Context Protocol](https://modelcontextprotocol.io) 服务器,它为像 Claude 这样的 AI 助手提供**安全、可控且可审计的终端访问**。每条命令都会进行风险分析,记录完整的上下文,并在可配置的安全边界内执行。 专为希望在工作流程中利用 AI 同时又不损害系统完整性的开发者而构建。 ``` AI Assistant → Terminal Guardian MCP → Risk Analysis → Sandboxed Execution → Structured Result ``` ## 功能 ### 🛡️ 风险分析引擎 每条命令在执行前都会经过多层安全分析: | 风险级别 | 示例命令 | 行为 | |------------|-----------------|----------| | `SAFE` | `ls`, `git status`, `npm list` | 立即执行 | | `WARNING` | `rm -rf ./dist`, `docker stop app` | 需要明确确认 | | `DANGEROUS` | `sudo apt-get`, `curl \| bash` | 默认阻止 | | `BLOCKED` | `rm -rf /`, `shutdown`, fork bombs | 始终阻止,并记录日志 | ### ⚡ 安全的终端执行 - 捕获完整 `stdout`/`stderr` 的 shell 命令执行 - 可配置的每条命令超时时间(默认:30秒,最大:5分钟) - 针对挂起进程的 SIGTERM → SIGKILL 升级机制 - 在工作区根目录内进行工作目录隔离 - 输出大小限制,防止内存耗尽 - 跨平台:自动检测 bash、sh、PowerShell 或 cmd ### 🤖 AI 提交信息生成器 *(v1.3 新增)* - 分析 `git diff` 并通过 Claude 生成 [Conventional Commits](https://www.conventionalcommits.org) 建议 - 返回 1–5 个建议,包含类型、作用域、主题、正文和破坏性变更标记 - 三种风格:`conventional`、`simple`、`detailed` - 自动截断大型 diff 以保持较低的 API 成本 - 需要 `ANTHROPIC_API_KEY` 环境变量 ### 📦 工作区模板 *(v1.3 新增)* 从 8 个生产就绪的模板中即时搭建新项目: | 模板 ID | 技术栈 | |-------------|-------| | `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 启动模板 (TypeScript) | ### 🔎 进程管理 - 列出所有正在运行的进程,包括 CPU、内存、PID 和命令 - 按名称或命令子字符串过滤,按 CPU / 内存 / PID / 名称排序 - 通过 PID 终止进程并带有信号控制 (SIGTERM / SIGKILL / SIGINT / SIGHUP) - 受保护的 PID 列表 —— 系统进程 (init, systemd, launchd, PID 0/1) 永远不会被杀死 - SIGKILL 需要 `confirmed: true` 作为额外的安全门槛 ### 🔐 环境变量 - 检查环境变量并**自动遮蔽敏感信息** - 敏感信息永远不会完整显示 —— 以 `sk**...xy` 格式显示 - 通过键名自动检测敏感信息 (`API_KEY`, `TOKEN`, `PASSWORD`, `DATABASE_URL`, `SECRET`, ...) - 通过值特征自动检测敏感信息 (base64 块、JWT、GitHub/Stripe/Slack/OpenAI token) - 按键名、类别 (`secret`, `path`, `system`, `runtime`, `unknown`) 过滤,或获取特定键 ### 🌐 网络诊断 - **Ping** —— 检查主机可达性并测量往返延迟,跨平台 - **HTTP 请求** —— 包含 header、body、重定向控制的 GET/POST/PUT/PATCH/DELETE/HEAD;响应 body 上限为 512KB - **DNS 查询** —— 通过 `dig` → `nslookup` → Node.js DNS 回退解析主机名 - 默认阻止私有/环回地址 (`127.x`, `10.x`, `192.168.x`, `::1`, link-local) - 仅允许 `http://` 和 `https://` —— `file://`, `ftp://`, `ldap://` 等被阻止 ### 📁 文件系统访问 - 文件列表、读取和内容搜索 - 可配置的工作区根目录,防止路径遍历 - 用于定向文件搜索的 Glob 模式匹配 - 带有语言检测的项目结构分析 ### 🐳 Docker 集成 *(可选)* - 列出和检查容器 - 读取带有时间戳支持的容器日志 - 实时资源统计 (CPU、内存、网络、块 I/O) - 在容器内执行命令 (`docker_exec`) 带有确认门槛 - 带有确认门槛的容器重启 - 默认禁用 —— 通过配置开启 ### 🌿 Git 仓库分析 - 完整的 `git status`,包含已暂存/未暂存/未跟踪的详细分类 - 带有每个文件增删情况的 Diff 查看器 - 包含作者、日期和引用的提交历史 - 分支列表 (本地 + 远程) - 默认只读 (push/commit 需要明确开启) ### 📊 会话日志 - 通过 [pino](https://getpino.io) 输出结构化的 JSON 日志 - 记录每一条命令、工具调用和安全事件 - 可配置的日志级别和输出目的地 - 可选的输出日志 (默认禁用以保护隐私) ### 🔒 速率限制 - 每分钟和每小时的请求限制 - 带有自动重置的内存桶算法 - 带有重试提示的清晰错误信息 ### 🔌 WebSocket 传输 *(v1.4 新增)* - 作为持久化的 HTTP + WebSocket 服务器运行 —— 多个客户端同时连接 - 每个 WebSocket 连接都有其独立的 MCP Server 实例 - Bearer token 认证 (通过 `Authorization` header 或 `?token=` 查询字符串) - 内置 **Web 仪表板**,位于 `GET /` —— 实时统计、连接数、运行时间、配置片段 - 位于 `GET /health` 的健康检查和位于 `GET /stats` 的统计 API - Keepalive ping/pong 机制,自动清理死连接 - 可配置的最大连接数 (默认:10) - 与 stdio 并行工作 —— 在启动时通过 CLI 标志选择模式 ### 🖥️ 远程 SSH 执行 *(v1.5 新增)* - 通过 SSH 在远程服务器上执行命令 —— 具有**与本地执行相同的风险分析** - 配置中的命名服务器配置文件 (`prod`, `staging`, `dev`, ...) - 基于密钥的认证 (读取 `~/.ssh/id_rsa` 或任何指定的密钥路径) 和密码认证 - 连接池 —— 重用 SSH 会话,无需为每条命令进行新的握手 - 主机指纹验证,防止 MITM 攻击 - `BLOCKED` / `WARNING` / `DANGEROUS` 规则在远程主机上同样适用 - 可配置的超时、最大连接数、keepalive 间隔 ## 快速开始 ### 前置条件 - Node.js ≥ 18.0.0 - npm 或 yarn ### 从 npm 安装 ``` npm install -g terminal-guardian-mcp ``` ### 从源码安装 ``` git clone https://github.com/7Majesty-M/terminal-guardian-mcp.git cd terminal-guardian-mcp npm install npm run build ``` ### 直接运行 ``` # stdio 模式 — 适用于 Claude Desktop(默认) terminal-guardian-mcp # WebSocket 模式 — 持久服务器,多客户端 terminal-guardian-mcp --transport ws --port 3000 # WebSocket 与 token 认证 terminal-guardian-mcp --transport ws --port 3000 --token mysecret # 帮助 terminal-guardian-mcp --help ``` ## Claude Desktop 集成 将 Terminal Guardian 添加到您的 Claude Desktop 配置中: **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-..." } } } } ``` 或者,如果全局安装: ``` { "mcpServers": { "terminal-guardian": { "command": "terminal-guardian-mcp", "env": { "GUARDIAN_CONFIG": "/absolute/path/to/terminal-guardian.config.json" } } } } ``` 保存后,**重启 Claude Desktop**。您应该会看到 Terminal Guardian 出现在工具列表中。 ### WebSocket 模式 (远程 / 持久化服务器) 如果您将 Terminal Guardian 作为持久化的 WebSocket 服务器运行 (例如在远程机器或 Docker 中),请改为通过 URL 连接: ``` { "mcpServers": { "terminal-guardian": { "url": "ws://localhost:3000", "headers": { "Authorization": "Bearer mysecret" } } } } ``` ``` # 首先启动服务器 terminal-guardian-mcp --transport ws --port 3000 --token mysecret # 然后在浏览器中打开 dashboard open http://localhost:3000 ``` ## MCP 工具 Terminal Guardian 跨 8 个领域提供了 **24 个工具**。 ### 终端 #### `run_command` 执行带有全面安全分析的 shell 命令。 ``` { "command": "npm run build", "cwd": "./my-project", "timeout": 60000, "confirmed": false } ``` **返回:** ``` { "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` 分析命令但不运行它。 ``` { "command": "rm -rf ./old-build" } ``` **返回:** ``` { "level": "WARNING", "score": 40, "reasons": ["Recursive deletion — verify target path carefully"], "requiresConfirmation": true, "blocked": false, "recommendation": "Review this command carefully before proceeding." } ``` ### SSH #### `ssh_list_profiles` 列出所有已配置的 SSH 配置文件。 ``` {} ``` **返回:** ``` [ { "name": "prod", "host": "prod.example.com", "port": 22, "username": "deploy", "authMethod": "key", "connected": false }, { "name": "staging", "host": "stg.example.com", "port": 22, "username": "ubuntu", "authMethod": "key", "connected": true } ] ``` #### `ssh_test` 测试 SSH 连通性并测量延迟。 ``` { "profile": "prod" } ``` **返回:** ``` { "profile": "prod", "host": "prod.example.com", "port": 22, "username": "deploy", "connected": true, "latencyMs": 42 } ``` #### `ssh_exec` ✨ 在远程服务器上执行命令。使用与本地执行相同的风险引擎。 ``` { "profile": "prod", "command": "systemctl status nginx", "cwd": "/var/app" } ``` **返回:** ``` { "profile": "prod", "host": "prod.example.com", "command": "systemctl status nginx", "exitCode": 0, "stdout": "● nginx.service - A high performance web server...", "stderr": "", "duration": 312, "timedOut": false, "riskAssessment": { "level": "SAFE", "score": 5, "blocked": false } } ``` ### Git #### `git_status` ``` { "path": "." } ``` #### `git_diff` ``` { "staged": false, "file": "src/api.ts" } ``` #### `git_log` ``` { "limit": 20 } ``` #### `git_suggest_commit` ✨ 根据您暂存的 diff 生成 AI 驱动的提交信息建议。 ``` { "staged": true, "count": 3, "style": "conventional" } ``` **返回:** ``` { "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 } ``` ### 工作区模板 #### `list_templates` 列出所有可用的项目模板,支持可选的标签过滤。 ``` { "tag": "python" } ``` **返回:** ``` [ { "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` ✨ 从模板搭建新项目。安全 —— 无法写入工作区根目录之外。 ``` { "templateId": "mcp-server", "projectName": "my-mcp-tool", "targetDir": "./projects/my-mcp-tool" } ``` **返回:** ``` { "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"] } ``` ### 进程 #### `list_processes` ``` { "filter": "node", "sortBy": "memory", "limit": 20 } ``` #### `kill_process` ``` { "pid": 12345, "signal": "SIGTERM" } ``` ### 环境 #### `get_env` ``` { "keys": ["NODE_ENV", "PORT", "DATABASE_URL"] } ``` **敏感信息遮蔽:** | 原始内容 | 显示为 | |----------|----------| | `sk-proj-abc123...xyz` | `sk**...yz` | | `postgres://user:pass@host/db` | `po**...db` | | `eyJhbGci...` (JWT) | `ey**...` | | `ab` | `****` | ### 网络 #### `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" } ``` ### 文件系统 #### `list_files` ``` { "path": "./src", "recursive": true } ``` #### `read_file` ``` { "path": "./src/index.ts" } ``` #### `search_files` ``` { "query": "TODO", "path": "./src", "pattern": "**/*.ts" } ``` ### Docker *(需要 `docker.enabled: true`)* #### `docker_ps` · `docker_logs` · `docker_stats` · `docker_exec` ``` { "container": "my-app", "command": ["node", "--version"], "confirmed": true } ``` ## 架构 ``` terminal-guardian-mcp/ ├── src/ │ ├── index.ts # MCP server entrypoint & tool routing (24 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) │ ├── ssh/ │ │ ├── manager.ts # SSH connection pool + profile management │ │ └── executor.ts # Remote command execution with risk analysis │ ├── workspace/ │ │ └── templates.ts # Project scaffolding — 8 templates │ ├── transport/ │ │ ├── wsServer.ts # WebSocket HTTP server + auth + multi-client │ │ └── dashboard.ts # Live web dashboard (dark theme, auto-refresh) │ └── logging/ │ └── logger.ts # Pino-based structured logging ├── tests/ # Vitest unit tests (170 tests) ├── .github/workflows/ # CI/CD pipeline (Node 18/20/22) ├── Dockerfile # Multi-stage build, non-root user ├── docker-compose.yml └── terminal-guardian.config.json ``` ## 配置 ``` { "workspace": { "rootDir": "/home/user/projects", "allowedPaths": ["/home/user/projects"], "maxFileSize": 10485760, "maxFilesPerOperation": 100 }, "execution": { "timeout": 30000, "maxOutputSize": 1048576, "maxConcurrentProcesses": 5, "shell": "auto" }, "security": { "enableRiskAnalysis": true, "blockDangerousCommands": true, "requireConfirmationForWarnings": true, "allowSudo": false, "allowNetworkCommands": true, "customBlocklist": [], "customAllowlist": [] }, "rateLimit": { "enabled": true, "maxRequestsPerMinute": 60, "maxRequestsPerHour": 500 }, "docker": { "enabled": false, "socketPath": "/var/run/docker.sock", "allowContainerRestart": false, "allowLogAccess": true }, "git": { "enabled": true, "allowPush": false, "allowCommit": false, "maxLogEntries": 50 }, "logging": { "enabled": true, "level": "info", "logDir": "./logs", "logCommands": true, "logOutputs": false, "logSecurityEvents": true, "prettyPrint": false }, "ssh": { "enabled": false, "timeout": 30000, "keepaliveInterval": 10000, "maxConnections": 5, "profiles": {} } } ``` ### SSH 配置文件 要使用 SSH 工具,请将配置文件添加到 `ssh.profiles` 并设置 `ssh.enabled: true`: ``` { "ssh": { "enabled": true, "profiles": { "prod": { "host": "prod.example.com", "port": 22, "username": "deploy", "privateKeyPath": "~/.ssh/id_rsa" }, "staging": { "host": "staging.example.com", "username": "ubuntu", "privateKeyPath": "~/.ssh/staging_key" } } } } ``` ### 配置参考 | 键 | 默认值 | 描述 | |-----|---------|-------------| | `workspace.rootDir` | `"."` | 所有文件系统操作的绝对根目录 | | `workspace.maxFileSize` | `10485760` | 最大可读文件大小(字节,10MB) | | `execution.timeout` | `30000` | 默认命令超时(毫秒) | | `execution.maxOutputSize` | `1048576` | 最大 stdoutstderr 大小(字节,1MB) | | `execution.shell` | `"auto"` | Shell —— `"auto"` 会自动检测 bash/pwsh/sh | | `security.allowSudo` | `false` | 是否允许 sudo 命令 | | `security.customBlocklist` | `[]` | 始终阻止的附加正则表达式模式 | | `security.customAllowlist` | `[]` | 绕过风险分析的模式 | | `docker.enabled` | `false` | 启用 Docker 工具集成 | | `docker.allowContainerRestart` | `false` | 允许重启容器 | | `git.allowPush` | `false` | 允许通过 run_command 执行 `git push` | | `logging.logOutputs` | `false` | 记录 stdout/stderr (可能包含敏感信息!) | | `ssh.enabled` | `false` | 启用 SSH 工具集成 | | `ssh.maxConnections` | `5` | 最大池化 SSH 连接数 | ## 安全理念 Terminal Guardian 采用 **默认拒绝** 模型,并带有明确的白名单机制。 ### 始终阻止 - 系统路径的递归文件系统删除 (`rm -rf /`) - Fork bombs (`:(){:|:&};:`) - 系统电源管理 (`shutdown`, `reboot`, `halt`) - 文件系统格式化 (`mkfs`, `wipefs`, `dd of=/dev/`) - 反向 shell 和 TCP 重定向 (`/dev/tcp/`) - `chmod 777 /` 以及类似的根级别权限更改 - HTTP 请求中的 `file://`, `ftp://`, `ldap://` URL schemes - 网络工具中的私有/环回地址 ### 需要确认 - 递归删除 (`rm -rf ./anything`) - Docker 容器停止/杀死/移除 - Docker 容器执行 (`docker_exec`) - 强制杀死 —— 带有 `SIGKILL` 的 `kill_process` - 权限修改 (`chmod`, `chown`) - Git 破坏性操作 (`reset --hard`, `push`) - 服务管理 (`systemctl stop`) ### 始终安全 - 只读 shell 命令:`ls`, `cat`, `grep`, `find` - Git 检查:`status`, `log`, `diff`, `branch` - `git_suggest_commit` —— 仅读取 diff,从不进行写入操作 - `list_templates` —— 不更改文件系统 - Docker 读取操作:`ps`, `images`, `inspect`, `stats`, `logs` - npm 读取操作:`list`, `outdated`, `audit` - 系统信息:`whoami`, `uptime`, `df`, `uname` - `list_processes` —— 只读,从不修改状态 - `get_env` —— 敏感信息在离开模块前被遮蔽 - `dns_lookup` —— 只读 DNS 查询 - 对公共主机的 `ping` - `ssh_list_profiles`, `ssh_test` —— 只读,不执行命令 ### 威胁模型 - **AI 幻觉安全** —— 阻止 AI 可能错误建议的命令 - **Prompt 注入防御** —— 速率限制和明确确认防止自动化滥用 - **供应链保护** —— 阻止通过管道传输到 shell 的模式 (`curl | bash`) - **提权** —— 默认阻止 sudo - **机密泄露** —— 环境变量在读取时被遮蔽,原始值永远不会进入 AI 上下文 - **SSRF 保护** —— 所有网络工具中阻止私有网络范围 - **数据外泄** —— 输出大小限制,默认不记录敏感信息 - **工作区隔离** —— 模板和文件系统工具无法逃逸工作区根目录 - **远程命令安全** —— SSH 上与本地使用相同的风险引擎,BLOCKED 意味着在任何地方都被 BLOCKED ## Windows 支持 Terminal Guardian 在启动时会自动检测可用的 shell —— 无需手动配置。 | 平台 | 默认 Shell | 回退方案 | |----------|--------------|---------| | Linux / macOS | `/bin/bash` | `/bin/sh` | | Windows | `pwsh` (PowerShell Core) | `cmd.exe` | ### Windows 快速开始 ``` # 选项 1:PowerShell Core(推荐) winget install Microsoft.PowerShell # 选项 2:WSL — shell 自动检测,无需更改配置 # 选项 3:Git Bash — 显式设置 path ``` ``` { "execution": { "shell": "C:\\Program Files\\Git\\bin\\bash.exe" } } ``` ## Docker 用法 ``` docker build -t terminal-guardian-mcp . docker-compose up -d docker-compose logs -f terminal-guardian ``` 容器以非 root 用户 (`guardian:guardian`) 身份运行,并具有只读的根文件系统。 ## 开发 ``` npm install # Install dependencies npm run dev # Start in watch mode npm test # Run tests npm run test:coverage # Coverage report npm run typecheck # TypeScript check npm run lint # ESLint npm run format # Prettier npm run build # Production build ``` ## 使用示例 ### 与 Claude Desktop 一起使用 ### 工具调用示例 **安全命令:** ``` User: Run `ls -la` in the src directory Claude: [calls run_command {"command": "ls -la", "cwd": "src"}] → Returns file listing immediately (SAFE) ``` **需要确认:** ``` User: Clean up the dist directory Claude: [calls analyze_command → WARNING] "rm -rf ./dist requires confirmation. Proceed?" User: Yes Claude: [calls run_command with confirmed: true] ``` **被阻止:** ``` User: Run rm -rf / Claude: "Terminal Guardian has blocked this — it would delete the root filesystem." ``` **AI 提交信息:** ``` User: I've staged my auth refactor, suggest a commit message Claude: [calls git_suggest_commit {"staged": true, "count": 3}] 1. refactor(auth): extract token validation into AuthGuard class 2. refactor(auth): decouple token logic from UserService 3. chore(auth): reorganize auth module structure Which one would you like to use? ``` **搭建项目:** ``` User: Create a new MCP server called "weather-mcp" Claude: [calls apply_template {"templateId": "mcp-server", "projectName": "weather-mcp", "targetDir": "./weather-mcp"}] Created 6 files. Next steps: cd weather-mcp && npm install && npm run build ``` **网络检查:** ``` User: Is my API server reachable? Claude: [calls ping {"host": "api.myapp.com", "count": 3}] "api.myapp.com is reachable. Avg latency: 24ms, 0% packet loss." ``` **环境检查:** ``` User: What's my runtime environment? Claude: [calls get_env {"filter": "NODE"}] "NODE_ENV=production, NODE_VERSION=20.11.0. DATABASE_URL and API_KEY are present — values masked for security." ``` **Docker 执行:** ``` User: Check the Node version inside the api container Claude: [calls docker_exec {"container": "api", "command": ["node", "--version"], "confirmed": true}] "v20.11.0" ``` **SSH —— 远程服务器管理:** ``` User: Check nginx status on prod Claude: [calls ssh_test {"profile": "prod"}] "Connected to prod.example.com (42ms latency)." Claude: [calls ssh_exec {"profile": "prod", "command": "systemctl status nginx"}] "● nginx.service — active (running) since..." User: Restart it Claude: [calls ssh_exec {"profile": "prod", "command": "systemctl restart nginx", "confirmed": true}] "Done — nginx restarted. Exit code 0." ``` **WebSocket 模式 —— 远程访问:** ``` # 在你的 dev server 上 terminal-guardian-mcp --transport ws --port 3000 --token mytoken # Dashboard: http://your-server:3000 # Claude Desktop 通过 ws://your-server:3000 连接 # 多个 Claude 会话可以同时连接 — 每个会话获取独立的 MCP instance ``` ## 路线图 ### 已发布 - [x] **v1.0** —— 带有风险分析引擎的安全终端执行 - [x] **v1.0** —— 带有路径遍历保护的文件系统访问 - [x] **v1.0** —— Git 仓库分析 (status、diff、log、branches) - [x] **v1.0** —— Docker 集成 (ps、logs、stats、restart) - [x] **v1.0** —— 会话日志、速率限制、可配置的安全性 - [x] **v1.0** —— 跨平台 shell 自动检测 (Linux / macOS / Windows) - [x] **v1.1** —— 进程管理 (`list_processes`, `kill_process`) - [x] **v1.1** —— 带有自动敏感信息遮蔽的环境变量检查 - [x] **v1.2** —— 网络诊断 (`ping`, `http_request`, `dns_lookup`) - [x] **v1.2** —— 带有确认门槛的 Docker 容器执行 (`docker_exec`) - [x] **v1.3** —— AI 驱动的提交信息生成 (`git_suggest_commit`) - [x] **v1.3** —— 工作区模板 —— 8 个项目启动模板 (`list_templates`, `apply_template`) - [x] **v1.4** —— WebSocket 传输 (与 stdio 一起),带有认证、仪表板、多客户端支持 - [x] **v1.5** —— 带有基于密钥的认证、连接池、风险分析的远程 SSH 执行 ### 计划中 - [ ] **v2.0** —— 完整的 gVisor/nsjail 沙盒集成 - [ ] **v2.0** —— 基于会话的权限范围划分 - [ ] **v2.0** —— 审计日志导出 (JSON/CSV/SIEM 格式) ## 贡献 1. Fork 本仓库 2. 创建一个功能分支:`git checkout -b feature/my-feature` 3. 提交:`git commit -m 'feat: add my feature'` 4. 推送:`git push origin feature/my-feature` 5. 发起一个 Pull Request 请确保所有测试通过,TypeScript 能顺利编译,并且新的安全模式已被测试覆盖。 ## 相关项目 - [Model Context Protocol](https://modelcontextprotocol.io) —— 协议规范 - [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) —— 官方 SDK - [Claude Desktop](https://claude.ai/download) —— 这是专为其构建的 AI 助手 ## 许可证 MIT © [Terminal Guardian 贡献者](LICENSE)
为 AI 基础设施社区用 ❤️ 构建 如果它对您有用,请 **[⭐ 为此项目加星](https://github.com/7Majesty-M/terminal-guardian-mcp)**
标签:GNU通用公共许可证, MCP服务器, MITM代理, Node.js, TypeScript, 命令行终端, 安全插件, 沙箱隔离, 系统防护, 自动化攻击, 请求拦截