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

MCP 整合

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

2026年3月20日 22 分鐘閱讀

你將學到什麼

Claude Code 內建了一套強大的工具 — Read、Edit、Bash、Grep、Glob。但如果你需要查詢資料庫呢?搜尋公司 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, Bash, Grep...     │
│  Custom:   ??? (fork the codebase?)      │
└──────────────────────────────────────────┘

With MCP:
┌──────────────────────────────────────────┐
│  Claude Code                              │
│                                           │
│  Built-in: Read, Edit, Bash, Grep...     │
│  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"
}

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

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

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

傳輸機制

MCP 支援兩種傳輸類型:

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

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

伺服器作為子程序運行。通訊透過 stdin 和 stdout 管道進行,與 CLI 和 SDK 的通訊方式相同(第 13 堂課)。這種方式快速、安全,不需要網路設定。

SSE (Server-Sent Events) — 用於遠端伺服器

Claude Code ──HTTP/SSE──► Remote MCP Server
                          (running on a server)

伺服器運行在遠端機器上。通訊透過 HTTP 和 SSE 串流進行。這讓整個團隊都能使用共享的 MCP 伺服器。

設定

MCP 伺服器在 .mcp.json 檔案中設定。Claude Code 會在你的專案根目錄尋找此檔案:

{
  "mcpServers": {
    "database": {
      "command": "npx",
      "args": ["-y", "@mcp/postgres", "--connection-string", "postgresql://localhost:5432/mydb"],
      "type": "stdio"
    },
    "memory": {
      "command": "npx",
      "args": ["-y", "@mcp/memory"],
      "type": "stdio"
    },
    "company-wiki": {
      "url": "https://mcp.internal.company.com/wiki",
      "type": "sse"
    }
  }
}

每個條目定義了:

  • 名稱 — 工具的前綴方式(例如 mcp__database__query
  • command/url — 如何啟動或連接到伺服器
  • typestdio 用於本地,sse 用於遠端

工具發現

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

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

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

Result:
┌──────────────────────────────────────────────┐
│  Available Tools                              │
│                                               │
│  Built-in:                                    │
│    Read, Edit, Bash, Glob, Grep, Write,      │
│    TodoRead, TodoWrite, WebFetch...          │
│                                               │
│  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__searchmcp__jira__search

權限整合

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

AI decides to call mcp__database__query


┌─────────────────┐
│ Permission Check │
│                  │
│ Is this tool     │
│ allowed?         │
│                  │
│ - Check settings │
│ - Check hooks    │
│ - Check scope    │
└────┬────────┬────┘
     │        │
  Allowed   Blocked
     │        │
     ▼        ▼
  Execute   Ask user
  tool      for permission

你可以在設定中為 MCP 工具設定權限,就像內建工具一樣。PreToolUse hook(第 15 堂課)可以檢查 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 伺服器,提供單一工具 — 字數計數器:

// word-counter-server.js
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "word-counter",
  version: "1.0.0",
});

// Register a tool
server.tool(
  "count_words",
  "Count words in a given text",
  {
    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}`,
        },
      ],
    };
  }
);

// Start listening on stdio
const transport = new StdioServerTransport();
await server.connect(transport);

連接到 Claude Code

將伺服器加入你專案的 .mcp.json

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

現在當你在這個專案中啟動 Claude Code 時,AI 就能存取 mcp__wordcount__count_words。你可以問「這段文字有多少字?」AI 就會使用你的自訂工具。

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

// file-metadata-server.js
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import fs from "fs/promises";
import path from "path";

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

server.tool(
  "file_stats",
  "Get detailed metadata about a file (size, dates, permissions)",
  {
    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.tool(
  "directory_size",
  "Calculate total size of a directory recursively",
  {
    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) {
      const fullPath = path.join(dir_path, entry.name);
      if (entry.isFile()) {
        const stat = await fs.stat(fullPath);
        totalSize += stat.size;
      }
    }
    return {
      content: [{
        type: "text",
        text: `Total size: ${(totalSize / 1024).toFixed(1)} KB (${entries.length} entries)`,
      }],
    };
  }
);

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

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

前後對比

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

下一堂課

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