Skip to content
Claude How To

MCP (模型脈絡協定, Model Context Protocol)

本資料夾包含與 Claude Code 一起使用 MCP 伺服器設定及說明的完整說明文件與範例。

概述 (Overview)

MCP (模型脈絡協定, Model Context Protocol) 是 Claude 存取外部工具、API 與即時資料源的標準化方式。與記憶 (Memory) 不同,MCP 提供對動態變化資料的即時存取。

主要特性:

  • 即時存取外部服務
  • 即時資料同步 (Live Data Synchronization)
  • 可擴充架構 (Extensible Architecture)
  • 安全驗證 (Secure Authentication)
  • 基於工具的互動 (Tool-based Interactions)

MCP 架構 (MCP Architecture)

mermaid
graph TB
    A["Claude"]
    B["MCP Server"]
    C["External Service"]

    A -->|Request: list_issues| B
    B -->|Query| C
    C -->|Data| B
    B -->|Response| A

    A -->|Request: create_issue| B
    B -->|Action| C
    C -->|Result| B
    B -->|Response| A

    style A fill:#e1f5fe,stroke:#333,color:#333
    style B fill:#f3e5f5,stroke:#333,color:#333
    style C fill:#e8f5e9,stroke:#333,color:#333

MCP 生態系統 (MCP Ecosystem)

mermaid
graph TB
    A["Claude"] -->|MCP| B["Filesystem<br/>MCP Server"]
    A -->|MCP| C["GitHub<br/>MCP Server"]
    A -->|MCP| D["Database<br/>MCP Server"]
    A -->|MCP| E["Slack<br/>MCP Server"]
    A -->|MCP| F["Google Docs<br/>MCP Server"]

    B -->|File I/O| G["Local Files"]
    C -->|API| H["GitHub Repos"]
    D -->|Query| I["PostgreSQL/MySQL"]
    E -->|Messages| J["Slack Workspace"]
    F -->|Docs| K["Google Drive"]

    style A fill:#e1f5fe,stroke:#333,color:#333
    style B fill:#f3e5f5,stroke:#333,color:#333
    style C fill:#f3e5f5,stroke:#333,color:#333
    style D fill:#f3e5f5,stroke:#333,color:#333
    style E fill:#f3e5f5,stroke:#333,color:#333
    style F fill:#f3e5f5,stroke:#333,color:#333
    style G fill:#e8f5e9,stroke:#333,color:#333
    style H fill:#e8f5e9,stroke:#333,color:#333
    style I fill:#e8f5e9,stroke:#333,color:#333
    style J fill:#e8f5e9,stroke:#333,color:#333
    style K fill:#e8f5e9,stroke:#333,color:#333

MCP 安裝方法 (MCP Installation Methods)

Claude Code 支援多種用於 MCP 伺服器連線的傳輸協定 (Transport Protocols):

HTTP 傳輸 (HTTP Transport, 推薦)

bash
# 基本 HTTP 連線
claude mcp add --transport http notion https://mcp.notion.com/mcp

# 帶有身份驗證標頭 (Authentication Header) 的 HTTP
claude mcp add --transport http secure-api https://api.example.com/mcp \
  --header "Authorization: Bearer your-token"

Stdio 傳輸 (Stdio Transport, 本地)

用於本地執行的 MCP 伺服器:

bash
# 本地 Node.js 伺服器
claude mcp add --transport stdio myserver -- npx @myorg/mcp-server

# 帶有環境變數
claude mcp add --transport stdio myserver --env KEY=value -- npx server

用於 stdio 伺服器的 CLAUDE_PROJECT_DIR (v2.1.139+)

每個 MCP stdio 伺服器在啟動時,其環境變數中都會預先設定好 CLAUDE_PROJECT_DIR=<儲存庫根目錄的絕對路徑> — 這與 Hook 所使用的慣例相同。擴充功能 (Plugins) 與專案的 .mcp.json 檔案可以在 commandargsenv 值中參照 ${CLAUDE_PROJECT_DIR},且變數替換會在 execve() 執行前完成:

json
{
  "mcpServers": {
    "repo-tools": {
      "type": "stdio",
      "command": "node",
      "args": ["${CLAUDE_PROJECT_DIR}/.claude/mcp/repo-tools.js"],
      "env": {
        "REPO_ROOT": "${CLAUDE_PROJECT_DIR}"
      }
    }
  }
}

當您的 stdio 伺服器需要讀取相對於專案根目錄的檔案時,無論 Claude Code 在何處啟動,都可以使用此功能。

stdio MCP 伺服器也會接收到 CLAUDE_CODE_SESSION_ID(與傳遞給 Hook 及 Bash 的值相符),包括透過 --resume 恢復工作階段時 (v2.1.163+)。

SSE 傳輸 (SSE Transport, 已廢棄)

伺服器發送事件 (Server-Sent Events) 傳輸已被廢棄,建議改用 http,但目前仍受支援:

bash
claude mcp add --transport sse legacy-server https://example.com/sse

WebSocket 傳輸 (ws) (WebSocket Transport)

WebSocket 伺服器保持持續的雙向連線,適合主動推播事件給 Claude 的遠端 MCP 伺服器。如果您的伺服器僅回應請求,請改用 HTTP,因為 HTTP 支援 OAuth 及 claude mcp add --transport 標誌,而 WebSocket 兩者都不支援。

由於 --transport 不接受 ws,請在 .mcp.json 中設定或透過 claude mcp add-json 設定:

json
{
  "type": "ws",
  "url": "wss://mcp.example.com/socket",
  "headers": {
    "Authorization": "Bearer YOUR_TOKEN"
  }
}

type: "ws" 項目接受與 http 相同的 urlheadersheadersHelpertimeoutalwaysLoad 欄位。驗證方式僅限標頭 (Header-only) — WebSocket 伺服器沒有 OAuth 流程。

注意:WebSocket 伺服器不會顯示在 claude mcp list 的輸出中。請使用 claude mcp get <name>/mcp 面板來檢查它們。

與 HTTP 及 SSE 相同,WebSocket 連線使用 5 分鐘的閒置視窗;stdio 及 WebSocket 沒有單次請求定時器。缺少 typeurl 項目會觸發錯誤,提示 "http""sse""ws" 為有效值。

工作階段工作目錄 (Session Working Directories, roots/list)

MCP 伺服器可以探索工作階段的工作目錄:啟動目錄加上所有 --add-dir/additionalDirectories 項目會透過 MCP roots/list 請求傳回,且每當集合變動時會發送 notifications/roots/list_changed 通知 (v2.1.203)。閒置逾時現在也適用於 stdio 伺服器(30 分鐘),且個別伺服器的 timeout 可作為閒置下限 (v2.1.203)。

