跳至主要內容

MCP (Model Context Protocol):完整指南

精通 Claude Code 的 MCP 系統。學習如何透過官方 Model Context Protocol 使用外部工具、資料庫和服務來擴展 Claude 的能力。

2026 年 10 月 21 日更新: 依 Claude Code 2.1.305 全面校正:修正 MCP 範圍與設定檔(.mcp.json 與 ~/.claude.json)、以目前官方伺服器取代已停止維護或不存在的套件,並補上 tool search、組織管理的 MCP 政策,以及 Memory 伺服器 MEMORY_FILE_PATH 必須使用絕對路徑的說明。

MCP (Model Context Protocol) 是 Claude Code 用來連接外部工具、資料庫和服務的開放協定,藉此擴展 Claude 的能力。本指南涵蓋了有效運用 MCP 所需的一切知識。

什麼是 MCP?

根據 Model Context Protocol 文件,MCP 是一個開放的標準化協定,讓 AI 助手能夠:

  • 存取外部資料來源(資料庫、API、檔案系統)
  • 執行專用工具(Git、套件管理器、雲端服務)
  • 維護持久上下文(記憶、知識圖譜)
  • 整合開發工具(IDE、CI/CD、專案管理)

可以把 MCP 伺服器想像成轉接器,賦予 Claude 內建工具之外的新技能。

MCP 架構

┌─────────────────────────────────────────────────────────┐
│                    Claude Code CLI                       │
│  ┌─────────────────────────────────────────────────┐    │
│  │                 MCP Client                       │    │
│  │  Manages connections to MCP servers             │    │
│  └─────────────────────────────────────────────────┘    │
│            │              │              │               │
│            ▼              ▼              ▼               │
│  ┌──────────────┐ ┌──────────────┐ ┌──────────────┐     │
│  │ MCP Server 1 │ │ MCP Server 2 │ │ MCP Server 3 │     │
│  │ (filesystem) │ │   (memory)   │ │    (git)     │     │
│  └──────────────┘ └──────────────┘ └──────────────┘     │
│            │              │              │               │
│            ▼              ▼              ▼               │
│      Local Files    Knowledge     Git Repository        │
│                      Graph                               │
└─────────────────────────────────────────────────────────┘

新增 MCP 伺服器

官方 CLI 方法(推薦)

根據 Claude Code MCP 文件,請使用 CLI 新增伺服器:

# Local stdio server: everything after -- is the server's own command
claude mcp add [--scope <scope>] <name> [-e KEY=value] -- <command> [args...]

# Remote HTTP server (the recommended transport for cloud services)
claude mcp add --transport http [--scope <scope>] <name> <url>

# Scopes:
# --scope local    → ~/.claude.json, this project only (default)
# --scope project  → .mcp.json in the project root (shared via git)
# --scope user     → ~/.claude.json, all your projects

下列官方參考伺服器(@modelcontextprotocol/server-*)在 2026 年 10 月發布的 2.0 版,要求 Node.js 24 以上。

常用 MCP 伺服器

1. 檔案系統存取

claude mcp add --scope project filesystem \
  -- npx -y @modelcontextprotocol/server-filesystem .

功能:

  • 讀寫檔案
  • 建立目錄
  • 列出目錄內容
  • 檔案搜尋和模式匹配

2. 記憶(知識圖譜)

# IMPORTANT: Use an absolute MEMORY_FILE_PATH for project isolation
# (run from the project root; the shell expands $PWD)
claude mcp add memory \
  -e MEMORY_FILE_PATH="$PWD/.claude/memory.jsonl" \
  -- npx -y @modelcontextprotocol/server-memory

功能:

  • 持久化知識儲存
  • 實體和關係追蹤
  • 跨工作階段記憶
  • 以關鍵字搜尋實體名稱、類型與觀察內容

⚠️ 重要: 如果沒有設定 MEMORY_FILE_PATH,所有專案會共用同一個記憶檔案!改用相對路徑也無法解決:伺服器會以自己的套件目錄(而非你的專案)來解析相對路徑,所以請一律使用絕對路徑(以 ~/ 開頭也可以)。

