Tetrad

io.github.SamoraDC由 GitHub 帳號 SamoraDC 發布v0.1.12更新於 Nov 10, 2026

Quadruple consensus MCP server for code validation using Codex, Gemini, and Qwen

已驗證STDIO僅桌面開發者工具AI 與機器學習

概覽

AI 產生的概覽

Tetrad 會把程式碼、方案與測試交給 Codex、Gemini、Qwen 三個外部 AI 命令列評估器審查,並在 Claude Code 儲存或提交前回傳共識結論。

可以做什麼
Tetrad 是一個本機 MCP 伺服器,提供六個工具:tetrad_review_plan、tetrad_review_code、tetrad_review_tests、tetrad_confirm、tetrad_final_check 與 tetrad_status。它會把提交的內容轉送給 Codex、Gemini 與 Qwen 命令列工具,收集各自的投票與評分,再依可設定的共識規則(全體一致、強共識或簡單多數)回傳 PASS 或 BLOCK 以及修改建議。結果會寫入 LRU 快取,並存入以 SQLite 為基礎的 ReasoningBank,跨工作階段記錄良好模式與反模式。
適用情境
當你希望在 AI 產生的程式碼被儲存或提交前取得自動化的第二意見時使用,特別適合關鍵或涉及安全性的變更。它也適合已經擁有底層 AI 命令列工具訂閱或 API 存取權,並想在 Claude Code 內設置審查關卡的團隊。
執行需求
以本機 stdio 程序執行,通常透過 npx @samoradc/tetrad serve 啟動;npm 套件需要 Node.js。必須至少安裝並登入一個外部命令列工具:Codex CLI、Gemini CLI 或 Qwen CLI。憑證可透過 OPENAI_API_KEY、GEMINI_API_KEY、GOOGLE_API_KEY 或 DASHSCOPE_API_KEY 等環境變數提供,也可使用各命令列工具內建的登入流程。需要能連線至對應 AI 服務商的網路。
安裝前請注意
你提交的程式碼、方案與測試會經由所設定的命令列工具傳送給第三方 AI 服務商,因此除非可以接受,否則不要用於機密或受監管的內容。它需要 OPENAI_API_KEY、GEMINI_API_KEY、GOOGLE_API_KEY 或 DASHSCOPE_API_KEY 等憑證,這些憑證會從環境變數讀取。評估會消耗服務商配額或付費額度。伺服器會在專案目錄中寫入本機 SQLite 資料庫與設定檔。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Tetrad,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

Tetrad

[CI] [MCP Registry] [npm] [Crates.io] [Rust] [License: MIT]

Quadruple Consensus MCP Server for Claude Code

Tetrad is a high-performance MCP (Model Context Protocol) server written in Rust that orchestrates three AI-powered CLI code evaluation tools (Codex, Gemini CLI, Qwen) to validate all code produced by Claude Code.

The system implements a quadruple consensus protocol where no code or plan is accepted without approval from four intelligences: the three external evaluators + Claude Code itself.

Features

  • Quadruple Consensus: 4 AI models must agree to approve code
  • ReasoningBank: Continuous learning system with RETRIEVE→JUDGE→DISTILL→CONSOLIDATE cycle
  • High Performance: Written in Rust with parallel execution via Tokio
  • MCP Server: JSON-RPC 2.0 server over stdio for Claude Code integration
  • Full CLI: Intuitive commands (init, serve, status, doctor, config, etc.)
  • LRU Cache: Result caching with configurable TTL
  • Hook System: Pre/post evaluation callbacks for customization
  • Extensible: Plugin system for custom executors
  • Cross-session: SQLite persistence for patterns and history

Quick Start

1. Install Tetrad

bash
# Via npm (recommended - works seamlessly with Claude Code)npm install -g @samoradc/tetrad
# Or via cargo (requires additional setup)cargo install tetradsudo cp ~/.cargo/bin/tetrad /usr/local/bin/

1.1 Initialize in Your Project (Optional)

bash
npx @samoradc/tetrad init

This will:

  • Create tetrad.toml configuration file
  • Create .tetrad/ directory for the database
  • Add .tetrad/ to your .gitignore