Windows 專屬說明 (Windows-Specific Note)

在原生 Windows(非 WSL)上,npx 命令請使用 cmd /c

bash
claude mcp add --transport stdio my-server -- cmd /c npx -y @some/package

OAuth 2.0 驗證 (OAuth 2.0 Authentication)

Claude Code 對於需要授權的 MCP 伺服器支援 OAuth 2.0。當連線至啟用 OAuth 的伺服器時,Claude Code 會處理整個驗證流程:

bash
# 連線至啟用 OAuth 的 MCP 伺服器(互動式流程)
claude mcp add --transport http my-service https://my-service.example.com/mcp

# 為非互動式設定預先配置 OAuth 憑證
claude mcp add --transport http my-service https://my-service.example.com/mcp \
  --client-id "your-client-id" \
  --client-secret "your-client-secret" \
  --callback-port 8080
功能 (Feature)說明 (Description)
互動式 OAuth (Interactive OAuth)使用 /mcp 觸發基於瀏覽器的 OAuth 流程
預先配置的 OAuth 用戶端 (Pre-configured OAuth clients)針對常用服務(如 Notion、Stripe 等)內建 OAuth 用戶端 (v2.1.30+)
預先配置的憑證 (Pre-configured credentials)提供 --client-id--client-secret--callback-port 標誌進行自動化設定
權杖儲存 (Token storage)權杖 (Tokens) 會安全地儲存在您的系統金鑰圈 (Keychain) 中
提權驗證 (Step-up auth)支援特權操作的提權驗證
探索快取 (Discovery caching)快取 OAuth 探索元資料 (Metadata) 以實現更快地重新連線
元資料覆寫 (Metadata override).mcp.json 中設定 oauth.authServerMetadataUrl 以覆寫預設的 OAuth 元資料探索

覆寫 OAuth 元資料探索 (Overriding OAuth Metadata Discovery)

如果您的 MCP 伺服器在標準 OAuth 元資料端點 (/.well-known/oauth-authorization-server) 返回錯誤,但提供正常運作的 OIDC 端點,您可以指示 Claude Code 從特定 URL 擷取 OAuth 元資料。請在伺服器設定的 oauth 物件中設定 authServerMetadataUrl

json
{
  "mcpServers": {
    "my-server": {
      "type": "http",
      "url": "https://mcp.example.com/mcp",
      "oauth": {
        "authServerMetadataUrl": "https://auth.example.com/.well-known/openid-configuration"
      }
    }
  }
}

URL 必須使用 https://。此選項需要 Claude Code v2.1.64 或更高版本。

啟動時驗證提示與動態標頭重新整理 (v2.1.193)

  • 啟動驗證提示 (Startup auth notice, v2.1.193+):啟動時,Claude Code 會顯示提示,列出任何仍需要驗證的 MCP 伺服器,因此需要登入的伺服器不會悄悄處於失效狀態。
  • headersHelper 自動重新整理 (v2.1.193+):如果您透過 headersHelper 提供自訂驗證,當伺服器傳回 HTTP 401 或 403 時,該 Helper 會自動重新叫用。憑證會即時重新整理,無需手動重新連線。請參閱 使用動態標頭進行自訂驗證

警告 (v2.1.238):專案 .mcp.json 中的 headersHelper,以及專案或 --add-dir 代理人檔案中的內聯 (Inline) MCP 伺服器,現在都需要接受該資料夾的信任對話方塊 — 包括在 claude -p 下。此類 Helper 也會在沒有繼承憑證環境變數的情況下執行;使用者、託管與 claude.ai 範圍的 Helper 改為從 Claude 設定目錄執行。依賴繼承憑證或在未受信任狀態下執行的專案設定將停止運作,直到您接受信任對話方塊並透過其他方式提供憑證。

Claude.ai MCP 連接器 (Claude.ai MCP Connectors)

在您的 Claude.ai 帳戶中設定的 MCP 伺服器會自動在 Claude Code 中可用。這意味著您透過 Claude.ai 網頁介面設定的任何 MCP 連線都可以在無需額外設定的情況下存取。

Claude.ai MCP 連接器也適用於 --print 模式 (v2.1.83+),支援非互動式與指令稿化使用。

啟動說明 (v2.1.117+): 當同時設定本地與 claude.ai MCP 伺服器時,預設會使用並行連線(以往為序列連線),從而減少使用多個伺服器時的啟動延遲。

要在 Claude Code 中停用 Claude.ai MCP 伺服器,請將 ENABLE_CLAUDEAI_MCP_SERVERS 環境變數設定為 false

bash
ENABLE_CLAUDEAI_MCP_SERVERS=false claude

注意: 此功能僅供登入 Claude.ai 帳戶的使用者使用。

MCP 設定流程 (MCP Setup Process)

mermaid
sequenceDiagram
    participant User
    participant Claude as Claude Code
    participant Config as Config File
    participant Service as External Service

    User->>Claude: Type /mcp
    Claude->>Claude: List available MCP servers
    Claude->>User: Show options
    User->>Claude: Select GitHub MCP
    Claude->>Config: Update configuration
    Config->>Claude: Activate connection
    Claude->>Service: Test connection
    Service-->>Claude: Authentication successful
    Claude->>User: ✅ MCP connected!

/mcp 指令 (/mcp command)

在工作階段內輸入 /mcp 可列出已連線的伺服器、觸發 OAuth 流程並檢查連線狀態。

  • v2.1.121 起,當遇到暫時性錯誤時,MCP 會最多重試初始連線 3 次。
  • v2.1.128 起,/mcp 會顯示每個已連線伺服器的工具數量 (Tool count),並以視覺標記回報 0 個工具 的伺服器,以便一眼識別出設定錯誤的伺服器。

當 MCP 工具描述超過脈絡視窗 (Context Window) 的 10% 時,Claude Code 會自動啟用工具搜尋,以有效選擇正確的工具,而不會使模型脈絡過載。

設定 (Setting)數值 (Value)說明 (Description)
ENABLE_TOOL_SEARCHauto (預設)當工具描述超過脈絡的 10% 時自動啟用
ENABLE_TOOL_SEARCHauto:<N>當工具數量達到自訂門檻 N 時自動啟用
ENABLE_TOOL_SEARCHtrue無論工具數量多少,始終啟用
ENABLE_TOOL_SEARCHfalse停用;所有工具描述將完整發送

