跳至主要內容
模組 3:真實架構 2 / 6
進階 S14 MCP Protocol

MCP 整合

精通 Model Context Protocol 作為工具擴展系統。

2026年3月20日 22 分鐘閱讀
已校驗 課程最近校驗: 2026年10月21日

你將學到什麼

Claude Code 內建了一套強大的工具 — Read、Edit、Write、Bash、WebFetch 等。但如果你需要查詢資料庫呢?搜尋公司 Wiki?與部署管線互動?你可以讓 Claude 透過 shell 呼叫 curl,但有更好的方式:Model Context Protocol (MCP)。

完成後,你將了解:

  • MCP 是什麼以及為什麼它存在
  • MCP 伺服器如何提供工具、資源和提示
  • 客戶端-伺服器架構和傳輸機制
  • 如何在你的專案中設定 MCP 伺服器
  • MCP 工具如何與 Claude Code 的權限系統整合
  • 如何從零開始建構一個簡單的 MCP 伺服器

問題是什麼

每個團隊都有自己的工具。前端團隊需要 Figma 整合。資料團隊需要 SQL 存取。DevOps 團隊需要 Kubernetes 控制。將每個整合直接建構到 Claude Code 中會:

  1. 維護上不可能 — 數千個整合,每個都有不同的 API
  2. 安全上的噩夢 — 每個整合都需要隨 Claude Code 一起發布
  3. 不夠靈活 — 組織無法添加自己的內部工具

這個模式在其他領域很常見。Web 瀏覽器不會內建每個功能 — 它們支援擴充功能。程式碼編輯器不會打包每種語言 — 它們支援外掛。Claude Code 也需要同樣的東西:一個工具擴展的標準協議。

Without MCP:
┌──────────────────────────────────────────┐
│  Claude Code                             │
│                                          │
│  Built-in: Read, Edit, Write, Bash...    │
│  Custom:   ??? (fork the codebase?)      │
└──────────────────────────────────────────┘

With MCP:
┌──────────────────────────────────────────┐
│  Claude Code                             │
│                                          │
│  Built-in: Read, Edit, Write, Bash...    │
│  MCP:      Database, Jira, Slack,        │
│            Figma, K8s, your-custom-tool  │
└──────────────────────────────────────────┘

如何運作

MCP 架構

MCP 遵循客戶端-伺服器模型。Claude Code 是客戶端。每個外部整合是一個伺服器。它們透過標準協議通訊:

┌─────────────────────────────────────────────────────┐
│  Claude Code (MCP Client)                           │
│                                                     │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐         │
│  │ Built-in │  │ MCP Conn │  │ MCP Conn │  ...     │
│  │ Tools    │  │    #1    │  │    #2    │         │
│  └──────────┘  └────┬─────┘  └────┬─────┘         │
│                     │              │                │
└─────────────────────│──────────────│────────────────┘
                      │              │
              ┌───────▼──────┐ ┌────▼─────────┐
              │ MCP Server   │ │ MCP Server   │
              │ (Database)   │ │ (Jira)       │
              │              │ │              │
              │ Tools:       │ │ Tools:       │
              │  - query     │ │  - search    │
              │  - schema    │ │  - create    │
              │  - explain   │ │  - update    │
              └──────────────┘ └──────────────┘

每個 MCP 伺服器是一個獨立的程序或遠端服務。Claude Code 連接到它,發現它提供哪些能力,並將它的工具與內建工具一起提供給 AI 使用。

MCP 伺服器提供什麼

一個 MCP 伺服器可以暴露三種類型的能力:

1. 工具 — AI 可以呼叫的函式(最常見)

{
  "name": "database_query",
  "description": "Execute a read-only SQL query against the project database",
  "inputSchema": {
    "type": "object",
    "properties": {
      "sql": { "type": "string", "description": "The SQL query to execute" }
    },
    "required": ["sql"]
  }
}

2. 資源 — AI 可以讀取的資料(檔案、文件、即時資料)

{
  "uri": "db://schema/users",
  "name": "Users table schema",
  "mimeType": "application/json"
}

在 Claude Code 中,用 @server:protocol://resource/path 形式的 @ mention 引用資源,例如 @github:issue://123。

3. 提示 — 可重用的提示模板

{
  "name": "code_review",
  "description": "Review code for common issues",
  "arguments": [
    { "name": "language", "description": "Programming language" }
  ]
}