2. Install and Configure External CLI Tools

Tetrad requires at least one of the following AI CLI tools. Good news: you don't need separate API keys if you have existing subscriptions!

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

Authentication options:

MethodRequirementsAPI Key Needed?
ChatGPT LoginChatGPT Plus, Pro, Business, Edu, or Enterprise subscriptionNo
API KeyOpenAI API account with creditsYes
bash
# Option 1: Login with your ChatGPT subscription (recommended)codex login# Opens browser for OAuth - follow the prompts
# Option 2: Use API keyexport OPENAI_API_KEY="your-openai-key"

Note: For headless/remote servers, use codex login --device-auth and follow the device code flow.

📖 Codex CLI Authentication Docs


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

Authentication options:

MethodRequirementsAPI Key Needed?Free Tier
Google LoginPersonal Google accountNo60 req/min, 1,000 req/day
API KeyGoogle AI Studio accountYesSame limits
bash
# 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 Studioexport GEMINI_API_KEY="your-gemini-key"

Free Tier: With a personal Google account, you get access to Gemini 2.5 Pro with 1M token context window at no cost!

📖 Gemini CLI Authentication Docs


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

Authentication options:

MethodRequirementsAPI Key Needed?Free Tier
DashScope APIAlibaba Cloud accountYes2,000 req/day
Coding PlanQwen Coding subscriptionYes (different format)Included
bash
# Get your API key from DashScope consoleexport DASHSCOPE_API_KEY="your-dashscope-key"
# For international users (outside China)export OPENAI_BASE_URL="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"

Regional Endpoints:

  • Singapore: dashscope-intl.aliyuncs.com
  • Virginia: dashscope-us.aliyuncs.com
  • Beijing: dashscope.aliyuncs.com

📖 Qwen API Docs

3. Verify Installation

bash
# Check Tetrad versiontetrad version
# Check CLI availabilitytetrad status
# Diagnose any issuestetrad doctor

4. Add to Claude Code CLI

bash
# Add Tetrad as MCP server (all projects)claude mcp add --scope user tetrad -- npx @samoradc/tetrad serve
# Verify it's configuredclaude mcp list
Alternative installation methods
bash
# Current project onlyclaude mcp add tetrad -- npx @samoradc/tetrad serve
# If installed via cargoclaude mcp add --scope user tetrad -- tetrad serve

Note: Tetrad is published on the MCP Registry for discoverability and documentation.

5. Alternative: Manual Configuration

Create or edit .mcp.json in your project root:

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}"      }    }  }}

Or for global user configuration in ~/.claude.json (mcpServers section):

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

How It Works

When you ask Claude Code to write code, Tetrad automatically validates it:

You: "Create a function in Rust that calculates the average of a vector"
Claude Code:1. Writes the code2. Calls tetrad_review_code automatically3. Tetrad sends to Codex, Gemini and Qwen for evaluation4. 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

When Issues Are Found:

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 Commands

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 Tools

When running as MCP server, Tetrad exposes 6 tools:

ToolDescription
tetrad_review_planReview implementation plans before coding
tetrad_review_codeReview code before saving
tetrad_review_testsReview tests before finalizing
tetrad_confirmConfirm agreement with received feedback
tetrad_final_checkFinal verification before commit
tetrad_statusCheck health of evaluators

Workflow Example

1. Claude Code generates plan → tetrad_review_plan → Feedback2. Claude Code implements   → tetrad_review_code → Feedback3. Claude Code adjusts      → tetrad_confirm     → Confirmation4. Claude Code finalizes    → tetrad_final_check → Certificate

Architecture

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

Executor Specializations

ExecutorCLISpecialization
Codexcodex exec --jsonSyntax and code conventions
Geminigemini -o jsonArchitecture and design
QwenqwenLogic bugs and correctness

Consensus Rules

RuleRequirementUse Case
GoldenUnanimity (3/3)Critical code, security
Strong3/3 or 2/3 with high confidenceDefault
WeakSimple majority (2/3)Rapid prototyping

ReasoningBank

