mcpField
T
tetrad

tetrad

本地服务
github.com/SamoraDC开发工具139 周前更新

关于 tetrad

Tetrad 是面向 Claude Code 的 Rust MCP 服务,用 Codex、Gemini CLI 和 Qwen 评审代码与计划,并汇总评审结果。它还提供跨会话模式记录、缓存和可配置的共识规则。

主要功能

  1. 01多模型代码与计划评审
  2. 02汇总评审共识
  3. 03ReasoningBank 模式学习
  4. 04LRU 结果缓存
  5. 05SQLite 跨会话记录
  6. 06CLI 配置与诊断

适用场景

  1. 01编码前审查实施计划
  2. 02保存前检查生成的代码
  3. 03定稿前评审测试与变更
  4. 04追踪并复用评审模式

MCP 相关

Tetrad 通过 stdio 上的 JSON-RPC 2.0 向 Claude Code 提供 6 个工具,用于评审计划、代码和测试,以及检查评审器状态。

配置

本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。

mcp.json · 通用配置
{
"mcpServers": {
"samoradc-tetrad": {
"command": "npx",
"args": [
"-y",
"@samoradc/tetrad"
]
}
}
}
启动命令npx -y @samoradc/tetrad

本地服务需要在你的电脑上安装运行环境(如 Node.js 18+)。各客户端的配置文件位置不同,请参考客户端文档。

安装包
npm@samoradc/tetrad0.1.12

工具

还没有获取到工具列表

本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。

详细介绍

Tetrad

CI MCP Registry npm Crates.io Rust License: MIT

面向 Claude Code 的四重共识 MCP 服务

Tetrad 是一个使用 Rust 编写的高性能 MCP(Model Context Protocol)服务,可编排三种由 AI 驱动的 CLI 代码评估工具(Codex、Gemini CLI、Qwen),以验证 Claude Code 生成的所有代码。

该系统实现了四重共识协议:只有四种智能体——三个外部评估器和 Claude Code 本身——都批准后,代码或计划才会被接受。

功能特性

  • 四重共识:必须有 4 个 AI 模型达成一致,代码才能获批
  • ReasoningBank:采用 RETRIEVE→JUDGE→DISTILL→CONSOLIDATE 循环的持续学习系统
  • 高性能:使用 Rust 编写,通过 Tokio 并行执行
  • MCP 服务:通过 stdio 提供 JSON-RPC 2.0 服务,集成 Claude Code
  • 完整 CLI:直观的命令(init、serve、status、doctor、config 等)
  • LRU 缓存:支持配置 TTL 的结果缓存
  • 钩子系统:提供评估前后回调,支持自定义
  • 可扩展:支持自定义执行器的插件系统
  • 跨会话:使用 SQLite 持久化模式和历史记录

快速开始

1. 安装 Tetrad
# Via npm (recommended - works seamlessly with Claude Code)
npm install -g @samoradc/tetrad

# Or via cargo (requires additional setup)
cargo install tetrad
sudo cp ~/.cargo/bin/tetrad /usr/local/bin/
1.1 在项目中初始化(可选)
npx @samoradc/tetrad init

此操作将:

  • 创建 tetrad.toml 配置文件
  • 创建用于存放数据库的 .tetrad/ 目录
  • 将 .tetrad/ 添加到你的 .gitignore
2. 安装并配置外部 CLI 工具

Tetrad 至少需要以下 AI CLI 工具之一。好消息:如果你已有订阅,就不需要单独的 API 密钥!

Codex CLI(OpenAI)
npm install -g @openai/codex

身份验证选项:

方法要求是否需要 API 密钥?
ChatGPT 登录ChatGPT Plus、Pro、Business、Edu 或 Enterprise 订阅否
API 密钥OpenAI API 账户且有可用额度是
# Option 1: Login with your ChatGPT subscription (recommended)
codex login
# Opens browser for OAuth - follow the prompts

# Option 2: Use API key
export OPENAI_API_KEY="your-openai-key"

**注意:**对于无头/远程服务,请使用 codex login --device-auth 并按照设备代码流程操作。

📖 Codex CLI 身份验证文档


Gemini CLI(Google)
npm install -g @google/gemini-cli

身份验证选项:

方法要求是否需要 API 密钥?免费额度
Google 登录个人 Google 账户否60 次请求/分钟,1,000 次请求/天
API 密钥Google AI Studio 账户是相同限制
# Option 1: Login with Google account (recommended)
gemini auth login
# Opens browser for OAuth - follow the prompts