Claude Code 會把伺服器的 prompts 列為指令,例如 /mcp__github__pr_review 456。

實際上,工具是目前最常見的。當 AI 決定使用 MCP 工具時,呼叫會透過與內建工具相同的 agent loop 流動。

傳輸機制

Claude Code 可透過幾種傳輸方式連接 MCP 伺服器,其中兩種幾乎涵蓋所有情境:

stdio — 用於本地程序(最常見)

Claude Code ──stdin/stdout──► MCP Server Process

伺服器作為子程序運行,雙方透過它的 stdin 與 stdout 交換 JSON-RPC 訊息。這種方式快速、不需要網路設定,但伺服器會以你的使用者帳號完整權限執行,而且不在 Claude Code 的 Bash sandbox 內,因此只執行你信任的伺服器。stdio 伺服器絕不能把 log 寫到 stdout,否則會破壞訊息串流;請改寫到 stderr。

HTTP(Streamable HTTP) — 用於遠端伺服器(建議)

Claude Code ──HTTPS──► Remote MCP Server
                       (running on a server)

伺服器運行在遠端機器上,整個團隊都能共用。HTTP 是建議的遠端傳輸方式,並支援 OAuth 登入。較舊的 SSE 傳輸已被棄用,只在服務沒有其他選項時使用。Claude Code 也接受在 JSON 設定中宣告的 WebSocket 伺服器("type": "ws")。

設定

MCP 伺服器可以設定在三種 scope:

Scope載入範圍儲存位置
Local(預設)目前專案,只對你生效~/.claude.json
Project目前專案,透過版本控制與團隊共享專案根目錄的 .mcp.json
User你的所有專案~/.claude.json

claude mcp 指令會替你寫入這些檔案:

# Remote server over HTTP, shared with the team through .mcp.json
claude mcp add --transport http --scope project company-wiki https://mcp.internal.example.com/wiki

# Local stdio server: everything after -- is the command that starts it
claude mcp add --transport stdio memory -- npx -y @modelcontextprotocol/server-memory

claude mcp list          # configured servers and their status
claude mcp get memory    # details for one server

在 session 內,/mcp 會顯示每個伺服器的狀態並處理登入。專案的 .mcp.json 長這樣:

{
  "mcpServers": {
    "database": {
      "type": "stdio",
      "command": "node",
      "args": ["./mcp/database-server.mjs"],
      "env": { "DATABASE_URL": "${DATABASE_URL}" }
    },
    "memory": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-memory"]
    },
    "company-wiki": {
      "type": "http",
      "url": "https://mcp.internal.example.com/wiki"
    }
  }
}

每個條目定義了:

  • 名稱 — 工具的前綴方式(例如 mcp__database__query)
  • command/url — 如何啟動或連接到伺服器
  • type — 本地程序用 stdio,遠端伺服器用 http(sse 已棄用)

這裡的 database 代表一個專案自有的伺服器(就像下文要建構的那種),提供 query、schema、explain 工具;memory 則是官方參考實作的 knowledge-graph 伺服器。Claude Code 會從你的環境變數展開 ${DATABASE_URL},因此 credentials 不會出現在提交的檔案中。

因為任何人都能提交 .mcp.json,Claude Code 會在你第一次於該專案啟動互動式 session 時,要求你核准其中的伺服器;claude mcp reset-project-choices 可重設這些選擇。claude -p 與 Agent SDK sessions 無法顯示這個提示,會直接連接專案伺服器,因此對非自己撰寫的 repository 編寫自動化腳本時,請加上 --strict-mcp-config 或設定 disabledMcpjsonServers。

工具發現

啟動時,Claude Code 連接到每個已設定的 MCP 伺服器並詢問:「你提供哪些工具?」

Startup sequence:
─────────────────

1. Claude Code reads MCP config (.mcp.json, ~/.claude.json, plugins)
2. For each server:
   a. Spawn process (stdio) or connect (http)
   b. Send: { "method": "tools/list" }
   c. Receive: list of tool definitions
   d. Register tools with naming convention

Result:
┌──────────────────────────────────────────────┐
│  Available Tools                             │
│                                              │
│  Built-in:                                   │
│    Read, Edit, Write, Bash, Agent,           │
│    WebFetch, ToolSearch...                   │
│                                              │
│  MCP (database):                             │
│    mcp__database__query                      │
│    mcp__database__schema                     │
│    mcp__database__explain                    │
│                                              │
│  MCP (memory):                               │
│    mcp__memory__add_observations             │
│    mcp__memory__search_nodes                 │
│    mcp__memory__read_graph                   │
└──────────────────────────────────────────────┘