The ReasoningBank is a continuous learning system that stores and consolidates code patterns:

Learning Cycle

RETRIEVE → JUDGE → DISTILL → CONSOLIDATE    │         │        │           │    │         │        │           └─ Merge similar patterns    │         │        └─ Extract new patterns    │         └─ Evaluate code with context    └─ Search for relevant patterns

Pattern Types

  • AntiPattern: Patterns to avoid (bugs, vulnerabilities, code smells)
  • GoodPattern: Patterns to follow (best practices, idiomatic patterns)
  • Ambiguous: Patterns with uncertain classification (needs more data)

ReasoningBank Commands

bash
# View evaluation historytetrad history --limit 50
# Export patterns to sharetetrad export -o team-patterns.json
# Import patterns from another ReasoningBanktetrad import team-patterns.json

Configuration

The tetrad.toml file is created automatically with tetrad init:

toml
[general]log_level = "info"timeout_secs = 60
[executors.codex]enabled = truecommand = "codex"args = ["exec", "--json"]timeout_secs = 30
[executors.gemini]enabled = truecommand = "gemini"args = ["-o", "json"]timeout_secs = 30
[executors.qwen]enabled = truecommand = "qwen"args = []timeout_secs = 30
[consensus]default_rule = "strong"min_score = 70max_loops = 3
[reasoning]enabled = truedb_path = ".tetrad/tetrad.db"max_patterns_per_query = 10consolidation_interval = 100
[cache]enabled = truecapacity = 1000ttl_secs = 300

Interactive Configuration

Use tetrad config for interactive configuration:

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

LRU Cache

The system includes an LRU cache to avoid unnecessary re-evaluations:

  • Capacity: Configurable (default: 1000 entries)
  • TTL: Configurable time-to-live (default: 5 minutes)
  • Key: Hash of code + language + evaluation type
  • Invalidation: Automatic by TTL or manual

Hook System

Hooks allow customizing behavior at specific points:

HookWhenUse
pre_evaluateBefore evaluationModify request, skip evaluation
post_evaluateAfter evaluationLogging, metrics, notifications
on_consensusWhen consensus reachedAutomatic actions on approval
on_blockWhen code blockedAlerts, automatic rollback

Built-in Hooks

  • LoggingHook: Records all evaluations
  • MetricsHook: Collects usage statistics

Project Structure

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

Development

bash
# Buildcargo buildcargo build --release
# Testscargo test                          # All testscargo test --lib                    # Unit tests onlycargo test --tests                  # Integration tests only
# Lintcargo clippy --all-targets --all-features -- -D warnings
# Formatcargo fmtcargo fmt --check
# Documentationcargo doc --open
# Run CLIcargo run -- statuscargo run -- doctorcargo run -- versioncargo run -- config

Troubleshooting

"CLI not found"

bash
# Check if CLIs are in PATHwhich codexwhich geminiwhich qwen
# Check configurationtetrad doctor

"stdin is not a terminal" (Codex)

Make sure your config uses exec --json:

toml
[executors.codex]args = ["exec", "--json"]

"Response does not contain valid JSON" (Gemini)

Make sure your config uses -o json:

toml
[executors.gemini]args = ["-o", "json"]

Check MCP status in Claude Code

Inside Claude Code, run:

/mcp

Prerequisites

To use Tetrad, you need at least one of the AI CLIs installed and authenticated:

CLIInstallationAuth Without API Key?Free Tier
Codex CLInpm i -g @openai/codex✅ ChatGPT Plus/Pro/BusinessVia subscription
Gemini CLInpm i -g @google/gemini-cli✅ Google account1,000 req/day
Qwen CLInpm i -g qwen-code❌ DashScope key required2,000 req/day

Check availability with:

bash
tetrad statustetrad doctor

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

MIT

Author

SamoraDC


Links:

來源:README.md,提交 dc5874e

工具

0
SourceWeft 尚未在沙箱中啟動過該軟體包,因此其工具未知。

版本歷史

1
  1. v0.1.12最新Sep 16, 2026

評分

已滿足適用檢查項的 50%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分

    請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。

  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具15 分

    請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。

  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分