11. MCP(Model Context Protocol)建置與使用

MCP = AI 領域的 USB-C。一條協定,所有服務(Slack、Notion、GitHub、您家資料庫…)都能用同一規格給 Claude 用。 Anthropic 於 2024/11 推出,已成為產業標準。


11.1 MCP 是什麼

核心:標準化 AI 與外部系統的橋樑。

項目角色
工具(Tools)Claude 自帶能力(Read、Write、Bash)
MCP統一規格,讓任何服務都能接 Claude
內建外掛一次性整合(早期作法,已被 MCP 取代)

比喻

  • 沒 MCP:每個服務(Slack、Notion…)都要寫專屬整合 → 重複造輪
  • 有 MCP:服務方做一次 MCP server → 所有 AI 都能用

11.2 三層架構

┌────────────────────────────────────┐
│  Host(Claude / Cowork / Code)   │ ← AI 主程式
└────────────────┬───────────────────┘
                 │ JSON-RPC 2.0
                 │
       ┌─────────▼─────────┐
       │  Client(內建)    │ ← Claude 端 MCP 客戶端
       └─────────┬─────────┘
                 │ stdio / HTTP / SSE
                 │
       ┌─────────▼─────────┐
       │  Server           │ ← 應用方實作(Slack、Linear、自寫)
       │  • 註冊 Tools     │
       │  • 提供 Resources │
       │  • 暴露 Prompts   │
       └─────────┬─────────┘
                 │
       ┌─────────▼─────────┐
       │  後端服務          │
       │  Slack / DB / API │
       └───────────────────┘

流程

  1. Claude 啟動 MCP Server
  2. Server 註冊它能做什麼(Tools / Resources / Prompts)
  3. Claude 看到使用者需求,決定呼叫哪個 Tool
  4. Server 執行 → 回傳結果
  5. Claude 整合結果,繼續推理

11.3 官方常用 MCP Servers

服務用途認證
Slack訊息、頻道、查對話OAuth
GitHubIssue、PR、倉庫Token
LinearIssue 管理API Key
Notion頁面、資料庫OAuth
Google Calendar行程查詢 / 建立OAuth
Google Drive檔案讀寫OAuth
PostgresSQL 查詢 / CRUDTCP
Git提交記錄、diff本地
Puppeteer網頁自動化本地
Asana / Jira / Gmail各家服務各家認證

完整清單:https://github.com/modelcontextprotocol/servers


11.4 Cowork 中加 MCP(OAuth 流程)

  1. Cowork 設定 → 左側「MCP Servers
  2. + Add Server」→ 搜尋(如 Slack)
  3. 點選 → 自動跳出 OAuth 授權頁
  4. 用您的 Slack 帳號登入 → 核准權限
  5. 授權後 token 存在本地加密區(不上 Anthropic 雲端)
  6. 開始用:「查我 Slack 上週訊息」

您現在的 Cowork 已連了 Notion、Linear、Hex 等多個 MCP server——任何時候問「列出我可用的 MCP 工具」就能看到。


11.5 Claude Code 中加 MCP

設定檔位置:

  • macOS:~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows:%APPDATA%\Claude\claude_desktop_config.json

範例:

{
  "mcpServers": {
    "slack": {
      "type": "stdio",
      "command": "node",
      "args": ["/path/to/slack-mcp-server/build/index.js"],
      "env": {
        "SLACK_BOT_TOKEN": "xoxb-xxxx"
      }
    },
    "postgres-pam": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "Server=localhost;Database=PAM;..."
      }
    },
    "github-remote": {
      "type": "http",
      "url": "http://localhost:3000/mcp"
    }
  }
}

⚠️ 編輯後務必完全關閉 Claude Code 再重啟,否則新 server 不會載入。


11.6 手把手寫一個 MCP Server

範例:PAM 員工查詢 MCP

讓 Claude 能直接查您 PAM 系統的員工資訊。

檔案結構

pam-employee-mcp/
├── package.json
├── tsconfig.json
└── src/
    └── server.ts

package.json

{
  "name": "pam-employee-mcp",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "build": "tsc",
    "start": "node build/server.js"
  },
  "dependencies": {
    "@modelcontextprotocol/sdk": "^0.5.0",
    "mssql": "^10.0.0"
  },
  "devDependencies": {
    "typescript": "^5.0.0",
    "@types/node": "^20.0.0"
  }
}

src/server.ts

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import sql from "mssql";
 
const dbConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PASS,
  server: "localhost",
  database: "PAM",
  options: { trustServerCertificate: true }
};
 
const server = new Server({
  name: "pam-employee-mcp",
  version: "1.0.0"
});
 
// 1️⃣ 註冊 Tools
server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    {
      name: "query_employee",
      description: "依員工編號查 PAM 員工資訊",
      inputSchema: {
        type: "object",
        properties: {
          employee_no: { type: "string", description: "員工編號" }
        },
        required: ["employee_no"]
      }
    },
    {
      name: "list_by_department",
      description: "列出指定部門所有員工",
      inputSchema: {
        type: "object",
        properties: {
          department: { type: "string" }
        },
        required: ["department"]
      }
    }
  ]
}));
 