命名規則 mcp__<server>__<tool> 可以防止衝突。如果兩個伺服器都有名為 search 的工具,它們會變成 mcp__wiki__search 和 mcp__jira__search。

在目前的模型上,tool search 預設開啟:session 啟動時只載入工具名稱與伺服器 instructions,Claude 需要某個工具時,才透過內建的 ToolSearch 工具載入完整定義。因此已連接的伺服器在實際使用前只占用很少的 context。設定 ENABLE_TOOL_SEARCH=false 可在啟動時載入所有 MCP 工具定義。

權限整合

MCP 工具會經過與內建工具相同的權限系統。這對安全性至關重要:

AI decides to call mcp__database__query
         │
         ▼
┌──────────────────────────┐
│ Permission check         │
│                          │
│ - PreToolUse hooks       │
│ - deny / ask / allow     │
│   rules                  │
│ - permission mode        │
└───┬──────────┬───────┬───┘
    │          │       │
  allow       ask     deny
    │          │       │
    ▼          ▼       ▼
 Execute    Prompt  Blocked
  tool     the user

MCP 權限規則使用相同的名稱:mcp__database__query 比對單一工具,mcp__database__* 比對該伺服器的所有工具。在 auto 模式中,分類器會取代大多數提示,但明確的 ask 規則仍會詢問你。PreToolUse hook(第 15 堂課)可以用 mcp__database__.* 這類 matcher 檢查 MCP 工具呼叫並阻止危險的操作。

通訊流程

以下是 AI 使用 MCP 工具時的完整流程:

User: "How many users signed up this week?"
         │
         ▼
┌─────────────────────────────────────────────┐
│  Agent Loop                                  │
│                                              │
│  AI decides: use mcp__database__query        │
│  Input: "SELECT COUNT(*) FROM users          │
│          WHERE created_at > NOW() - '7d'"    │
│                                              │
│  Permission check → allowed                  │
│         │                                    │
│         ▼                                    │
│  Claude Code sends to MCP server:            │
│  { "method": "tools/call",                   │
│    "params": {                               │
│      "name": "query",                        │
│      "arguments": { "sql": "SELECT..." }     │
│    }                                         │
│  }                                           │
│         │                                    │
│         ▼                                    │
│  MCP server executes query, returns:         │
│  { "result": { "content": [                  │
│      { "type": "text", "text": "142" }       │
│    ]}                                        │
│  }                                           │
│         │                                    │
│         ▼                                    │
│  Result injected as tool_result              │
│  AI continues: "142 users signed up..."      │
└─────────────────────────────────────────────┘

從 AI 的角度來看,MCP 工具的用法與內建工具相同:載入定義後,用正確的參數呼叫它,並得到結果回傳。協議處理了中間的一切。

關鍵洞見

MCP 讓 Claude Code 在不改變核心的情況下獲得無限的可擴展性。 不是將整合建構到程式碼庫中,MCP 讓你透過標準協議接入任何工具。

這反映了軟體中一個經過驗證的模式:

系統核心擴展協議
Web 瀏覽器渲染引擎Extension APIs
VS Code編輯器核心Language Server Protocol
UnixKernelstdin/stdout 管道
Claude CodeAgent loopMCP

關鍵在於標準。因為 MCP 是一個開放協議,任何人都可以建構伺服器。生態系統可以獨立於 Claude Code 本身成長。一個團隊建構的資料庫 MCP 伺服器可以與任何 MCP 客戶端一起工作 — 不只是 Claude Code。

實作範例

建構一個簡單的 MCP 伺服器

以下伺服器使用官方 MCP server guide 採用的 2.x TypeScript server 套件。請在腳本旁安裝(需要 Node.js 20 以上):

npm install @modelcontextprotocol/server zod

這是一個最小的 MCP 伺服器,提供單一工具 — 字數計數器:

// word-counter-server.mjs
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";