注意: 工具搜尋需要 Sonnet 4 或更高版本,或 Opus 4 或更高版本。Haiku 模型不支援工具搜尋。

繞過特定伺服器的工具搜尋 (v2.1.121+) (Bypassing Tool Search per Server)

如果輪到每回合都需要特定 MCP 伺服器的工具,可以在其設定中標記 "alwaysLoad": true 以跳過工具搜尋的延遲載入,保持其工具始終可用:

json
{
  "mcpServers": {
    "always-on-tool": {
      "command": "node",
      "args": ["./tools/always.js"],
      "alwaysLoad": true
    }
  }
}

請謹慎使用 — 每個始終載入的工具都會消耗脈絡,否則這些脈絡本可用於工具搜尋以呈現更相關的工具。

動態工具更新 (Dynamic Tool Updates)

Claude Code 支援 MCP list_changed 通知。當 MCP 伺服器動態新增、移除或修改其可用工具時,Claude Code 會收到更新並自動調整其工具清單 -- 無需重新連線或重啟。

MCP 應用程式 (MCP Apps)

MCP Apps 是第一個官方 MCP 擴充功能,使 MCP 工具呼叫能夠傳回直接在聊天介面中轉譯的互動式 UI 元件。MCP 伺服器無需僅提供純文字回應,而是可以提供豐富的儀表板、表單、資料視覺化與多步驟工作流程 -- 全部內聯顯示而無需離開對話。

MCP 導出引導 (MCP Elicitation)

MCP 伺服器可以透過互動式對話方塊向使用者要求結構化輸入 (v2.1.49+)。這允許 MCP 伺服器在工作流程中途要求額外資訊 -- 例如提示確認、從選項清單中選擇或填寫必填欄位 -- 為 MCP 伺服器互動增添互動性。

工具描述與指令上限 (Tool Description and Instruction Cap)

自 v2.1.84 起,Claude Code 對每個 MCP 伺服器的工具描述與指令實施 2 KB 的上限。這可以防止個別伺服器因過於冗長的工具定義而消耗過多脈絡,從而減少脈絡膨脹並保持互動的高效性。

MCP 提示詞作為斜線指令 (MCP Prompts as Slash Commands)

MCP 伺服器可以公開提示詞 (Prompts),使其在 Claude Code 中顯示為斜線指令 (Slash Commands)。提示詞可使用以下命名慣例存取:

/mcp__<server>__<prompt>

例如,如果名為 github 的伺服器公開了名為 review 的提示詞,您可以將其作為 /mcp__github__review 來叫用。

伺服器去重 (Server Deduplication)

當相同的 MCP 伺服器定義在多個作用域 (Local, Project, User) 時,本地設定優先。這允許您使用本地自訂覆寫專案級或使用者級的 MCP 設定而不會發生衝突。

近期生命週期修復 (v2.1.136) (Recent Lifecycle Fixes)

v2.1.136 中修復了兩個存在已久的 MCP 生命週期 Bug — 如果您執行多伺服器架構,非常值得升級:

  • MCP 伺服器在 /clear 後繼續保持 persistence:透過 .mcp.json、擴充套件或 claude.ai 連接器設定的伺服器,在 VS Code、JetBrains 或 Agent SDK 中執行 /clear 後不再消失。早期版本會悄悄丟棄它們並需要重新啟動。
  • OAuth 重新整理權杖 (Refresh Token) 競態修復:多伺服器 OAuth 設定在多個伺服器同時競爭重新整理時不再丟失重新整理權杖。這消除了影響多個受 OAuth 保護的 MCP 伺服器設定的「每天早上我都必須重新驗證」模式。

透過 @ 提及存取 MCP 資源 (MCP Resources via @ Mentions)

您可以使用 @ 提及語法在提示詞中直接參照 MCP 資源:

@server-name:protocol://resource/path

例如,要參照特定的資料庫資源:

@database:postgres://mydb/users

這允許 Claude 擷取 MCP 資源內容並將其作為對話脈絡的一部分內聯包含進來。

MCP 作用域 (MCP Scopes)

MCP 設定可以儲存在具有不同共享層級的不同作用域中:

作用域 (Scope)標誌 (Flag)位置 (Location)說明 (Description)共享對象 (Shared With)需要批准 (Requires Approval)
本地 (Local) (預設)--scope local~/.claude.json (在專案路徑下)僅限當前使用者、當前專案私有(在舊版本中稱為 project僅限您
專案 (Project)--scope project.mcp.json提交至 git 儲存庫團隊成員是 (首次使用)
使用者 (User)--scope user~/.claude.json適用於所有專案(在舊版本中稱為 global僅限您

使用 --scope(簡寫 -s)新增伺服器時選擇作用域。如果省略,Claude Code 會使用 local

bash
# 專案作用域 — 寫入 .mcp.json 以便團隊共享
claude mcp add --scope project --transport http github https://api.github.com/mcp

# 使用者作用域 — 在每個專案中均可用
claude mcp add --scope user --transport stdio memory -- npx @modelcontextprotocol/server-memory

使用專案作用域 (Using Project Scope)

將專案專屬的 MCP 設定儲存在 .mcp.json 中:

json
{
  "mcpServers": {
    "github": {
      "type": "http",
      "url": "https://api.github.com/mcp"
    }
  }
}

團隊成員在首次使用專案 MCP 時會看到批准提示。在未受信任的工作區中,儲存庫透過已提交的 .claude/settings.json 自動批准的伺服器不會claude mcp list/get 自動啟動 — 它們會顯示 ⏸ Pending approval,直到您接受信任對話方塊,且在未受信任的資料夾中 enableAllProjectMcpServers 會被忽略 (v2.1.196)。

MCP 設定管理 (MCP Configuration Management)

新增 MCP 伺服器 (Adding MCP Servers)

bash
# 新增基於 HTTP 的伺服器
claude mcp add --transport http github https://api.github.com/mcp

# 新增本地 stdio 伺服器
claude mcp add --transport stdio database -- npx @company/db-server

# 列出所有 MCP 伺服器
claude mcp list

# 取得特定伺服器的詳細資訊
claude mcp get github

# 移除 MCP 伺服器
claude mcp remove github

# 重置專案專屬的批准選擇
claude mcp reset-project-choices

# 從 CLI 驗證 MCP 伺服器 (v2.1.186+)
claude mcp login github

# 登出 MCP 伺服器 (v2.1.186+)
claude mcp logout github

# 從 Claude Desktop 匯入
claude mcp add-from-claude-desktop

# 從 JSON 區塊新增伺服器(對指令稿化設定很有用)
claude mcp add-json events-server '{"type":"stdio","command":"npx","args":["@modelcontextprotocol/server-events"]}'

注意:在 JSON 設定中 — .mcp.json~/.claude.jsonclaude mcp add-jsontype 欄位接受 streamable-http 作為 http 的別名。MCP 規格對此傳輸使用 streamable-http 名稱,因此從伺服器自有的說明文件複製的設定可直接運作而無需修改。

自 v2.1.238 起,claude mcp listclaude mcp get 會將停用的伺服器顯示為 ⊘ Disabled,而不會連線至它們進行健康檢查。

claude mcp login <name> / claude mcp logout <name>/mcp 選單中 OAuth 流程的非互動式等效項 — 無需開啟選單即可進行驗證或登出。在 login 中新增 --no-browser 可以透過 SSH 或在無頭 (Headless) 工作階段中完成 OAuth(它會透過 stdin 重導向流程)。

可用 MCP 伺服器表 (Available MCP Servers Table)

MCP 伺服器用途 (Purpose)常見工具 (Common Tools)驗證 (Auth)即時 (Real-time)
Filesystem檔案操作read, write, deleteOS 權限✅ 是
GitHub儲存庫管理list_prs, create_issue, pushOAuth✅ 是
Slack團隊溝通send_message, list_channelsToken✅ 是
DatabaseSQL 查詢query, insert, update憑證✅ 是
Google Docs文件存取read, write, shareOAuth✅ 是
Asana專案管理create_task, update_statusAPI Key✅ 是
Stripe付款資料list_charges, create_invoiceAPI Key✅ 是
Memory持久化記憶store, retrieve, delete本地❌ 否

實用範例 (Practical Examples)

範例 1:GitHub MCP 設定 (GitHub MCP Configuration)

檔案: .mcp.json(專案根目錄)

json
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}

可用的 GitHub MCP 工具:

Pull Request 管理 (Pull Request Management)

  • list_prs - 列出儲存庫中的所有 PR
  • get_pr - 取得包含 diff 的 PR 詳細資訊
  • create_pr - 建立新的 PR
  • update_pr - 更新 PR 描述/標題
  • merge_pr - 將 PR 合併至主分支 (main branch)
  • review_pr - 新增審查評論

請求範例:

/mcp__github__get_pr 456

# Returns:
Title: Add dark mode support
Author: @alice
Description: Implements dark theme using CSS variables
Status: OPEN
Reviewers: @bob, @charlie

Issue 管理 (Issue Management)

  • list_issues - 列出所有 Issue
  • get_issue - 取得 Issue 詳細資訊
  • create_issue - 建立新 Issue
  • close_issue - 關閉 Issue
  • add_comment - 為 Issue 新增評論

儲存庫資訊 (Repository Information)

  • get_repo_info - 儲存庫詳細資訊
  • list_files - 檔案樹結構
  • get_file_content - 讀取檔案內容
  • search_code - 跨程式碼庫搜尋

Commit 操作 (Commit Operations)

  • list_commits - Commit 歷史紀錄
  • get_commit - 特定 Commit 的詳細資訊
  • create_commit - 建立新 Commit

設定:

bash
export GITHUB_TOKEN="your_github_token"
# 或使用 CLI 直接新增:
claude mcp add --transport stdio github -- npx @modelcontextprotocol/server-github

設定中的環境變數展開 (Environment Variable Expansion in Configuration)

MCP 設定支援帶有預設退路 (Fallback) 的環境變數展開。${VAR}${VAR:-default} 語法適用於以下欄位:commandargsenvurlheaders

json
{
  "mcpServers": {
    "api-server": {
      "type": "http",
      "url": "${API_BASE_URL:-https://api.example.com}/mcp",
      "headers": {
        "Authorization": "Bearer ${API_KEY}",
        "X-Custom-Header": "${CUSTOM_HEADER:-default-value}"
      }
    },
    "local-server": {
      "command": "${MCP_BIN_PATH:-npx}",
      "args": ["${MCP_PACKAGE:-@company/mcp-server}"],
      "env": {
        "DB_URL": "${DATABASE_URL:-postgresql://localhost/dev}"
      }
    }
  }
}

變數會在執行階段展開:

  • ${VAR} - 使用環境變數,若未設定則報錯
  • ${VAR:-default} - 使用環境變數,若未設定則退回使用預設值

範例 2:Database MCP 設定 (Database MCP Setup)

設定:

json
{
  "mcpServers": {
    "database": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-database"],
      "env": {
        "DATABASE_URL": "${DATABASE_URL}"
      }
    }
  }
}

使用範例:

markdown
User: Fetch all users with more than 10 orders

Claude: I'll query your database to find that information.

# Using MCP database tool:
SELECT u.*, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id
HAVING COUNT(o.id) > 10
ORDER BY order_count DESC;

# Results:
- Alice: 15 orders
- Bob: 12 orders
- Charlie: 11 orders

設定:

bash
export DATABASE_URL="postgresql://user:pass@localhost/mydb"
# 或使用 CLI 直接新增:
claude mcp add --transport stdio database -- npx @modelcontextprotocol/server-database

範例 3:多 MCP 工作流程 (Multi-MCP Workflow)

情境:每日報告生成

markdown
# Daily Report Workflow using Multiple MCPs

## Setup
1. GitHub MCP - fetch PR metrics
2. Database MCP - query sales data
3. Slack MCP - post report
4. Filesystem MCP - save report

## Workflow

### Step 1: Fetch GitHub Data
/mcp__github__list_prs completed:true last:7days

Output:
- Total PRs: 42
- Average merge time: 2.3 hours
- Review turnaround: 1.1 hours

### Step 2: Query Database
SELECT COUNT(*) as sales, SUM(amount) as revenue
FROM orders
WHERE created_at > NOW() - INTERVAL '1 day'

Output:
- Sales: 247
- Revenue: $12,450

### Step 3: Generate Report
Combine data into HTML report

### Step 4: Save to Filesystem
Write report.html to /reports/

### Step 5: Post to Slack
Send summary to #daily-reports channel

Final Output:
✅ Report generated and posted
📊 47 PRs merged this week
💰 $12,450 in daily sales

設定:

bash
export GITHUB_TOKEN="your_github_token"
export DATABASE_URL="postgresql://user:pass@localhost/mydb"
export SLACK_TOKEN="your_slack_token"
# 透過 CLI 新增每個 MCP 伺服器或在 .mcp.json 中設定它們