3. Git 操作

# The official Git server is a Python package; run it with uv's uvx
claude mcp add --scope project git \
  -- uvx mcp-server-git --repository .

功能:

  • Git status、log、diff
  • 分支操作
  • 提交歷史
  • 暫存與提交

4. GitHub 整合

# GitHub's remote MCP server, authenticated with a fine-grained personal access token
claude mcp add --transport http --scope user github \
  https://api.githubcopilot.com/mcp/ \
  --header "Authorization: Bearer <your-github-pat>"

功能:

  • Issues 和 PRs
  • 儲存庫管理
  • 程式碼搜尋
  • Actions 工作流程

5. 循序思考

claude mcp add --scope user sequential-thinking \
  -- npx -y @modelcontextprotocol/server-sequential-thinking

功能:

  • 結構化推理
  • 多步驟分析
  • 複雜問題分解

6. Context7(即時文件)

# Remote server; an API key is optional but recommended for higher rate limits
claude mcp add --transport http --scope user context7 \
  https://mcp.context7.com/mcp \
  --header "Authorization: Bearer <your-context7-api-key>"

功能:

  • 即時官方文件
  • 最新函式庫參考
  • 框架指引

資料庫 MCP 伺服器

PostgreSQL

# DBHub (@bytebase/dbhub) is the example the Claude Code docs use.
# Connect with a read-only database user.
claude mcp add --transport stdio db \
  -- npx -y @bytebase/dbhub \
  --dsn "postgresql://readonly:pass@localhost:5432/db"

功能:

  • SQL 執行(execute_sql)
  • Schema 與資料表搜尋(search_objects)
  • 查詢計畫與健康檢查(需選擇啟用的工具)
  • 也支援 MySQL、MariaDB、SQL Server、Oracle 與 SQLite

SQLite

claude mcp add sqlite \
  -- npx -y @bytebase/dbhub --dsn "sqlite:///path/to/app.db"

MongoDB

# MongoDB's official server; --readOnly blocks create/update/delete tools
claude mcp add mongodb \
  -e MDB_MCP_CONNECTION_STRING="mongodb://localhost:27017/db" \
  -- npx -y mongodb-mcp-server@latest --readOnly

雲端服務 MCP 伺服器

AWS

# AWS MCP Server (managed, OAuth sign-in); pick your Region's endpoint
claude mcp add --transport http --scope user aws-mcp \
  https://aws-mcp.us-east-1.api.aws/mcp

Cloudflare

# Cloudflare API MCP Server: sign in with OAuth from /mcp,
# or add --header "Authorization: Bearer <api-token>"
claude mcp add --transport http --scope user cloudflare \
  https://mcp.cloudflare.com/mcp

Vercel

# Vercel's official remote server; authenticate from /mcp
claude mcp add --transport http --scope user vercel \
  https://mcp.vercel.com

使用 OAuth 的遠端伺服器,請在 Claude Code 內執行 /mcp(或 claude mcp login <name>)完成登入。

MCP 設定檔

專案伺服器(.mcp.json)

claude mcp add --scope project 會寫入專案根目錄的 .mcp.json。把它提交到版本控制,整個團隊就會使用相同的伺服器。command、args、env、url 與 headers 中的 ${VAR} 和 ${VAR:-default} 都會被展開:

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
    },
    "db": {
      "command": "npx",
      "args": ["-y", "@bytebase/dbhub", "--dsn", "${DATABASE_URL}"]
    },
    "docs-api": {
      "type": "http",
      "url": "${API_BASE_URL:-https://api.example.com}/mcp",
      "headers": {
        "Authorization": "Bearer ${API_KEY}"
      }
    }
  }
}

在互動式工作階段中,Claude Code 會先詢問你是否核准 .mcp.json 裡的伺服器。若要預先核准,請在 .claude/settings.local.json 或 ~/.claude/settings.json 設定 enableAllProjectMcpServers(或在 enabledMcpjsonServers 列出名稱)。同樣的設定若提交在專案的 .claude/settings.json,在你信任該資料夾之前都會被忽略。