# Option 2: Use API key from Google AI Studio
export GEMINI_API_KEY="your-gemini-key"

**免费额度:**使用个人 Google 账户,即可免费使用 Gemini 2.5 Pro,并获得 1M token 的上下文窗口!

📖 Gemini CLI 身份验证文档


Qwen CLI(Alibaba)
npm install -g qwen-code

身份验证选项:

方法要求是否需要 API 密钥?免费额度
DashScope APIAlibaba Cloud 账户是2,000 次请求/天
Coding PlanQwen Coding 订阅是(格式不同)已包含
# Get your API key from DashScope console
export DASHSCOPE_API_KEY="your-dashscope-key"

# For international users (outside China)
export OPENAI_BASE_URL="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"

区域端点:

  • 新加坡:dashscope-intl.aliyuncs.com
  • 弗吉尼亚:dashscope-us.aliyuncs.com
  • 北京:dashscope.aliyuncs.com

📖 Qwen API 文档

3. 验证安装
# Check Tetrad version
tetrad version

# Check CLI availability
tetrad status

# Diagnose any issues
tetrad doctor
4. 添加到 Claude Code CLI
# Add Tetrad as MCP server (all projects)
claude mcp add --scope user tetrad -- npx @samoradc/tetrad serve

# Verify it's configured
claude mcp list
其他安装方法
# Current project only
claude mcp add tetrad -- npx @samoradc/tetrad serve

# If installed via cargo
claude mcp add --scope user tetrad -- tetrad serve

注意: Tetrad 已发布到 MCP Registry,便于发现和查阅文档。

5. 替代方案:手动配置

在项目根目录中创建或编辑 .mcp.json:

{
  "mcpServers": {
    "tetrad": {
      "type": "stdio",
      "command": "npx",
      "args": ["@samoradc/tetrad", "serve"],
      "env": {
        "OPENAI_API_KEY": "${OPENAI_API_KEY}",
        "GOOGLE_API_KEY": "${GOOGLE_API_KEY}",
        "DASHSCOPE_API_KEY": "${DASHSCOPE_API_KEY}"
      }
    }
  }
}

或者在 ~/.claude.json 中进行全局用户配置(mcpServers 部分):

{
  "mcpServers": {
    "tetrad": {
      "type": "stdio",
      "command": "npx",
      "args": ["@samoradc/tetrad", "serve"]
    }
  }
}

工作原理

当你让 Claude Code 编写代码时,Tetrad 会自动对其进行验证:

You: "Create a function in Rust that calculates the average of a vector"

Claude Code:
1. Writes the code
2. Calls tetrad_review_code automatically
3. Tetrad sends to Codex, Gemini and Qwen for evaluation
4. Returns consolidated consensus from all 3 evaluators

Tetrad Response:
┌─────────────────────────────────────────────┐
│ DECISION: PASS ✓                            │
│ Score: 92/100                               │
│ Consensus: Yes (3/3 approved)               │
│                                             │
│ Votes:                                      │
│   • Codex:  Pass (95)                       │
│   • Gemini: Pass (90)                       │
│   • Qwen:   Pass (92)                       │
│                                             │
│ Suggestions:                                │
│   - Consider handling empty vector case     │
└─────────────────────────────────────────────┘

Claude Code: Saves the approved code
发现问题时:
Tetrad Response:
┌─────────────────────────────────────────────┐
│ DECISION: BLOCK ✗                           │
│ Score: 26/100                               │
│ Consensus: Yes (3/3 rejected)               │
│                                             │
│ Votes:                                      │
│   • Codex:  Fail (30) - division by zero    │
│   • Gemini: Fail (25) - no error handling   │
│   • Qwen:   Fail (25) - unsafe operation    │
│                                             │
│ Issues:                                     │
│   - Division by zero not handled            │
│   - Missing input validation                │
│   - No Result/Option return type            │
└─────────────────────────────────────────────┘

Claude Code: Fixes the code and resubmits

CLI 命令

tetrad - Quadruple Consensus CLI for Claude Code

COMMANDS:
    init              Initialize configuration in current directory
    serve             Start the MCP server (used by Claude Code)
    status            Show CLI status (codex, gemini, qwen)
    config            Configure options interactively
    doctor            Diagnose configuration issues
    version           Show version
    evaluate          Evaluate code manually (without MCP)
    history           Show evaluation history from ReasoningBank
    export            Export patterns from ReasoningBank
    import            Import patterns into ReasoningBank