範例 4:Filesystem MCP 操作 (Filesystem MCP Operations)

設定:

json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-filesystem", "/home/user/projects"]
    }
  }
}

可用操作:

操作 (Operation)指令 (Command)用途 (Purpose)
列出檔案ls ~/projects顯示目錄內容
讀取檔案cat src/main.ts讀取檔案內容
寫入檔案create docs/api.md建立新檔案
編輯檔案edit src/app.ts修改檔案
搜尋grep "async function"在檔案中搜尋
刪除rm old-file.js刪除檔案

設定:

bash
# 使用 CLI 直接新增:
claude mcp add --transport stdio filesystem -- npx @modelcontextprotocol/server-filesystem /home/user/projects

MCP vs Memory:決策矩陣 (MCP vs Memory: Decision Matrix)

mermaid
graph TD
    A["Need external data?"]
    A -->|No| B["Use Memory"]
    A -->|Yes| C["Does it change frequently?"]
    C -->|No/Rarely| B
    C -->|Yes/Often| D["Use MCP"]

    B -->|Stores| E["Preferences<br/>Context<br/>History"]
    D -->|Accesses| F["Live APIs<br/>Databases<br/>Services"]

    style A fill:#fff3e0,stroke:#333,color:#333
    style B fill:#e1f5fe,stroke:#333,color:#333
    style C fill:#fff3e0,stroke:#333,color:#333
    style D fill:#f3e5f5,stroke:#333,color:#333
    style E fill:#e8f5e9,stroke:#333,color:#333
    style F fill:#e8f5e9,stroke:#333,color:#333

請求/回應模式 (Request/Response Pattern)

mermaid
sequenceDiagram
    participant App as Claude
    participant MCP as MCP Server
    participant DB as Database

    App->>MCP: Request: "SELECT * FROM users WHERE id=1"
    MCP->>DB: Execute query
    DB-->>MCP: Result set
    MCP-->>App: Return parsed data
    App->>App: Process result
    App->>App: Continue task

    Note over MCP,DB: Real-time access<br/>No caching

環境變數 (Environment Variables)

將敏感憑證儲存在環境變數中:

bash
# ~/.bashrc 或 ~/.zshrc
export GITHUB_TOKEN="ghp_xxxxxxxxxxxxx"
export DATABASE_URL="postgresql://user:pass@localhost/mydb"
export SLACK_TOKEN="xoxb-xxxxxxxxxxxxx"

然後在 MCP 設定中參照它們:

json
{
  "env": {
    "GITHUB_TOKEN": "${GITHUB_TOKEN}"
  }
}

Claude 作為 MCP 伺服器 (claude mcp serve) (Claude as MCP Server)

Claude Code 本身可以作為其他應用程式的 MCP 伺服器。這使外部工具、編輯器與自動化系統能夠透過標準 MCP 協定利用 Claude 的功能。

bash
# 在 stdio 上將 Claude Code 作為 MCP 伺服器啟動
claude mcp serve

其他應用程式隨後可以像連線任何基於 stdio 的 MCP 伺服器一樣連線至此伺服器。例如,要在另一個 Claude Code 執行個體中將 Claude Code 作為 MCP 伺服器新增:

bash
claude mcp add --transport stdio claude-agent -- claude mcp serve

這對於建構多代理人 (Multi-Agent) 工作流程非常有用,其中一個 Claude 執行個體協調另一個執行個體。

託管 MCP 設定 (企業版) (Managed MCP Configuration (Enterprise))

對於企業部署,IT 管理員透過兩種獨立的機制強制執行 MCP 伺服器原則:一個部署具有獨占控制權的固定伺服器集的 managed-mcp.json 檔案,以及過濾可以載入哪些已設定伺服器的 allowedMcpServers / deniedMcpServers 設定金鑰。

位置:

  • macOS: /Library/Application Support/ClaudeCode/managed-mcp.json
  • Linux 與 WSL: /etc/claude-code/managed-mcp.json
  • Windows: C:\Program Files\ClaudeCode\managed-mcp.json

managed-mcp.json 使用與專案 .mcp.json 相同的格式 — 頂層的 mcpServers 映射。它用於部署伺服器,而不是過濾伺服器:

json
{
  "mcpServers": {
    "example-remote": {
      "type": "http",
      "url": "https://mcp.example.com/mcp"
    },
    "company-internal": {
      "type": "stdio",
      "command": "/usr/local/bin/company-mcp-server",
      "args": ["--config", "/etc/company/mcp-config.json"]
    }
  }
}

機器上的任何使用者都可以讀取此檔案,因此切勿將憑證放在 env 區塊中。請改用 ${VAR} 展開、OAuth 或 headersHelper

過濾:白名單與黑名單 (Filtering: allowlists and denylists)

allowedMcpServersdeniedMcpServersallowAllClaudeAiMcps設定金鑰,而非 managed-mcp.json 的欄位。將它們放在受管設定源中 — 伺服器託管設定、managed-settings.json、MDM 設定檔或登錄檔 — 以便強制執行:

  • allowedMcpServers -- 允許伺服器的白名單。在其旁邊、相同的託管源中設定 allowManagedMcpServersOnly: true,否則白名單會從每個作用域合併,使用者可以放寬您的設定。
  • deniedMcpServers -- 封鎖伺服器的黑名單。無論如何都會從每個作用域合併。
  • allowAllClaudeAiMcps -- 在部署的 managed-mcp.json 旁邊載入 claude.ai 雲端連接器 (v2.1.149+)。僅能從管理員控制的策略層級讀取。

每個項目都是帶有單一金鑰的物件:

金鑰 (Key)比對對象 (Matches)
serverUrl遠端伺服器 URL,精確比對或包含 * 萬用字元
serverCommand啟動 stdio 伺服器的精確指令與引數陣列 — 每個引數均需按順序比對
serverName使用者指派的標籤。僅精確比對;不會展開萬用字元

設定範例:

json
{
  "allowedMcpServers": [
    { "serverUrl": "https://mcp.example.com/*" },
    { "serverCommand": ["/usr/local/bin/company-mcp-server", "--config", "/etc/company/mcp-config.json"] }
  ],
  "deniedMcpServers": [
    { "serverName": "untrusted-server" },
    { "serverUrl": "http://*" }
  ],
  "allowAllClaudeAiMcps": true
}

第三個託管設定 managedMcpServers (v2.1.259+) 允許組織為每個使用者提供 HTTP/SSE MCP 伺服器。項目使用與 .mcp.json 相同的結構;指定要執行的指令之項目會被跳過。

