1. 專案定位與核心價值

1.1 PAL MCP 是什麼

PAL MCP Server(Provider Abstraction Layer for Model Context Protocol)是一個開源 MCP 伺服器,讓你在 Claude Code、Gemini CLI、Codex CLI、Cursor 等 AI 開發工具內同時調度多個 AI 模型,實現真正的多模型協作開發。

核心概念:「一個 context,多個模型」。你不需要在不同工具之間切換,就能讓 Gemini 做 code review、O3 做 debug、GPT-5 做 planning,而且對話脈絡在工具之間自動延續

1.2 解決什麼問題

痛點PAL MCP 的解法
只能用一個模型一次 prompt 調度多個 provider 的模型
Context 切換成本高對話延續(Conversation Continuity)跨工具保留上下文
模型選擇困難Auto mode(DEFAULT_MODEL=auto)自動為每個任務挑選最適合的模型
CLI 之間無法互通clink 工具讓 Claude Code 可 spawn Gemini CLI 子代理,反之亦然
工具功能零散18 個專精工具涵蓋 code review、debug、planning、security audit、consensus

1.3 適用對象

  • 已在使用 Claude Code / Gemini CLI / Codex CLI 的開發者
  • 想要多模型 second opinion 的技術團隊
  • 需要系統化 code review / security audit 流程的專案
  • 想要在 Cursor / VS Code 中整合多模型能力的 IDE 使用者

2. 安裝指南

2.1 系統需求

  • Python 3.10+
  • Git
  • uv(推薦)或 pip
  • 至少一個 AI 模型 API key(Gemini / OpenAI / OpenRouter / Azure / X.AI / Ollama)

2.2 方法 A:Clone + 自動安裝(推薦)

1git clone https://github.com/BeehiveInnovations/pal-mcp-server.git
2cd pal-mcp-server
3
4# 一鍵完成:建 venv、安裝依賴、設定 .env、自動偵測並設定 Claude/Gemini/Codex CLI
5./run-server.sh

run-server.sh 會自動:

  1. 建立 .pal_venv 虛擬環境
  2. 安裝 requirements.txt 依賴
  3. 引導你設定 API keys 到 .env
  4. 偵測並設定 Claude Desktop、Claude Code、Gemini CLI、Codex CLI、Qwen CLI

2.3 方法 B:uvx 即時安裝(零 clone)

在 Claude Code 的 ~/.claude/settings.json 或專案 .mcp.json 中加入:

 1{
 2  "mcpServers": {
 3    "pal": {
 4      "command": "bash",
 5      "args": ["-c", "for p in $(which uvx 2>/dev/null) $HOME/.local/bin/uvx /opt/homebrew/bin/uvx /usr/local/bin/uvx uvx; do [ -x \"$p\" ] && exec \"$p\" --from git+https://github.com/BeehiveInnovations/pal-mcp-server.git pal-mcp-server; done; echo 'uvx not found' >&2; exit 1"],
 6      "env": {
 7        "GEMINI_API_KEY": "your-key",
 8        "OPENAI_API_KEY": "your-key",
 9        "DISABLED_TOOLS": "analyze,refactor,testgen,secaudit,docgen,tracer",
10        "DEFAULT_MODEL": "auto"
11      }
12    }
13  }
14}

2.4 方法 C:Docker 部署

1cd pal-mcp-server
2docker compose up -d

Docker 部署適合需要隔離環境或團隊共用的場景。詳見 docs/docker-deployment.md

2.5 API Key 設定

.env 中設定你有的 provider API key(至少一個):

1GEMINI_API_KEY=your-gemini-key
2OPENAI_API_KEY=your-openai-key
3OPENROUTER_API_KEY=your-openrouter-key
4XAI_API_KEY=your-xai-key
5# Azure 需額外設定 endpoint
6AZURE_OPENAI_API_KEY=your-azure-key
7AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/

PAL 會自動啟用有 API key 的 provider,無 key 的 provider 會被跳過。

2.6 驗證安裝

安裝完成後,在 Claude Code 中測試:

1use pal listmodels to show available models

如果看到模型清單,表示安裝成功。


3. 核心架構解析

3.1 系統架構圖