OPTIONS:
    -c, --config <FILE>    Configuration file (default: tetrad.toml)
    -v, --verbose          Verbose mode
    -q, --quiet            Quiet mode
    -h, --help             Show help

MCP 工具

作为 MCP 服务运行时,Tetrad 会提供 6 个工具:

工具说明
tetrad_review_plan在编码前审查实现计划
tetrad_review_code在保存前审查代码
tetrad_review_tests在最终确定前审查测试
tetrad_confirm确认是否同意收到的反馈
tetrad_final_check提交前进行最终验证
tetrad_status检查评估器的运行状况
工作流示例
1. Claude Code generates plan → tetrad_review_plan → Feedback
2. Claude Code implements   → tetrad_review_code → Feedback
3. Claude Code adjusts      → tetrad_confirm     → Confirmation
4. Claude Code finalizes    → tetrad_final_check → Certificate

架构

Claude Code → MCP Protocol (stdio) → Tetrad Server (Rust)
                                          │
                    ┌─────────────────────┼─────────────────────┐
                    ▼                     ▼                     ▼
              Codex CLI            Gemini CLI              Qwen CLI
              (syntax)            (architecture)           (logic)
                    │                     │                     │
                    └─────────────────────┼─────────────────────┘
                                          ▼
                                  Consensus Engine
                                          │
                            ┌─────────────┴─────────────┐
                            ▼                           ▼
                      LRU Cache                  ReasoningBank
                      (results)                    (SQLite)
                                    RETRIEVE→JUDGE→DISTILL→CONSOLIDATE
执行器专长
执行器CLI专长
Codexcodex exec --json语法和代码规范
Geminigemini -o json架构和设计
Qwenqwen逻辑错误和正确性
共识规则
规则要求使用场景
Golden一致同意(3/3)关键代码、安全性
Strong3/3,或高置信度的 2/3默认
Weak简单多数(2/3)快速原型开发

ReasoningBank

ReasoningBank 是一个持续学习系统,用于存储和整合代码模式:

学习周期
RETRIEVE → JUDGE → DISTILL → CONSOLIDATE
    │         │        │           │
    │         │        │           └─ Merge similar patterns
    │         │        └─ Extract new patterns
    │         └─ Evaluate code with context
    └─ Search for relevant patterns
模式类型
  • AntiPattern:应避免的模式(错误、漏洞、代码异味)
  • GoodPattern:应遵循的模式(最佳实践、惯用模式)
  • Ambiguous:分类不确定的模式(需要更多数据)
ReasoningBank 命令
# View evaluation history
tetrad history --limit 50

# Export patterns to share
tetrad export -o team-patterns.json

# Import patterns from another ReasoningBank
tetrad import team-patterns.json

配置

运行 tetrad init 时会自动创建 tetrad.toml 文件:

[general]
log_level = "info"
timeout_secs = 60

[executors.codex]
enabled = true
command = "codex"
args = ["exec", "--json"]
timeout_secs = 30

[executors.gemini]
enabled = true
command = "gemini"
args = ["-o", "json"]
timeout_secs = 30

[executors.qwen]
enabled = true
command = "qwen"
args = []
timeout_secs = 30

[consensus]
default_rule = "strong"
min_score = 70
max_loops = 3

[reasoning]
enabled = true
db_path = ".tetrad/tetrad.db"
max_patterns_per_query = 10
consolidation_interval = 100

[cache]
enabled = true
capacity = 1000
ttl_secs = 300
交互式配置

使用 tetrad config 进行交互式配置:

🔧 Tetrad Interactive Configuration

What would you like to configure?
❯ General Settings
  Executors (Codex, Gemini, Qwen)
  Consensus
  ReasoningBank
  Save and Exit
  Exit without Saving

LRU 缓存

系统包含一个 LRU 缓存,用于避免不必要的重新评估:

  • 容量:可配置(默认:1000 条)
  • TTL:可配置的生存时间(默认:5 分钟)
  • 键:代码 + 语言 + 评估类型的哈希值
  • 失效:按 TTL 自动失效,也可手动失效

Hook 系统

Hook 可在特定时机自定义行为:

Hook时机用途
pre_evaluate评估前修改请求,跳过评估
post_evaluate评估后日志记录、指标、通知
on_consensus达成共识时批准后自动执行操作
on_block代码被阻止时告警、自动回滚
内置 Hook
  • LoggingHook:记录所有评估
  • MetricsHook:收集使用统计信息