注意:allowedMcpServersdeniedMcpServers 同時比對某個伺服器時,拒絕規則 (Deny rule) 優先。

外掛提供之 MCP 伺服器 (Plugin-Provided MCP Servers)

外掛 (Plugins) 可以綁定自己的 MCP 伺服器,在安裝外掛時自動使其可用。外掛提供的 MCP 伺服器可以透過兩種方式定義:

  1. 獨立 .mcp.json -- 將 .mcp.json 檔案放在外掛根目錄中
  2. plugin.json 中內聯 -- 直接在外掛資訊清單 (Manifest) 中定義 MCP 伺服器

使用 ${CLAUDE_PLUGIN_ROOT} 變數參照相對於外掛安裝目錄的路徑:

json
{
  "mcpServers": {
    "plugin-tools": {
      "command": "node",
      "args": ["${CLAUDE_PLUGIN_ROOT}/dist/mcp-server.js"],
      "env": {
        "CONFIG_PATH": "${CLAUDE_PLUGIN_ROOT}/config.json"
      }
    }
  }
}

子代理人作用域 MCP (Subagent-Scoped MCP)

可以使用 mcpServers: 金鑰在代理人 Frontmatter 中內聯定義 MCP 伺服器,將其作用域限制在特定子代理人 (Subagent) 而非整個專案。當代理人需要存取工作流程中其他代理人不需要的特定 MCP 伺服器時,這非常有用。

yaml
---
mcpServers:
  my-tool:
    type: http
    url: https://my-tool.example.com/mcp
---

You are an agent with access to my-tool for specialized operations.

子代理人作用域的 MCP 伺服器僅在該代理人的執行脈絡中可用,不會與父代理人或兄弟代理人共享。

MCP 輸出限制 (MCP Output Limits)

Claude Code 對 MCP 工具輸出實施限制以防止脈絡溢位:

限制 (Limit)門檻 (Threshold)行為 (Behavior)
警告 (Warning)10,000 個權杖 (tokens)顯示輸出過大的警告
預設最大值 (Default max)25,000 個權杖 (tokens)超過此限制的輸出將被裁切 (Truncated)
磁碟持久化 (Disk persistence)50,000 個字元超過 50K 字元的工具結果會持久化寫入磁碟

最大輸出限制可透過 MAX_MCP_OUTPUT_TOKENS 環境變數進行設定:

bash
# 將最大輸出增加至 50,000 個權杖
export MAX_MCP_OUTPUT_TOKENS=50000

自動背景化長時間執行的工具呼叫 (v2.1.212) (Auto-Backgrounding Long-Running Tool Calls)

執行時間超過 2 分鐘的 MCP 工具呼叫現在會自動轉移至背景,因此工作階段保持可用狀態而不會阻塞在慢速工具上。門檻可透過 CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS 進行設定、調整或停用:

bash
# 將自動背景化門檻變更為 5 分鐘 (300,000ms)
export CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS=300000

使用程式碼執行解決脈絡膨脹問題 (Solving Context Bloat with Code Execution)

隨著 MCP 採用的規模擴大,連線至擁有數百或數千個工具的數十個伺服器會帶來重大挑戰:脈絡膨脹 (Context bloat)。這可說是規模化使用 MCP 時最大的問題,Anthropic 工程團隊提出了一個優雅的解決方案 — 使用程式碼執行 (Code Execution) 代替直接的工具呼叫。

來源Code Execution with MCP: Building More Efficient Agents — Anthropic 工程部落格

問題所在:權杖浪費的兩個來源 (The Problem: Two Sources of Token Waste)

1. 工具定義過載脈絡視窗

大多數 MCP 用戶端預先載入所有工具定義。連線至數千個工具時,模型在讀取使用者的請求之前就必須處理數十萬個權杖。

2. 中間結果消耗額外的權杖

每個中間工具結果都會通過模型的脈絡。考慮將會議逐字稿從 Google Drive 傳輸至 Salesforce — 完整的逐字稿會流經脈絡 兩次:一次是讀取時,另一次是寫入目的地時。長達 2 小時的會議逐字稿可能意味著 50,000+ 的額外權杖。

mermaid
graph LR
    A["Model"] -->|"Tool Call: getDocument"| B["MCP Server"]
    B -->|"Full transcript (50K tokens)"| A
    A -->|"Tool Call: updateRecord<br/>(re-sends full transcript)"| B
    B -->|"Confirmation"| A

    style A fill:#ffcdd2,stroke:#333,color:#333
    style B fill:#f3e5f5,stroke:#333,color:#333

解決方案:將 MCP 工具作為程式碼 API (The Solution: MCP Tools as Code APIs)

代理人不再將工具定義與結果通過脈絡視窗傳遞,而是撰寫程式碼將 MCP 工具作為 API 來叫用。程式碼在沙盒化 (Sandboxed) 執行環境中執行,只有最終結果會傳回給模型。

mermaid
graph LR
    A["Model"] -->|"Writes code"| B["Code Execution<br/>Environment"]
    B -->|"Calls tools directly"| C["MCP Servers"]
    C -->|"Data stays in<br/>execution env"| B
    B -->|"Only final result<br/>(minimal tokens)"| A

    style A fill:#c8e6c9,stroke:#333,color:#333
    style B fill:#e1f5fe,stroke:#333,color:#333
    style C fill:#f3e5f5,stroke:#333,color:#333

運作方式 (How It Works)

MCP 工具以帶型別函數 (Typed functions) 的檔案樹形式呈現:

servers/
├── google-drive/
│   ├── getDocument.ts
│   └── index.ts
├── salesforce/
│   ├── updateRecord.ts
│   └── index.ts
└── ...

每個工具檔案包含一個帶型別的封裝器 (Wrapper):

typescript
// ./servers/google-drive/getDocument.ts
import { callMCPTool } from "../../../client.js";

interface GetDocumentInput {
  documentId: string;
}

interface GetDocumentResponse {
  content: string;
}

export async function getDocument(
  input: GetDocumentInput
): Promise<GetDocumentResponse> {
  return callMCPTool<GetDocumentResponse>(
    'google_drive__get_document', input
  );
}

代理人隨後撰寫程式碼來編排這些工具:

typescript
import * as gdrive from './servers/google-drive';
import * as salesforce from './servers/salesforce';

// Data flows directly between tools — never through the model
const transcript = (
  await gdrive.getDocument({ documentId: 'abc123' })
).content;

