跳至主要內容
精選 MCP Tools Integration Configuration

MCP (Model Context Protocol):完整指南

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

2026年1月10日 18 分鐘閱讀 作者:ClaudeWorld

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

什麼是 MCP?

根據 Anthropic 官方文件,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 文件,請務必使用 CLI:

# Basic syntax
claude mcp add [--scope <scope>] <name> [options] -- <command>

# Scopes:
# --scope user     → ~/.claude/settings.json (all projects)
# --scope project  → .claude/settings.json (this project)

常用 MCP 伺服器

1. 檔案系統存取

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

功能:

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

2. 記憶(知識圖譜)

# IMPORTANT: Always use MEMORY_FILE_PATH for project isolation
claude mcp add --scope project memory \
  -e MEMORY_FILE_PATH=./.claude/memory.json \
  -- npx -y @modelcontextprotocol/server-memory

功能:

  • 持久化知識儲存
  • 實體和關係追蹤
  • 跨工作階段記憶
  • 語意搜尋

⚠️ 重要: 如果沒有設定 MEMORY_FILE_PATH,所有專案會共用同一個記憶檔案!

3. Git 操作

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

功能:

  • Git status、log、diff
  • 分支操作
  • 提交歷史
  • 檔案追溯(blame)

4. GitHub 整合

claude mcp add --scope user github \
  -e GITHUB_TOKEN=<your-token> \
  -- npx -y @modelcontextprotocol/server-github

功能:

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

5. 循序思考

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

功能:

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

6. Context7(即時文件)

claude mcp add --scope user context7 \
  -- npx -y context7-mcp

功能:

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

資料庫 MCP 伺服器

PostgreSQL

claude mcp add --scope project postgres \
  -e DATABASE_URL="postgresql://user:pass@localhost:5432/db" \
  -- npx -y @modelcontextprotocol/server-postgres

功能:

  • 查詢執行
  • Schema 檢視
  • 資料表操作
  • Migration 支援

SQLite

claude mcp add --scope project sqlite \
  -e DATABASE_PATH="./data/app.db" \
  -- npx -y @modelcontextprotocol/server-sqlite

MongoDB

claude mcp add --scope project mongodb \
  -e MONGODB_URI="mongodb://localhost:27017/db" \
  -- npx -y @modelcontextprotocol/server-mongodb

雲端服務 MCP 伺服器

AWS

claude mcp add --scope user aws \
  -e AWS_ACCESS_KEY_ID=<key> \
  -e AWS_SECRET_ACCESS_KEY=<secret> \
  -e AWS_REGION=us-east-1 \
  -- npx -y @modelcontextprotocol/server-aws

Cloudflare

claude mcp add --scope user cloudflare \
  -e CLOUDFLARE_API_TOKEN=<token> \
  -- npx -y @anthropic/cloudflare-mcp

Vercel

claude mcp add --scope user vercel \
  -e VERCEL_TOKEN=<token> \
  -- npx -y vercel-mcp

MCP 設定檔

專案設定 (.claude/settings.json)

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
    },
    "memory": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-memory"],
      "env": {
        "MEMORY_FILE_PATH": "./.claude/memory.json"
      }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "${DATABASE_URL}"
      }
    }
  },
  "enableAllProjectMcpServers": true
}

使用者設定 (~/.claude/settings.json)

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

MCP 範圍和層級

MCP 伺服器遵循 Claude Code 的四層層級架構:

┌─────────────────────────────────────────────┐
│  Layer 1: Enterprise                         │
│  Location: /etc/claude-code/settings.json    │
│  Control: IT department                      │
│  Use: Restrict MCP servers via allowlist     │
├─────────────────────────────────────────────┤
│  Layer 2: User Global                        │
│  Location: ~/.claude/settings.json           │
│  Use: Personal MCP servers (github, etc.)    │
├─────────────────────────────────────────────┤
│  Layer 3: Project                            │
│  Location: .claude/settings.json             │
│  Use: Project-specific servers (db, memory)  │
├─────────────────────────────────────────────┤
│  Layer 4: Project Local                      │
│  Location: .claude/settings.local.json       │
│  Use: Personal overrides (gitignored)        │
└─────────────────────────────────────────────┘

優先順序: Local > Project > User > Enterprise

MCP 上下文成本

每個 MCP 伺服器都會消耗上下文 token。請注意成本:

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 伺服器。更多伺服器 = 更多上下文 = 更高成本和更慢的回應。

MCP 管理指令

# List all MCP servers
claude mcp list

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

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

# Check server status
claude mcp status

# Reset project MCP choices (troubleshooting)
claude mcp reset-project-choices

實際使用 MCP

範例 1:資料庫查詢

啟用 postgres MCP 後:

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

Claude:[使用 postgres 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 指令

# Built-in skills for memory management
/memory-save    # Save important knowledge
/memory-search  # Search saved knowledge
/memory-list    # List all entities
/memory-audit   # Check memory health

Memory 結構

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

Memory 最佳實踐

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

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

MCP 疑難排解

伺服器無法載入

# Check if server is registered
claude mcp list

# Verify settings file
cat .claude/settings.json

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

權限問題

確保專案設定中有 enableAllProjectMcpServers: true

{
  "enableAllProjectMcpServers": true,
  "mcpServers": { ... }
}

環境變數問題

使用 ${VAR_NAME} 語法來引用環境變數:

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

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

claude mcp add --scope project postgres \
  -e DATABASE_URL="postgresql://..." \
  -- npx -y @modelcontextprotocol/server-postgres

企業 MCP 管理

對於企業環境,使用 allowlist 來控制可以使用哪些 MCP 伺服器:

// /etc/claude-code/settings.json
{
  "mcpServers": {
    "allowlist": [
      "filesystem",
      "memory",
      "git"
    ]
  }
}

這可以防止使用者新增未授權的 MCP 伺服器。

建立自訂 MCP 伺服器

您可以為特殊需求建立自訂 MCP 伺服器。協定規格在 modelcontextprotocol.io

基本結構

import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

const server = new Server(
  { name: 'my-custom-mcp', version: '1.0.0' },
  { capabilities: { tools: {} } }
);

server.setRequestHandler('tools/list', async () => ({
  tools: [
    {
      name: 'my_tool',
      description: 'Does something useful',
      inputSchema: {
        type: 'object',
        properties: {
          input: { type: 'string' }
        }
      }
    }
  ]
}));

server.setRequestHandler('tools/call', async (request) => {
  // Handle tool calls
});

const transport = new StdioServerTransport();
await server.connect(transport);

MCP 與其他工具比較

功能MCP內建工具Hooks
外部資料存取✅ 主要用途❌ 有限❌ 否
持久化儲存✅ Memory MCP❌ 僅限工作階段❌ 否
自訂整合✅ 可擴展❌ 固定✅ 透過指令
上下文成本變動已包含最小
設定複雜度中等

開始使用 MCP

今天:

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

本週:

  1. 如果適用,新增資料庫 MCP
  2. 設定 GitHub MCP 進行 issue 追蹤
  3. 探索 memory 指令(/memory-*)

本月:

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

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

來源:Model Context ProtocolClaude Code 文件MCP 伺服器儲存庫