本機與使用者伺服器(~/.claude.json)

本機範圍(預設)與使用者範圍的伺服器存放在 ~/.claude.json,由 Claude Code 代為管理。本機伺服器放在該專案的項目底下;使用者伺服器則放在最上層的 mcpServers:

{
  "mcpServers": {
    "github": {
      "type": "http",
      "url": "https://api.githubcopilot.com/mcp/",
      "headers": {
        "Authorization": "Bearer <your-github-pat>"
      }
    },
    "sequential-thinking": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-sequential-thinking"]
    }
  }
}

請優先使用 claude mcp add / claude mcp remove,而不是手動編輯這個檔案。不要在 settings.json 放 mcpServers 區塊:設定檔存放的是核准與政策(例如 enableAllProjectMcpServers 或 allowedMcpServers),而不是你的伺服器定義。唯一的例外是 managedMcpServers,只有組織能在受管理設定中使用。

MCP 範圍和層級

MCP 伺服器來自三個範圍,再加上組織管理的設定:

┌─────────────────────────────────────────────┐
│  Organization (managed)                      │
│  managed-mcp.json or managedMcpServers       │
│  allowedMcpServers / deniedMcpServers        │
├─────────────────────────────────────────────┤
│  Local scope (default)                       │
│  ~/.claude.json, this project only           │
│  Use: personal or credentialed servers       │
├─────────────────────────────────────────────┤
│  Project scope                               │
│  .mcp.json in the project root               │
│  Use: team-shared servers (committed)        │
├─────────────────────────────────────────────┤
│  User scope                                  │
│  ~/.claude.json, all your projects           │
│  Use: personal tools (github, docs)          │
└─────────────────────────────────────────────┘

優先順序: Local > Project > User > 外掛提供的伺服器 > claude.ai connectors。同一個伺服器在多處定義時,Claude Code 會採用優先順序最高來源的完整設定(欄位不會合併)。組織透過 managedMcpServers 提供的伺服器,優先順序高於上述所有來源。

MCP 上下文成本

每個工具定義在載入時都會消耗上下文 token。以下是本指南在 2026 年 1 月發布時列出的約略預先載入成本:

MCP 伺服器約略 Token 數建議
hubspot~1,800✅ 小,推薦
netlify~2,000✅ 小,推薦
figma~2,500✅ 可接受
notion已優化✅ 官方優化
vercel~3,000✅ 可接受
stripe~4,000⚠️ 中等
linear~6,200⚠️ 偏大
atlassian~7,100⚠️ 偏大
asana~12,800❌ 太大
sentry~14,000❌ 太大,謹慎使用

最佳實踐: 只啟用實際使用的 MCP 伺服器。每個已連線的伺服器仍會在每個工作階段加入工具名稱與伺服器說明,伺服器越多,啟動時的工作也越多。

Tool search(預設開啟): Claude Code 會延遲載入 MCP 工具定義,並透過 ToolSearch 工具按需載入,因此工作階段開始時只會載入工具名稱與伺服器說明。在設定 ENABLE_TOOL_SEARCH=false、伺服器標記 "alwaysLoad": true,或模型與部署不支援 tool search 時,工具仍會預先載入。ENABLE_TOOL_SEARCH=auto(或 auto:N)會在工具定義未達 context window 的 10%(或 N%)前預先載入。執行 /context 可查看工作階段實際的消耗。

MCP 管理指令

# List all MCP servers with a health status
claude mcp list

# Add a new server
claude mcp add --scope project <name> -- <command>

# Add a server from a JSON config block
claude mcp add-json <name> '<json>'

# Inspect one server (status, approval, last error)
claude mcp get <name>

# Remove a server
claude mcp remove --scope project <name>

# Reset approvals for project .mcp.json servers (troubleshooting)
claude mcp reset-project-choices

# Inside a session: status, OAuth sign-in, enable/disable, reconnect
/mcp

實際使用 MCP

範例 1:資料庫查詢

啟用資料庫 MCP(例如 DBHub)後:

使用者:「顯示最近 7 天註冊的使用者」

Claude:[使用 db MCP]
  → 查詢:SELECT * FROM users WHERE created_at > NOW() - INTERVAL '7 days'
  → 回傳格式化結果
  → 如果查詢緩慢,建議索引

範例 2:知識持久化

啟用 memory MCP 後:

使用者:「記住我們所有 API 驗證都使用 Zod」

Claude:[使用 memory MCP]
  → 建立實體:"API Validation"
  → 新增觀察:"Use Zod for all API validation"
  → 在未來的工作階段中可用

範例 3:GitHub 整合

啟用 github MCP 後:

使用者:「為我們討論的登入 bug 建立一個 issue」

Claude:[使用 github MCP]
  → 建立帶有標題、內容、標籤的 issue
  → 連結到相關程式碼
  → 如果有指定,指派給團隊成員

Memory MCP 深入探討

Memory MCP 值得特別關注,因為它能實現持久化的專案知識。

Memory 指令

伺服器提供九個由 Claude 直接呼叫的工具:create_entities、create_relations、add_observations、delete_entities、delete_observations、delete_relations、read_graph、search_nodes 與 open_nodes。直接說「記住……」就足夠了。若想要捷徑,可以把這些工具包成自訂 skills;它們並非 Claude Code 內建:

# Custom skills you can create for memory management
/memory-save    # Save important knowledge
/memory-search  # Search saved knowledge
/memory-list    # List all entities
/memory-audit   # Check memory health

Memory 結構

read_graph 會以下列結構回傳知識圖譜(在磁碟上,伺服器會以 .jsonl 檔案每行儲存一個 JSON 物件):

{
  "entities": [
    {
      "name": "Authentication System",
      "entityType": "Architecture",
      "observations": [
        "Uses JWT with 24-hour expiration",
        "Refresh tokens stored in httpOnly cookies",
        "Located in src/lib/auth.ts"
      ]
    },
    {
      "name": "Database Schema",
      "entityType": "Infrastructure",
      "observations": [
        "PostgreSQL with Prisma ORM",
        "Users table has email_verified column",
        "Soft deletes using deleted_at"
      ]
    }
  ],
  "relations": [
    {
      "from": "Authentication System",
      "to": "Database Schema",
      "relationType": "uses"
    }
  ]
}

Memory 最佳實踐

## 應該儲存的內容
✅ 架構決策和理由
✅ 程式碼模式和慣例
✅ Bug 修復和根本原因
✅ 重要的設定細節
✅ 團隊決策和限制

## 不應該儲存的內容
❌ 臨時除錯資訊
❌ 一次性的實作細節
❌ 已經在 CLAUDE.md 中的資訊
❌ 經常變動的資料

MCP 疑難排解

伺服器無法載入

# Check if server is registered and healthy
claude mcp list

# See one server's status and last error
claude mcp get <name>

# Verify the project config file
cat .mcp.json

# Reset approvals and re-add
claude mcp reset-project-choices
claude mcp add --scope project <name> -- <command>

權限問題

.mcp.json 裡的專案伺服器,在你於互動式工作階段核准前,會一直停在「Pending approval」。若要預先核准,請在 .claude/settings.local.json 或 ~/.claude/settings.json 加入:

{
  "enableAllProjectMcpServers": true
}

列在 disabledMcpjsonServers 中的伺服器,無論如何都會維持被拒絕。

環境變數問題

在 .mcp.json 中使用 ${VAR_NAME}(或 ${VAR_NAME:-default})語法:

{
  "env": {
    "DATABASE_URL": "${DATABASE_URL}"
  }
}

或直接使用 -e 參數提供:

claude mcp add --scope project mongodb \
  -e MDB_MCP_CONNECTION_STRING="mongodb://..." \
  -- npx -y mongodb-mcp-server@latest --readOnly

未設定且沒有預設值的 ${VAR} 會保持原樣不展開,並在 claude mcp list 顯示警告。在遠端伺服器的 url 與 headers 中,ANTHROPIC_API_KEY 等憑證變數一律會被讀成空值,請把 token 複製到你自己命名的變數。