await salesforce.updateRecord({
  objectType: 'SalesMeeting',
  recordId: '00Q5f000001abcXYZ',
  data: { Notes: transcript }
});

結果:權杖使用量從 ~150,000 降至 ~2,000 — 減少了 98.7%。

主要優勢 (Key Benefits)

優勢 (Benefit)說明 (Description)
漸進式揭露 (Progressive Disclosure)代理人瀏覽檔案系統以僅載入其需要的工具定義,而非一次載入所有工具
高效脈絡的結果 (Context-Efficient Results)資料在傳回模型之前於執行環境中進行過濾/轉換
強大的控制流程 (Powerful Control Flow)迴圈、條件式與錯誤處理在程式碼中執行,無需在模型間來回傳輸 (Round-tripping)
隱私保護 (Privacy Preservation)中間資料(個人識別資訊 PII、敏感紀錄)留在執行環境中;絕不安裝至模型脈絡
狀態持久化 (State Persistence)代理人可以將中間結果儲存至檔案並建構可重複使用的技能函數 (Skill functions)

範例:過濾大型資料集 (Example: Filtering Large Datasets)

typescript
// Without code execution — all 10,000 rows flow through context
// TOOL CALL: gdrive.getSheet(sheetId: 'abc123')
//   -> returns 10,000 rows in context

// With code execution — filter in the execution environment
const allRows = await gdrive.getSheet({ sheetId: 'abc123' });
const pendingOrders = allRows.filter(
  row => row["Status"] === 'pending'
);
console.log(`Found ${pendingOrders.length} pending orders`);
console.log(pendingOrders.slice(0, 5)); // Only 5 rows reach the model

範例:無來回傳輸的迴圈 (Example: Loop Without Round-Tripping)

typescript
// Poll for a deployment notification — runs entirely in code
let found = false;
while (!found) {
  const messages = await slack.getChannelHistory({
    channel: 'C123456'
  });
  found = messages.some(
    m => m.text.includes('deployment complete')
  );
  if (!found) await new Promise(r => setTimeout(r, 5000));
}
console.log('Deployment notification received');

需考量的權衡 (Trade-offs to Consider)

程式碼執行帶來了其自身的複雜性。執行代理人生成的程式碼需要:

  • 具有適當資源限制的安全沙盒化執行環境
  • 對已執行程式碼的監控與記錄 (Monitoring and logging)
  • 與直接工具呼叫相比額外的基礎設施開銷 (Infrastructure overhead)

應根據這些實作成本權衡好處 — 降低權杖成本、降低延遲、改進工具組合。對於僅有少數 MCP 伺服器的代理人,直接工具呼叫可能更簡單。對於大規模代理人(數十個伺服器、數百個工具),程式碼執行是一項顯著改進。

MCPorter:MCP 工具組合的執行階段 (MCPorter: A Runtime for MCP Tool Composition)

MCPorter 是一個 TypeScript 執行階段與 CLI 工具包,使呼叫 MCP 伺服器無需樣板程式碼 (Boilerplate) 即可實用化 — 並透過選擇性工具暴露出與帶型別封裝器來幫助減少脈絡膨脹。

解決的問題: MCPorter 允許您按需探索、檢查與叫用特定工具,而不是事先從所有 MCP 伺服器載入所有工具定義 — 從而保持脈絡精簡。

主要功能:

功能 (Feature)說明 (Description)
零設定探索 (Zero-config discovery)自動從 Cursor、Claude、Codex 或本地設定中探索 MCP 伺服器
帶型別的工具用戶端 (Typed tool clients)mcporter emit-ts 生成 .d.ts 介面與可直接執行的封裝器
可組合 API (Composable API)createServerProxy() 將工具暴露為駝峰式 (camelCase) 方法,附帶 .text().json().markdown() 輔助工具
CLI 生成 (CLI generation)mcporter generate-cli 可將任何 MCP 伺服器轉為獨立 CLI,附帶 --include-tools / --exclude-tools 過濾
參數隱藏 (Parameter hiding)選用參數預設保持隱藏,減少 Schema 冗長度

安裝方式:

bash
npx mcporter list          # No install required — discover servers instantly
pnpm add mcporter          # Add to a project
brew install steipete/tap/mcporter  # macOS via Homebrew

範例 — 在 TypeScript 中組合工具:

typescript
import { createRuntime, createServerProxy } from "mcporter";

const runtime = await createRuntime();
const gdrive = createServerProxy(runtime, "google-drive");
const salesforce = createServerProxy(runtime, "salesforce");

// Data flows between tools without passing through the model context
const doc = await gdrive.getDocument({ documentId: "abc123" });
await salesforce.updateRecord({
  objectType: "SalesMeeting",
  recordId: "00Q5f000001abcXYZ",
  data: { Notes: doc.text() }
});

範例 — CLI 工具呼叫:

bash
# Call a specific tool directly
npx mcporter call linear.create_comment issueId:ENG-123 body:'Looks good!'

# List available servers and tools
npx mcporter list

MCPorter 透過提供將 MCP 工具作為帶型別 API 叫用的執行階段基礎設施,補足了上述程式碼執行方法 — 使將中間資料保持在模型脈絡之外變得十分直接。

最佳實踐 (Best Practices)

安全性考量 (Security Considerations)