graph TB
    subgraph Clients["AI CLI 客戶端"]
        CC[Claude Code]
        GC[Gemini CLI]
        CX[Codex CLI]
        CU[Cursor / VS Code]
    end

    subgraph PAL["PAL MCP Server (server.py)"]
        MCP[MCP Protocol Layer
stdio JSON-RPC] TR[Tool Registry
18 tools] RH[Request Handler] CM[Conversation Memory
跨工具對話延續] end subgraph Tools["工具層 (tools/)"] T1[chat / thinkdeep / planner] T2[codereview / debug / precommit] T3[consensus / clink] T4[secaudit / refactor / testgen] T5[apilookup / challenge / tracer] end subgraph Providers["Provider 層 (providers/)"] PR[ModelProviderRegistry] P1[GeminiProvider] P2[OpenAIProvider] P3[AzureProvider] P4[OpenRouterProvider] P5[XAIProvider] P6[DIALProvider] P7[CustomProvider] end subgraph External["外部 AI 模型"] E1[Gemini 3.0 Pro] E2[GPT-5 / O3] E3[Grok-4] E4[Ollama 本地模型] end CC & GC & CX & CU -->|stdio| MCP MCP --> TR TR --> RH RH --> CM RH --> T1 & T2 & T3 & T4 & T5 T1 & T2 & T3 & T4 & T5 --> PR PR --> P1 & P2 & P3 & P4 & P5 & P6 & P7 P1 --> E1 P2 --> E2 P5 --> E3 P7 --> E4

3.2 核心組件說明