// serveStdio may call this factory more than once, so return a new server each time
function createServer() {
  const server = new McpServer({
    name: "word-counter",
    version: "1.0.0",
  });

  // Register a tool
  server.registerTool(
    "count_words",
    {
      description: "Count words in a given text",
      inputSchema: z.object({
        text: z.string().describe("The text to count words in"),
      }),
    },
    async ({ text }) => {
      const wordCount = text.split(/\s+/).filter(Boolean).length;
      const charCount = text.length;
      return {
        content: [
          {
            type: "text",
            text: `Words: ${wordCount}, Characters: ${charCount}`,
          },
        ],
      };
    },
  );

  return server;
}

// Serve over stdio; log to stderr only, because stdout carries the protocol
serveStdio(createServer, {
  onerror: (error) => console.error("word-counter error:", error),
});

serveStdio 會與每個客戶端協商協議版本。以 1.x @modelcontextprotocol/sdk 套件建構的伺服器(其中 server.tool() 已棄用,改用 registerTool())仍能以較早的協議版本連接 Claude Code。

連接到 Claude Code

為專案註冊這個伺服器:

claude mcp add --transport stdio --scope project wordcount -- node word-counter-server.mjs

這個指令會在專案的 .mcp.json 中加入類似以下的條目,你也可以手動撰寫:

{
  "mcpServers": {
    "wordcount": {
      "type": "stdio",
      "command": "node",
      "args": ["word-counter-server.mjs"]
    }
  }
}

下次在這個專案中啟動 Claude Code 時,依提示核准 wordcount 伺服器,並確認 /mcp 顯示它已連線。之後 AI 就能存取 mcp__wordcount__count_words。你可以問「這段文字有多少字?」AI 就會使用你的自訂工具。

更實用的範例:檔案中繼資料伺服器

// file-metadata-server.mjs
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";
import fs from "fs/promises";
import path from "path";

function createServer() {
  const server = new McpServer({
    name: "file-metadata",
    version: "1.0.0",
  });

  server.registerTool(
    "file_stats",
    {
      description: "Get detailed metadata about a file (size, dates, permissions)",
      inputSchema: z.object({
        file_path: z.string().describe("Path to the file"),
      }),
    },
    async ({ file_path }) => {
      const stats = await fs.stat(file_path);
      return {
        content: [{
          type: "text",
          text: JSON.stringify({
            size_bytes: stats.size,
            created: stats.birthtime.toISOString(),
            modified: stats.mtime.toISOString(),
            is_directory: stats.isDirectory(),
            permissions: stats.mode.toString(8),
          }, null, 2),
        }],
      };
    },
  );

  server.registerTool(
    "directory_size",
    {
      description: "Total the size of the files directly inside a directory (not recursive)",
      inputSchema: z.object({
        dir_path: z.string().describe("Path to the directory"),
      }),
    },
    async ({ dir_path }) => {
      let totalSize = 0;
      const entries = await fs.readdir(dir_path, { withFileTypes: true });
      for (const entry of entries) {
        if (entry.isFile()) {
          const stat = await fs.stat(path.join(dir_path, entry.name));
          totalSize += stat.size;
        }
      }
      return {
        content: [{
          type: "text",
          text: `Total size: ${(totalSize / 1024).toFixed(1)} KB (${entries.length} entries)`,
        }],
      };
    },
  );

  return server;
}

serveStdio(createServer, {
  onerror: (error) => console.error("file-metadata error:", error),
});

這讓 AI 獲得了兩個以前沒有的新能力 — 詳細的檔案中繼資料和目錄大小計算 — 完全不需要修改 Claude Code 本身。

這個示範會信任收到的任何路徑。正式的伺服器應把路徑限制在專案內:Claude Code 會在 stdio 伺服器的環境中設定 CLAUDE_PROJECT_DIR,並以 session 的工作目錄回應 MCP 的 roots/list 請求。

前後對比

沒有 MCP有 MCP
固定的內建工具集無限的可擴展性
新整合需要修改程式碼放入一個伺服器設定即可
每個使用者得到相同的工具團隊可自訂工具集
AI 透過 shell 執行自訂工作AI 使用結構化、有型別的工具
沒有工具擴展的標準開放協議,不斷成長的生態系統
安全性是各整合各自處理統一的權限系統

下一堂課

MCP 讓你可以添加工具。但你如何強制執行工具使用的規則呢?第 15 堂課介紹 Hooks 系統 — 在工具執行前後觸發的事件訂閱者,讓你可以實現安全閘道、稽核日誌和組織政策強制執行。