應做事項 ✅ (Do's)

  • 對於所有憑證使用環境變數
  • 定期輪替權杖與 API 金鑰(建議每月)
  • 盡可能使用唯讀權杖
  • 將 MCP 伺服器存取作用域限制在所需的最小值
  • 監控 MCP 伺服器使用情況與存取紀錄
  • 可用時對外部服務使用 OAuth
  • 對 MCP 請求實施速率限制 (Rate limiting)
  • 生產環境使用前測試 MCP 連線
  • 記錄所有活躍的 MCP 連線
  • 保持 MCP 伺服器套件為最新狀態

禁忌事項 ❌ (Don'ts)

  • 切勿在設定檔案中硬編碼 (Hardcode) 憑證
  • 切勿將權杖或秘密提交至 git
  • 切勿在團隊聊天或電子郵件中共享權杖
  • 切勿將個人權杖用於團隊專案
  • 切勿授予不必要的權限
  • 切勿忽視驗證錯誤
  • 切勿公開暴露 MCP 端點
  • 切勿以 root/admin 權限執行 MCP 伺服器
  • 切勿在紀錄中快取敏感資料
  • 切勿停用驗證機制

設定最佳實踐 (Configuration Best Practices)

  1. 版本控制 (Version Control):將 .mcp.json 保持在 git 中,但對秘密使用環境變數
  2. 最小特權 (Least Privilege):授予每個 MCP 伺服器所需的最少權限
  3. 隔離 (Isolation):盡可能在獨立程序中執行不同的 MCP 伺服器
  4. 監控 (Monitoring):記錄所有 MCP 請求與錯誤以用於稽核軌跡
  5. 測試 (Testing):部署至生產環境之前測試所有 MCP 設定

效能技巧 (Performance Tips)

  • 在應用程式層級快取經常存取的資料
  • 使用具體的 MCP 查詢以減少資料傳輸
  • 監控 MCP 操作的回應時間
  • 考量外部 API 的速率限制
  • 執行多個操作時使用批次處理 (Batching)

安裝說明 (Installation Instructions)

先決條件 (Prerequisites)

  • 已安裝 Node.js 與 npm
  • 已安裝 Claude Code CLI
  • 外部服務的 API 權杖/憑證

逐步設定 (Step-by-Step Setup)

  1. 使用 CLI 新增第一個 MCP 伺服器(範例:GitHub):
bash
claude mcp add --transport stdio github -- npx @modelcontextprotocol/server-github

或在專案根目錄建立 .mcp.json 檔案:

json
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}
  1. 設定環境變數:
bash
export GITHUB_TOKEN="your_github_personal_access_token"
  1. 測試連線:
bash
claude /mcp
  1. 使用 MCP 工具:
bash
/mcp__github__list_prs
/mcp__github__create_issue "Title" "Description"

特定服務的安裝 (Installation for Specific Services)

GitHub MCP:

bash
npm install -g @modelcontextprotocol/server-github

Database MCP:

bash
npm install -g @modelcontextprotocol/server-database

Filesystem MCP:

bash
npm install -g @modelcontextprotocol/server-filesystem

Slack MCP:

bash
npm install -g @modelcontextprotocol/server-slack

疑難排解 (Troubleshooting)

從錯誤輸出開始 (v2.1.219+) (Start With the Error Output)

如果伺服器無法連線,請在進行任何變更前執行 claude mcp list(或在工作階段內輸入 /mcp)。Claude Code 現在會在失敗的伺服器旁印出 HTTP 狀態碼與伺服器的錯誤文字,因此您會獲得 401 Unauthorized404 Not Found,而不是泛泛的「failed to connect」:

bash
# 顯示連線狀態以及失敗項目的 HTTP 狀態碼與錯誤文字
claude mcp list

請先閱讀狀態 — 它會告訴您適用哪種修復方法:

  • 401 / 403 → 憑證錯誤或已過期;使用 claude mcp login <name> 重新驗證
  • 404 → URL 錯誤(通常是因為缺少 /mcp/sse 路徑字尾)
  • 5xx / timeout → 遠端伺服器停機;請參閱 連線逾時

設定值中的隱藏空白 (v2.1.219+) (Hidden Whitespace in Config Values)

當 MCP 設定值包含前導或字尾空白時,Claude Code 會發出警告。這是驗證失敗常見且難以發現的原因:從瀏覽器或聊天訊息複製貼上的權杖通常帶有尾隨空格或分行符號,這些內容會原封不動地發送在 Authorization 標頭中,並作為無效憑證而失敗。

如果您看到此警告,請重新檢查 .mcp.json 中的值(或其展開的環境變數)並進行修剪 (Trim):

bash
# 顯示定界符之間隱藏的前導/尾隨空白
printf '[%s]\n' "$GITHUB_TOKEN"

在無頭執行中跳過的伺服器 (v2.1.219+) (Skipped Servers in Headless Runs)

透過 --mcp-config 傳遞且未通過設定驗證的伺服器會被跳過而非在中途終止執行,因此無頭指令稿可能表面看似正常運作,實則缺少了一半的工具。Claude Code 現在會回報哪些伺服器被丟棄:

  • 無頭 (Headless) / -p 執行:stream-json init 事件帶有一個 mcp_server_errors 欄位,列出每個被跳過的項目。在信任執行輸出之前請先檢查該欄位。
  • 互動式終端機執行:當工作階段開始時,相同的問題會作為啟動警告印出。
bash
# 在無頭執行中檢查跳過的 --mcp-config 項目
claude -p "list my tools" --mcp-config ./servers.json \
  --output-format stream-json --verbose \
  | jq -r 'select(.type == "system" and .subtype == "init") | .mcp_server_errors'

找不到 MCP 伺服器 (MCP Server Not Found)

bash
# 驗證 MCP 伺服器是否已安裝
npm list -g @modelcontextprotocol/server-github

# 若缺少則進行安裝
npm install -g @modelcontextprotocol/server-github

驗證失敗 (Authentication Failed)

bash
# 驗證環境變數是否已設定
echo $GITHUB_TOKEN

# 必要時重新匯出
export GITHUB_TOKEN="your_token"

# 驗證權杖具有正確的權限
# 在以下位置檢查 GitHub token scopes:https://github.com/settings/tokens

連線逾時 (Connection Timeout)

  • 檢查網路連線:ping api.github.com
  • 驗證 API 端點可存取
  • 檢查 API 的速率限制 (Rate limits)
  • 嘗試增加設定中的逾時時間
  • 檢查防火牆或代理伺服器問題

MCP 伺服器當機 (MCP Server Crashes)

  • 檢查 MCP 伺服器紀錄:~/.claude/logs/
  • 驗證所有環境變數均已設定
  • 確保正確的檔案權限
  • 嘗試重新安裝 MCP 伺服器套件
  • 檢查相同連接埠 (Port) 上是否有相衝突的程序

Memory vs MCP

  • Memory(記憶):儲存持久、不常變動的資料(偏好設定、脈絡、歷史紀錄)
  • MCP(模型脈絡協定):存取動態、即時變化的資料(API、資料庫、即時服務)

何時使用何者 (When to Use Each)

  • 使用 Memory 於:使用者偏好設定、對話歷史紀錄、學習到的脈絡
  • 使用 MCP 於:當前 GitHub Issues、即時資料庫查詢、即時資料

與其他 Claude 功能的整合 (Integration with Other Claude Features)

  • 組合 MCP 與 Memory 以獲得豐富脈絡
  • 在提示詞中使用 MCP 工具以實現更好的推理
  • 利用多個 MCP 處理複雜工作流程

額外資源 (Additional Resources)


最後更新 (Last Updated):2026 年 9 月 6 日 Claude Code 版本 (Claude Code Version):2.1.263 來源 (Sources)

Released under the MIT License.