實用的環境變數

變數用途
MCP_TIMEOUT伺服器啟動逾時,單位毫秒(預設 30000)
MCP_TOOL_TIMEOUT工具執行逾時,單位毫秒
MAX_MCP_OUTPUT_TOKENS單次 MCP 工具結果的 token 上限(預設 25000;超過 10,000 會警告)
ENABLE_TOOL_SEARCHtrue(預設行為)、auto、auto:N 或 false
MCP_CONNECTION_NONBLOCKING設為 0 時,會等伺服器連線後才處理第一個提示

企業 MCP 管理

管理員透過受管理的設定來控制 MCP 伺服器:

  • managed-mcp.json 部署一組固定的伺服器並取得獨占控制(macOS 為 /Library/Application Support/ClaudeCode/,Linux 與 WSL 為 /etc/claude-code/,Windows 為 C:\Program Files\ClaudeCode\)。
  • 受管理設定中的 managedMcpServers 會在使用者自己的伺服器之外,為每位使用者提供伺服器。
  • allowedMcpServers / deniedMcpServers 限制哪些伺服器可以載入。每個項目只能有一個鍵:serverName、serverCommand 或 serverUrl。拒絕清單優先於允許清單。
// managed-settings.json
{
  "allowManagedMcpServersOnly": true,
  "allowedMcpServers": [
    { "serverName": "github" },
    { "serverCommand": ["npx", "-y", "@modelcontextprotocol/server-filesystem"] },
    { "serverUrl": "https://mcp.example.com/*" }
  ]
}

設定 allowManagedMcpServersOnly 後,使用者、專案與本機的允許清單都無法放寬受管理的清單,使用者也就無法載入未經核准的 MCP 伺服器。

建立自訂 MCP 伺服器

您可以為特殊需求建立自訂 MCP 伺服器。協定規格在 modelcontextprotocol.io。官方「Build an MCP server」指南使用 TypeScript SDK v2(npm install @modelcontextprotocol/server zod,需要 Node.js 20 以上)。

基本結構

import { McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import { z } from 'zod';

// serveStdio calls this whenever it needs an instance,
// so return a fresh server every time
function createServer() {
  const server = new McpServer({ name: 'my-custom-mcp', version: '1.0.0' });

  server.registerTool(
    'my_tool',
    {
      description: 'Does something useful',
      inputSchema: z.object({
        input: z.string().describe('What to process'),
      }),
    },
    async ({ input }) => ({
      content: [{ type: 'text', text: `Processed: ${input}` }],
    }),
  );

  return server;
}

serveStdio(createServer, {
  onerror: (error) => console.error('my-custom-mcp error:', error),
});

建置後再註冊:claude mcp add my-custom-mcp -- node /path/to/build/index.js。

MCP 與其他工具比較

功能MCP內建工具Hooks
外部資料存取✅ 主要用途❌ 有限❌ 否
持久化儲存✅ Memory MCP✅ 內建 auto memory❌ 否
自訂整合✅ 可擴展❌ 固定✅ 透過指令
上下文成本變動(啟用 tool search 時偏低)已包含最小
設定複雜度中等無低

開始使用 MCP

今天:

  1. 在專案中新增 filesystem 和 memory MCP
  2. 使用絕對路徑的 MEMORY_FILE_PATH 進行專案隔離
  3. 將一個重要決策儲存到 memory

本週:

  1. 如果適用,新增資料庫 MCP
  2. 設定 GitHub MCP 進行 issue 追蹤
  3. 探索 memory 工具(或打造自己的 /memory-* skills)

本月:

  1. 優化 MCP 選擇以提高上下文效率
  2. 建立專案專屬的 MCP 設定
  3. 考慮為特殊需求建立自訂 MCP

MCP 將 Claude Code 從獨立助手轉變為整合開發平台。明智地選擇伺服器,釋放 Claude 的全部潛力。

來源:Model Context Protocol、Claude Code MCP 文件、MCP 伺服器儲存庫