项目结构

tetrad/
├── Cargo.toml              # Crate manifest
├── CLAUDE.md               # Documentation for Claude Code
├── README.md               # This file
├── Tetrad.md               # Complete specification
├── src/
│   ├── main.rs             # Entry point (CLI)
│   ├── lib.rs              # Exportable library
│   ├── cli/
│   │   ├── mod.rs          # CLI definition with clap
│   │   ├── commands.rs     # Command implementations
│   │   └── interactive.rs  # Interactive configuration (dialoguer)
│   ├── executors/
│   │   ├── mod.rs
│   │   ├── base.rs         # CliExecutor trait
│   │   ├── codex.rs        # Codex executor
│   │   ├── gemini.rs       # Gemini executor
│   │   └── qwen.rs         # Qwen executor
│   ├── types/
│   │   ├── mod.rs
│   │   ├── config.rs       # TOML configuration
│   │   ├── errors.rs       # TetradError/TetradResult
│   │   ├── requests.rs     # EvaluationRequest
│   │   └── responses.rs    # EvaluationResult, ModelVote
│   ├── consensus/
│   │   ├── mod.rs          # Exports
│   │   ├── engine.rs       # ConsensusEngine
│   │   ├── aggregator.rs   # Vote aggregation
│   │   └── rules.rs        # Voting rules
│   ├── reasoning/
│   │   ├── mod.rs          # Exports
│   │   ├── bank.rs         # ReasoningBank
│   │   ├── patterns.rs     # Pattern types
│   │   ├── sqlite.rs       # SQLite storage
│   │   └── export.rs       # Import/Export
│   ├── mcp/
│   │   ├── mod.rs          # Exports
│   │   ├── server.rs       # MCP server
│   │   ├── protocol.rs     # JSON-RPC types
│   │   ├── tools.rs        # Tool handlers
│   │   └── transport.rs    # Stdio transport
│   ├── cache/
│   │   ├── mod.rs          # Exports
│   │   └── lru.rs          # LRU cache
│   └── hooks/
│       ├── mod.rs          # Hook trait and HookSystem
│       └── builtin.rs      # Default hooks
└── tests/
    ├── cli_integration.rs
    ├── consensus_integration.rs
    ├── mcp_integration.rs
    └── reasoning_integration.rs

开发

# Build
cargo build
cargo build --release

# Tests
cargo test                          # All tests
cargo test --lib                    # Unit tests only
cargo test --tests                  # Integration tests only

# Lint
cargo clippy --all-targets --all-features -- -D warnings

# Format
cargo fmt
cargo fmt --check

# Documentation
cargo doc --open

# Run CLI
cargo run -- status
cargo run -- doctor
cargo run -- version
cargo run -- config

故障排除

“找不到 CLI”
# Check if CLIs are in PATH
which codex
which gemini
which qwen

# Check configuration
tetrad doctor
“stdin is not a terminal”(Codex)

确保配置使用 exec --json:

[executors.codex]
args = ["exec", "--json"]
“Response does not contain valid JSON”(Gemini)

确保配置使用 -o json:

[executors.gemini]
args = ["-o", "json"]
在 Claude Code 中检查 MCP 状态

在 Claude Code 中,运行:

/mcp

前置条件

要使用 Tetrad,你至少需要安装并完成身份验证的 AI CLI:

CLI安装无需 API 密钥即可验证?免费额度
Codex CLInpm i -g @openai/codex✅ ChatGPT Plus/Pro/Business通过订阅
Gemini CLInpm i -g @google/gemini-cli✅ Google 账号每天 1,000 次请求
Qwen CLInpm i -g qwen-code❌ 需要 DashScope 密钥每天 2,000 次请求

运行以下命令检查是否可用:

tetrad status
tetrad doctor

参与贡献

欢迎贡献!欢迎提交 Pull Request。

  1. Fork 此仓库
  2. 创建功能分支(git checkout -b feature/amazing-feature)
  3. 提交更改(git commit -m 'Add some amazing feature')
  4. 将更改推送到分支(git push origin feature/amazing-feature)
  5. 创建 Pull Request

许可证

MIT

作者

SamoraDC


链接:

评论

支持 Markdown

第一次接触 MCP?

从协议是什么,到在客户端里装上第一个服务,这几条回答覆盖了大多数入门问题。

一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。