// 2️⃣ 實作 Tools
server.setRequestHandler(CallToolRequestSchema, async (req) => {
  const { name, arguments: args } = req.params;
  await sql.connect(dbConfig);
 
  if (name === "query_employee") {
    const r = await sql.query`
      SELECT Id, EmployeeNo, Name, Department, JobLevel, HireDate
      FROM Employees WHERE EmployeeNo = ${args.employee_no}
    `;
    return {
      content: [{ type: "text", text: JSON.stringify(r.recordset, null, 2) }]
    };
  }
 
  if (name === "list_by_department") {
    const r = await sql.query`
      SELECT EmployeeNo, Name, JobLevel
      FROM Employees WHERE Department = ${args.department}
    `;
    return {
      content: [{ type: "text", text: JSON.stringify(r.recordset, null, 2) }]
    };
  }
 
  return { content: [{ type: "text", text: "未知 tool" }], isError: true };
});
 
// 3️⃣ 啟動
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("PAM Employee MCP Server 已啟動");

啟動 + 註冊到 Claude

npm install
npm run build
# 把路徑加進 claude_desktop_config.json:
{
  "mcpServers": {
    "pam-employee": {
      "type": "stdio",
      "command": "node",
      "args": ["/path/to/pam-employee-mcp/build/server.js"],
      "env": {
        "DB_USER": "sa",
        "DB_PASS": "xxx"
      }
    }
  }
}

測試

> 查 E001 員工的考核相關資訊
→ Claude 自動呼叫 query_employee("E001") → 回傳資料

11.7 MCP 的 3 個原語(Primitives)

原語定位
Tools可執行的動作query_employee(id), send_slack(text)
Resources唯讀的靜態資源員工手冊 PDF、組織圖、API 文件
Prompts預設提示模板「年度考核評語範例」

何時用哪個

  • 想 Claude 去做:Tool
  • 想 Claude 去讀:Resource
  • 想提供範本:Prompt

11.8 OAuth 認證流程(深入)

1. 用戶在 Cowork 點「連接 Slack」
2. Claude 開瀏覽器 → Slack OAuth URL
3. 用戶登入 + 選工作區
4. Slack 顯示「允許 Claude 讀訊息?」
5. 用戶點「授權」
6. Slack 回傳 access_token 給 Cowork
7. Token 存於本地加密倉(macOS Keychain / Windows Credential Manager)
8. MCP Server 用 token 呼叫 Slack API

安全

  • Token 永遠不上傳 Anthropic 雲端
  • Refresh Token 自動更新
  • 用戶可隨時「移除授權」清空 token

11.9 stdio vs HTTP

項目stdio(本地)HTTP(遠端)
啟動Claude 跑本機程式Server 自跑,Claude 連
速度快(IPC)略慢(網路)
部署本地裝依賴部署到雲端
安全完全隔離需 TLS / 白名單
適用個人 DB、本地工具多人共享、SaaS

11.10 發佈到 MCP Registry

  1. GitHub 建倉庫 mcp-{name}
  2. README + 完整範例
  3. 發佈 NPM(TS)/ PyPI(Python)
  4. 提 PR 至 modelcontextprotocol/servers
  5. 審核通過 → 自動上 Registry

11.11 Debug 技巧

MCP Inspector

npm install -g @modelcontextprotocol/inspector
mcp-inspector node /path/to/server.js

→ 開瀏覽器 http://localhost:5173,即時測試 Tools、看日誌。

看 Claude Code MCP 日誌

# macOS
tail -f ~/Library/Logs/Claude/mcp.log
 
# Windows
Get-Content "$env:APPDATA\Claude\logs\mcp.log" -Tail 50 -Wait

驗證 JSON 設定

cat ~/Library/Application\ Support/Claude/claude_desktop_config.json | jq .

11.12 PAM 場景的 MCP 想像(3 個 idea)

Idea 1:PAM 員工查詢(上面範例)

讓 Claude 直接查 PAM DB,不用您手動撈。

Idea 2:PAM 考核狀態 MCP

Tools:
- get_period_progress(periodId)        // 整體進度
- list_pending_reviews(reviewerId)     // 主管待辦
- get_grade_ceiling(employeeId)        // 等第天花板

用途:HR 問「業務部進度幾趴?」→ Claude 即時查。

Idea 3:PAM 報表產出 MCP

Tools:
- generate_exam_report(periodId, format: "xlsx" | "pdf")
- export_grade_stats(filters)
- create_settlement_pdf(deptId)

用途:「產 4 月份結案報表」→ Claude 呼叫後端 API → 直接生檔給您。


11.13 排錯 FAQ

Q
MCP server 灰色無法連npm install、看 claude logs
OAuth 授權後仍 401移除授權重連,檢查 scope
Tool 呼叫超時看 server 端日誌,stdio → HTTP
編 JSON 後沒反應完全關 Claude Code 等 3 秒再開
tool not found檢查 server 進程 ps aux | grep node

11.14 官方資源


下一章 → 12-Agent 建置與使用 上一章 ← 10-Skill 建置與使用 回到 Claude 學習指南目錄