MCP Protocol Layer (server.py)

  • 實作 MCP 規格的 stdio 通訊(JSON-RPC over stdin/stdout)
  • 負責 tool discovery(handle_list_tools)和 tool invocation(handle_call_tool
  • 啟動時根據 .env 的 API keys 自動初始化對應 provider

Tool Registry(tools/

  • 18 個獨立工具,每個都有自己的 Pydantic request model 和 response schema
  • 分為「預設啟用」和「預設停用」兩組,透過 DISABLED_TOOLS 環境變數控制
  • 預設啟用:chat, thinkdeep, planner, consensus, codereview, precommit, debug, apilookup, challenge, clink

Provider Registry(providers/

  • ModelProviderRegistry:單例模式,管理所有已啟用的 provider
  • 每個 provider 繼承 BaseModelProvider,實作 generate_content() 非同步方法
  • 支援 model alias resolution(如 progemini-3.0-pro)和 auto mode 智慧選模型

Conversation Memory(utils/conversation_memory.py

  • 跨工具的對話歷史管理,支援 multi-turn conversation
  • Token budgeting:自動計算剩餘 token 預算,避免超出 context window
  • File deduplication:已在對話中出現的檔案不重複傳送

CLink Bridge(clink/

  • 透過 asyncio.create_subprocess_exec spawn 外部 CLI
  • 支援 Claude、Gemini CLI、Codex CLI 三種客戶端(conf/cli_clients/*.json
  • 每個客戶端可設定多個 role(如 planner, codereviewer),各有專屬 system prompt

3.3 請求處理流程

  1. Claude Code 發出 MCP tool call(如 pal__chat
  2. server.pyhandle_call_tool 解析 arguments,包含 model 指定
  3. parse_model_option 解析 model string(如 gemini-3.0-pro
  4. Tool 執行邏輯:建構 prompt → 透過 ModelProviderRegistry 路由到正確 provider
  5. Provider 呼叫外部 API → 回傳結果
  6. 結果寫入 ConversationMemory → 回傳 TextContent 給 MCP client

3.4 Auto Mode 運作原理

DEFAULT_MODEL=auto 時,PAL 不會指定固定模型,而是:

  1. 每個 tool 有自己的 ToolModelCategory(如 analytical, balanced, creative)
  2. 由 Claude(或其他 host CLI)根據任務類型自動選擇最適合的模型
  3. 工具的 schema 描述中會包含可用模型清單,讓 host CLI 做出選擇

4. 核心工具詳細用法

4.1 協作規劃工具

chat — 多模型對話與 brainstorming

1# 基本用法:用 Gemini Pro 討論架構決策
2Use pal chat with gemini pro: should we use Redis or Memcached for session storage?
3
4# 帶檔案的對話:讓外部模型讀你的程式碼
5Use pal chat with o3 about the auth module, share files: src/auth.py src/middleware.py
6
7# 多輪對話延續
8Use pal chat to continue: what about the edge cases you mentioned?

thinkdeep — 延伸推理與深度分析

1# 深度分析架構問題
2Use pal thinkdeep with high thinking mode: analyze the trade-offs of our current microservices architecture
3
4# 邊界案例分析
5Use pal thinkdeep: what edge cases could break our payment processing pipeline?

planner — 結構化任務拆解

1# 建立遷移計畫
2Use pal planner: break down the monolith-to-microservices migration into phases
3
4# 持續規劃(多步驟)
5Use pal planner to continue planning from step 3

consensus — 多模型共識決策

1# 從兩個模型取得共識
2Use pal consensus with gemini pro and o3: should we adopt GraphQL or stick with REST?
3
4# 帶立場引導(stance steering)
5Use pal consensus with stance "favor simplicity": evaluate these three database options
1# 從 Claude Code 中 spawn Gemini CLI 做 code review
2Use pal clink with cli_name="gemini" role="codereviewer" to review the auth module
3
4# Spawn Codex 子代理做安全稽核
5Use pal clink with codex to audit this project for supply chain vulnerabilities
6
7# 自訂 role
8Use pal clink with gemini role="planner" to create a rollout plan for the new API version

CLink 的特色是context isolation:子代理在獨立的 context 中執行,不會汙染你的主 session。結果會被摘要後回傳。

4.2 程式碼品質工具

codereview — 系統化 Code Review

1# 基本 review
2Use pal codereview: review the changes in src/api/
3
4# 指定模型 + 聚焦方向
5Use pal codereview with gemini pro focusing on performance and memory leaks

debug — 系統化 Root Cause 分析

1# debug 錯誤
2Use pal debug: getting "ConnectionRefusedError" when connecting to Redis cluster
3
4# 帶 log 的 debug
5Use pal debug with files: logs/error.log src/cache.py

precommit — Pre-commit 驗證

1# commit 前驗證
2Use pal precommit: validate the changes I'm about to commit

4.3 開發工具(預設停用,需在 DISABLED_TOOLS 中移除)

secaudit — OWASP Top 10 資安稽核

1# 啟用後使用
2Use pal secaudit: audit the authentication and authorization modules

testgen — 測試生成

1Use pal testgen: generate comprehensive tests for src/auth/

refactor — 智慧重構

1Use pal refactor: decompose this 500-line function into smaller modules

4.4 實用工具

apilookup — API 文件即時查詢

1# 查詢最新 API 用法(不依賴訓練資料)
2Use pal apilookup: what's the latest Stripe API for creating subscriptions?

challenge — 批判性分析

1# 防止 "You're absolutely right!" 回應
2Use pal challenge: critically evaluate my proposed database schema

5. 應用場景

5.1 場景一:多模型 Code Review 工作流

情境:你完成了一個新功能,想要從不同角度取得 review feedback。

 1# Step 1: 用 Gemini Pro 做結構性 review
 2Use pal codereview with gemini pro: review src/payments/ focusing on architecture
 3
 4# Step 2: 用 O3 做安全性 review
 5Use pal codereview with o3: review src/payments/ focusing on security vulnerabilities
 6
 7# Step 3: 建立共識
 8Use pal consensus: which review findings should be prioritized?
 9
10# Step 4: 建立修復計畫
11Use pal planner: create a fix plan based on the code review findings

5.2 場景二:協作 Debug

情境:生產環境出現間歇性 race condition。

1# Step 1: 深度分析
2Use pal debug with max thinking: race condition in order processing, errors attached
3
4# Step 2: 取得第二意見
5Use pal chat with gemini pro: do you agree with the root cause analysis? Here's what we found...
6
7# Step 3: 驗證修復
8Use pal precommit: validate the race condition fix before committing

情境:你在 Claude Code 中工作,但想讓 Gemini CLI 用它的 planning 能力來規劃。

1# Gemini CLI 規劃 → Claude Code 實作
2Use pal clink with gemini role="planner" to design the API migration strategy
3# Gemini CLI 在獨立 context 中規劃,結果回傳 Claude Code
4# 然後你在 Claude Code 中實作

5.4 場景四:新專案啟動

1# Step 1: 架構規劃
2Use pal planner with gemini pro: plan a new real-time notification system
3
4# Step 2: 多模型架構決策
5Use pal consensus with pro and o3: WebSocket vs SSE vs long polling for real-time notifications
6
7# Step 3: 安全考量
8Use pal thinkdeep: what security implications should we consider for the notification system?

6. 資安掃描報告

6.1 掃描範圍

掃描 server.pytools/providers/utils/clink/ 目錄下的所有 .py 檔案。

6.2 掃描結果

子程序執行(subprocess)

風險位置說明
🟡 中clink/agents/base.py:111使用 asyncio.create_subprocess_exec spawn 外部 CLI。雖然使用 exec(非 shell)形式較安全,但命令來自使用者 prompt,需注意 prompt injection
🟢 低docker/scripts/healthcheck.py:22subprocess.run(["pgrep", "-f", "server.py"]) — 硬編碼指令,無注入風險

動態載入

風險位置說明
🟢 低docker/scripts/healthcheck.py:35__import__(module) 用於 Docker healthcheck 模組檢測,非使用者可控
🟢 低providers/openai_compatible.py:776ast.literal_eval 用於解析 JSON-like 錯誤回應,literal_eval 是安全的(不執行任意程式碼)

檔案存取安全

風險位置說明
🟢 低utils/security_config.py完整的 path traversal 防護:DANGEROUS_SYSTEM_PATHS 黑名單 + is_dangerous_path() 檢查 + symlink resolve
🟢 低utils/file_utils.pyresolve_and_validate_path() 實作三步驗證:展開路徑 → resolve symlink → 檢查危險路徑。PR #353 修復了 macOS symlink 系統目錄的邊界案例

網路通訊

風險位置說明
🟢 低providers/*.py透過 httpx.Client + openai SDK 連接 AI 模型 API,使用 HTTPS + timeout 設定
🟢 低tools/version.pyurllib.request.urlopen 檢查新版本,僅 GET 請求到 GitHub API

API Key 管理

風險位置說明
🟢 低config.py / utils/env.pyAPI keys 透過 .env + python-dotenv 載入,不硬編碼。.env.example 提供範本

已知安全議題

風險來源說明
🟡 中Issue #417「Untrusted Prompt Forwarding Enables Arbitrary File Modification via CLI Integration」— CLink 將 prompt 轉發給外部 CLI 時,若 prompt 含惡意指令,可能導致檔案被修改。這是 prompt injection 的固有風險
🟡 中Issue #395ConsensusTool 使用 singleton mutable state,concurrent callers 可能互相覆寫。屬於 race condition bug,非直接安全漏洞

6.3 綜合評估

整體風險等級:🟢 低(附帶 2 個中等注意事項)

PAL MCP Server 的安全設計相對成熟:

  • 檔案存取有完整的 path traversal 防護(含 symlink resolve)
  • 子程序執行使用 exec 形式(非 shell=True
  • API keys 透過環境變數管理,不硬編碼
  • 主要風險在於 CLink prompt forwarding(Issue #417),這是所有 CLI bridge 工具的固有挑戰

7. FAQ(常見問題)

Q1: PAL MCP 跟直接用 Claude Code 有什麼差別?

Claude Code 只能用 Anthropic 的模型。PAL MCP 讓你在 Claude Code 內同時使用 Gemini、OpenAI、Grok 等多個模型,並保持對話延續。

Q2: Auto mode 怎麼運作?

設定 DEFAULT_MODEL=auto 後,PAL 會在工具的 schema 中列出所有可用模型。Claude(或其他 host CLI)會根據任務類型自動選擇最適合的模型。

CLink 的核心價值是 context isolation。它在 Claude Code session 內 spawn 一個獨立的 Gemini CLI 子代理,子代理的工作不會汙染你的主 context window。結果會被摘要後回傳。

Q4: 可以用本地模型(Ollama)嗎?

可以。設定 CUSTOM_API_KEY + CUSTOM_API_BASE 指向你的 Ollama 端點即可。詳見 docs/custom_models.md

Q5: DISABLED_TOOLS 有哪些工具可以停用?

預設停用:analyze, refactor, testgen, secaudit, docgen, tracer。無法停用:version, listmodels

Q6: 如何在 Windows 上使用?

推薦透過 WSL(Windows Subsystem for Linux)。詳見 docs/wsl-setup.md。也提供 run-server.ps1 PowerShell 腳本。

Q7: 對話紀錄會保留多久?

預設 CONVERSATION_TIMEOUT_HOURS=6,最多 MAX_CONVERSATION_TURNS=50 輪。可在 .env 中調整。


8. 進階技巧

8.1 Thinking Mode 控制

PAL 支援三種 thinking mode,控制模型的推理深度:

1# 深度推理(較慢、更精確)
2Use pal thinkdeep with high thinking mode: ...
3
4# 標準推理
5Use pal chat: ...
6
7# 輕量推理(較快、較便宜)
8Use pal chat with low thinking mode: ...

也可透過環境變數設定預設值:

1DEFAULT_THINKING_MODE_THINKDEEP=high
2DEFAULT_THINKING_MODE_CHAT=low

8.2 Per-tool Model 預設

你可以為每個工具設定不同的預設模型:

1# 在 .env 中
2DEFAULT_MODEL_CHAT=gemini-3.0-pro
3DEFAULT_MODEL_CODEREVIEW=o3
4DEFAULT_MODEL_DEBUG=gpt-5

8.3 Context Revival(對話復活)

當 context window 耗盡時,PAL 可以恢復之前的對話脈絡:

1Use pal chat to continue our previous discussion about the auth refactoring

詳見 docs/context-revival.md

8.4 大型 Prompt 處理

MCP 預設有 25K token 限制。PAL 內建大型 prompt 支援,自動分割處理超過限制的內容。詳見 docs/advanced-usage.md#working-with-large-prompts

你可以在 conf/cli_clients/ 新增自訂 CLI 客戶端設定:

 1{
 2  "name": "my-custom-cli",
 3  "command": "/path/to/my-cli",
 4  "additional_args": ["--mode", "headless"],
 5  "env": {},
 6  "roles": {
 7    "default": {
 8      "prompt_path": "systemprompts/clink/default.txt",
 9      "role_args": []
10    }
11  }
12}

也支援使用者層級設定(~/.config/pal-mcp/cli_clients/)。


9. 整合進其他工作流

9.1 整合 CI/CD Pipeline

PAL MCP 可以作為 CI/CD 中的 code review / security audit 節點:

1# GitHub Actions 範例概念
2- name: Security Audit with PAL
3  run: |
4    echo "Use pal secaudit: audit the changes in this PR" | claude --mcp pal

9.2 整合 AIKT 工作流

PAL MCP 可以作為 AIKT 的外部模型層,補強 Claude Code 的能力:

  1. gh-tutorial-qd 產出的教學文件 → 透過 pal chat 讓 Gemini Pro 做 second review
  2. paper-tutorial 的論文分析 → 透過 pal consensus 讓多個模型交叉驗證結論
  3. research-pipeline 的研究管線 → 透過 pal thinkdeep 做深度推理

9.3 團隊共用部署

透過 Docker 部署 PAL MCP Server,團隊成員各自在自己的 CLI 中連接:

1# docker-compose.yml 已提供
2docker compose up -d
3# 團隊成員在 MCP settings 中指向 server 位址

10. 重點摘要 Checklist

  • 安裝:Clone repo + ./run-server.sh 或 uvx 即時安裝
  • API Keys:至少設定一個 provider 的 API key(推薦 Gemini + OpenAI 雙 provider)
  • 驗證use pal listmodels 確認模型可用
  • 預設工具:10 個預設啟用(chat / thinkdeep / planner / consensus / codereview / precommit / debug / apilookup / challenge / clink)
  • Auto modeDEFAULT_MODEL=auto 讓 host CLI 自動選模型
  • CLink:用 clink spawn 外部 CLI 子代理做 isolated 任務
  • Consensus:用 consensus 讓多個模型辯論後達成共識
  • 資安:整體風險 🟢 低;注意 CLink prompt forwarding(Issue #417)
  • 對話延續:跨工具對話自動保留,CONVERSATION_TIMEOUT_HOURS 預設 6 小時
  • 停用工具DISABLED_TOOLS 控制啟用範圍,減少 context window 消耗

11. 進一步閱讀

資源說明
Getting Started完整安裝與設定指南
Advanced Usage進階功能:thinking mode、大型 prompt、model ranking
Configuration所有環境變數與設定選項
Tools Reference每個工具的詳細文件與範例
CLink GuideCLink CLI Bridge 完整指南
Custom Models自訂模型與 Ollama 設定
Docker DeploymentDocker 部署指南
Contributing貢獻指南與程式碼標準
Adding Providers新增 AI provider 指南
SECURITY.md安全政策與漏洞回報