Model Context Protocol (MCP) 技術深度解析:AI 應用的通用連接標準


0. 為什麼需要 MCP?

在 AI 應用開發中,一個核心挑戰是:如何讓 LLM 與外部世界互動?

傳統做法是每個應用自己實現一套整合方案——連接資料庫、調用 API、讀取文件。這導致了 N×M 問題:N 個 AI 應用 × M 個數據源 = N×M 個客製化整合。

Model Context Protocol (MCP) 正是為解決這個問題而生。它是由 Anthropic 於 2024 年 11 月推出的開放標準,目標是成為 AI 應用的「USB-C 接口」——一個統一的連接標準。

┌─────────────────────────────────────────────────────────────┐
│                     傳統整合方式 (N×M)                        │
├─────────────────────────────────────────────────────────────┤
│  Claude ─┬── 自定義 ── Database                              │
│          ├── 自定義 ── GitHub                                │
│          └── 自定義 ── Slack                                 │
│  ChatGPT ─┬── 自定義 ── Database                             │
│           ├── 自定義 ── GitHub                               │
│           └── 自定義 ── Slack                                │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│                     MCP 統一標準 (N+M)                        │
├─────────────────────────────────────────────────────────────┤
│  Claude  ──┐                ┌── Database MCP Server          │
│            │                │                                │
│  ChatGPT ──┼── MCP 協議 ────┼── GitHub MCP Server            │
│            │                │                                │
│  Gemini ───┘                └── Slack MCP Server             │
└─────────────────────────────────────────────────────────────┘

2025 年 12 月,Anthropic 將 MCP 捐贈給 Agentic AI Foundation (AAIF)——由 Linux Foundation 管理的專項基金,共同創始成員包括 Anthropic、Block 和 OpenAI,並獲得 Google、Microsoft、AWS、Cloudflare 和 Bloomberg 的支持。


1. 核心架構

1.1 三層參與者模型

MCP 採用經典的 Client-Server 架構,但引入了 Host 層來管理多個連接:

flowchart TD
  subgraph Host["MCP Host (AI 應用)"]
    direction TB
    App["Claude Desktop / IDE / 自定義應用"]
  end

  subgraph Clients["MCP Clients"]
    direction LR
    C1["Client 1"]
    C2["Client 2"]
    C3["Client 3"]
  end

  subgraph Servers["MCP Servers"]
    direction LR
    S1["GitHub Server"]
    S2["Database Server"]
    S3["File System Server"]
  end

  Host --> Clients
  C1 --> S1
  C2 --> S2
  C3 --> S3
組件職責範例
Host用戶交互的 AI 應用,管理多個 ClientClaude Desktop, Cursor, VS Code
Client維護與單個 Server 的 1:1 連接每個 MCP Server 對應一個 Client
Server暴露 Tools、Resources、Prompts 給 AIGitHub API 封裝、資料庫連接器

1.2 協議層級

MCP 分為兩個主要層級:

┌─────────────────────────────────────┐
│           Data Layer                │
│  ┌─────────────────────────────┐   │
│  │  Lifecycle Management       │   │
│  │  Server Features            │   │
│  │  (Tools, Resources, Prompts)│   │
│  │  Client Features            │   │
│  │  (Sampling, Elicitation)    │   │
│  │  Utility Features           │   │
│  │  (Progress, Cancellation)   │   │
│  └─────────────────────────────┘   │
├─────────────────────────────────────┤
│         Transport Layer             │
│  ┌─────────────────────────────┐   │
│  │  stdio Transport            │   │
│  │  Streamable HTTP Transport  │   │
│  │  Custom Transport           │   │
│  └─────────────────────────────┘   │
└─────────────────────────────────────┘

2. 傳輸層 (Transport Layer)

2.1 JSON-RPC 2.0 基礎

MCP 基於 JSON-RPC 2.0 協議進行消息交換。所有消息必須是 UTF-8 編碼。

三種消息類型

# 1. Request (請求)
{
    "jsonrpc": "2.0",
    "id": 1,                    # 唯一請求 ID
    "method": "tools/call",     # 方法名
    "params": {...}             # 可選參數
}

# 2. Response (響應)
{
    "jsonrpc": "2.0",
    "id": 1,                    # 對應的請求 ID
    "result": {...}             # 成功結果
}

# 2b. Error Response (錯誤響應)
{
    "jsonrpc": "2.0",
    "id": 1,
    "error": {
        "code": -32602,
        "message": "Invalid params",
        "data": {...}
    }
}

# 3. Notification (通知,無需響應)
{
    "jsonrpc": "2.0",
    "method": "notifications/tools/list_changed"
    # 注意:沒有 id 字段
}

2.2 stdio 傳輸

最常用的本地傳輸方式。Client 啟動 Server 作為子進程:

┌──────────┐                    ┌──────────┐
│  Client  │ ── stdin (JSON) ─→ │  Server  │
│          │ ←─ stdout (JSON) ─ │ (子進程)  │
└──────────┘                    └──────────┘

特點

  • 消息以換行符分隔
  • 消息內部 不可 包含換行符
  • Server 的 stderr 可用於日誌(不被 MCP 處理)
  • 適合本地整合:文件系統、本地資料庫、腳本執行

2.3 Streamable HTTP 傳輸

適合遠程 Server 的傳輸方式:

┌──────────┐                              ┌──────────┐
│  Client  │ ── HTTP POST (JSON-RPC) ───→ │  Server  │
│          │ ←─ Response / SSE Stream ─── │ (獨立)   │
└──────────┘                              └──────────┘

關鍵規則

  • 每個 JSON-RPC 消息必須是新的 HTTP POST 請求
  • Server 可選擇使用 Server-Sent Events (SSE) 流式返回多個消息
  • 支持通知和請求的串流
  • 必須在後續請求中包含協議版本 Header:
POST /mcp HTTP/1.1
Content-Type: application/json
MCP-Protocol-Version: 2025-11-25

{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}

3. 生命週期管理

3.1 初始化流程

sequenceDiagram
  participant C as Client
  participant S as Server

  C->>S: initialize (protocolVersion, capabilities, clientInfo)
  S->>C: InitializeResult (protocolVersion, capabilities, serverInfo)
  C->>S: notifications/initialized
  Note over C,S: 進入 Operation Phase

初始化請求

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "initialize",
  "params": {
    "protocolVersion": "2025-11-25",
    "capabilities": {
      "roots": { "listChanged": true },
      "sampling": { "tools": {} },
      "elicitation": {}
    },
    "clientInfo": {
      "name": "Claude Desktop",
      "version": "1.5.0"
    }
  }
}

初始化響應

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "protocolVersion": "2025-11-25",
    "capabilities": {
      "tools": { "listChanged": true },
      "resources": { "subscribe": true },
      "prompts": { "listChanged": true },
      "logging": {}
    },
    "serverInfo": {
      "name": "GitHub MCP Server",
      "version": "2.0.0"
    }
  }
}

3.2 版本協商

  • Client 發送其支持的 最新 協議版本
  • Server 響應 相同版本(如果支持)或其支持的其他版本
  • 如果版本不兼容,Client 應斷開連接

3.3 能力協商

類別能力說明
Clientroots提供文件系統根目錄
Clientsampling支持 LLM 採樣請求
Clientelicitation支持 Server 請求用戶輸入
Servertools暴露可調用的工具
Serverresources提供可讀取的資源
Serverprompts提供提示詞模板
Serverlogging發送結構化日誌

子能力

  • listChanged:支持列表變更通知
  • subscribe:支持訂閱個別資源變更(僅 resources)

3.4 關閉流程

stdio 傳輸

  1. Client 關閉 Server 的 stdin
  2. 等待 Server 退出
  3. 超時後發送 SIGTERM
  4. 必要時發送 SIGKILL

HTTP 傳輸

  • 關閉相關 HTTP 連接即可

4. Server 原語:Tools

Tools 是 Server 暴露給 AI 模型的可執行函數,由模型控制調用。

4.1 工具定義

{
  "name": "get_weather",
  "title": "Weather Information Provider",
  "description": "Get current weather information for a location",
  "inputSchema": {
    "type": "object",
    "properties": {
      "location": {
        "type": "string",
        "description": "City name or zip code"
      },
      "units": {
        "type": "string",
        "enum": ["metric", "imperial"],
        "default": "metric"
      }
    },
    "required": ["location"]
  },
  "outputSchema": {
    "type": "object",
    "properties": {
      "temperature": { "type": "number" },
      "conditions": { "type": "string" },
      "humidity": { "type": "number" }
    },
    "required": ["temperature", "conditions"]
  },
  "annotations": {
    "audience": ["assistant"],
    "priority": 0.8
  }
}

欄位說明

欄位必填說明
name唯一標識符 (1-128 字符,字母數字、下劃線、連字符、點)
title人類可讀的顯示名稱
description功能描述,幫助 LLM 理解何時使用
inputSchemaJSON Schema 定義輸入參數
outputSchemaJSON Schema 定義結構化輸出
annotations元數據(audience、priority)

4.2 列出工具

// Request
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/list",
  "params": { "cursor": "optional-pagination-cursor" }
}

// Response
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "tools": [ /* tool definitions */ ],
    "nextCursor": "next-page-cursor"
  }
}

4.3 調用工具

// Request
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "get_weather",
    "arguments": {
      "location": "Tokyo",
      "units": "metric"
    }
  }
}

// Response
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Tokyo: 22°C, Partly Cloudy, Humidity 65%"
      }
    ],
    "structuredContent": {
      "temperature": 22,
      "conditions": "Partly Cloudy",
      "humidity": 65
    },
    "isError": false
  }
}

4.4 內容類型

工具結果支持多種內容類型:

# 文本內容
{
    "type": "text",
    "text": "Result text"
}

# 圖片內容
{
    "type": "image",
    "data": "base64-encoded-data",
    "mimeType": "image/png"
}

# 音頻內容
{
    "type": "audio",
    "data": "base64-encoded-audio",
    "mimeType": "audio/wav"
}

# 資源鏈接
{
    "type": "resource_link",
    "uri": "file:///project/output.json",
    "name": "output.json",
    "mimeType": "application/json"
}

# 嵌入資源
{
    "type": "resource",
    "resource": {
        "uri": "file:///data.csv",
        "mimeType": "text/csv",
        "text": "col1,col2\n1,2"
    }
}

4.5 錯誤處理

協議錯誤(結構性問題):

{
  "jsonrpc": "2.0",
  "id": 3,
  "error": {
    "code": -32602,
    "message": "Unknown tool: invalid_tool"
  }
}

執行錯誤(可恢復,應提供給 LLM):

{
  "jsonrpc": "2.0",
  "id": 4,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Error: Location 'XYZ' not found. Please provide a valid city name."
      }
    ],
    "isError": true
  }
}

5. Server 原語:Resources

Resources 是 Server 提供的數據源,由應用程式控制訪問,類似 REST API 的 GET 端點。

5.1 資源定義

{
  "uri": "file:///project/src/main.py",
  "name": "main.py",
  "title": "Main Application Entry",
  "description": "Primary Python application file",
  "mimeType": "text/x-python",
  "size": 2048,
  "annotations": {
    "audience": ["user", "assistant"],
    "priority": 0.9,
    "lastModified": "2025-12-23T10:30:00Z"
  }
}

5.2 列出資源

// Request
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "resources/list",
  "params": { "cursor": "optional-cursor" }
}

// Response
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "resources": [
      {
        "uri": "file:///project/README.md",
        "name": "README.md",
        "mimeType": "text/markdown"
      },
      {
        "uri": "postgres://db/users",
        "name": "Users Table",
        "mimeType": "application/json"
      }
    ],
    "nextCursor": "..."
  }
}

5.3 讀取資源

// Request
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "resources/read",
  "params": {
    "uri": "file:///project/config.json"
  }
}

// Response (文本內容)
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "contents": [
      {
        "uri": "file:///project/config.json",
        "mimeType": "application/json",
        "text": "{\"debug\": true, \"port\": 8080}"
      }
    ]
  }
}

// Response (二進制內容)
{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "contents": [
      {
        "uri": "file:///project/logo.png",
        "mimeType": "image/png",
        "blob": "iVBORw0KGgoAAAANSUhEUgAA..."
      }
    ]
  }
}

5.4 資源模板

使用 URI Templates (RFC 6570) 暴露參數化資源:

// Request
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "resources/templates/list"
}

// Response
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "resourceTemplates": [
      {
        "uriTemplate": "github://repos/{owner}/{repo}/issues/{issue_id}",
        "name": "GitHub Issue",
        "description": "Access specific GitHub issues",
        "mimeType": "application/json"
      },
      {
        "uriTemplate": "postgres://db/{table}?limit={limit}",
        "name": "Database Table",
        "description": "Query database tables with optional limit"
      }
    ]
  }
}

5.5 訂閱機制

Client 可訂閱特定資源的變更通知:

// Subscribe Request
{
  "jsonrpc": "2.0",
  "id": 4,
  "method": "resources/subscribe",
  "params": { "uri": "file:///project/config.json" }
}

// Update Notification (Server → Client)
{
  "jsonrpc": "2.0",
  "method": "notifications/resources/updated",
  "params": { "uri": "file:///project/config.json" }
}

// List Changed Notification
{
  "jsonrpc": "2.0",
  "method": "notifications/resources/list_changed"
}

5.6 常用 URI Schemes

Scheme用途範例
file://文件系統資源file:///home/user/doc.txt
https://Web 資源(可直接獲取)https://api.example.com/data
git://Git 版本控制git://repo/main/file.py
postgres://資料庫資源postgres://db/users?id=1
自定義應用特定資源notion://page/abc123

6. Server 原語:Prompts

Prompts 是 Server 提供的可重用消息模板,由用戶選擇使用(如 slash commands)。

6.1 提示詞定義

{
  "name": "code_review",
  "title": "Code Review Assistant",
  "description": "Analyzes code quality and suggests improvements",
  "arguments": [
    {
      "name": "code",
      "description": "The code to review",
      "required": true
    },
    {
      "name": "language",
      "description": "Programming language",
      "required": false
    }
  ]
}

6.2 列出提示詞

// Request
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "prompts/list"
}

// Response
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "prompts": [
      {
        "name": "explain_code",
        "title": "Explain Code",
        "description": "Explains what a piece of code does"
      },
      {
        "name": "refactor_code",
        "title": "Refactor Code",
        "arguments": [
          { "name": "code", "required": true },
          { "name": "style", "required": false }
        ]
      }
    ]
  }
}

6.3 獲取提示詞

// Request
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "prompts/get",
  "params": {
    "name": "code_review",
    "arguments": {
      "code": "def hello():\n    print('world')",
      "language": "python"
    }
  }
}

// Response
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "description": "Code review for Python code",
    "messages": [
      {
        "role": "user",
        "content": {
          "type": "text",
          "text": "Please review this Python code for quality, best practices, and potential improvements:\n\ndef hello():\n    print('world')"
        }
      }
    ]
  }
}

6.4 消息內容類型

Prompts 的消息支持:

  • text:純文本
  • image:Base64 編碼圖片
  • audio:Base64 編碼音頻
  • resource:嵌入資源內容

7. Client 功能:Sampling

Sampling 允許 Server 請求 Client 執行 LLM 推理,實現 Server 端的 Agentic 行為。

7.1 基本採樣請求

// Request (Server → Client)
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "sampling/createMessage",
  "params": {
    "messages": [
      {
        "role": "user",
        "content": {
          "type": "text",
          "text": "Summarize this document in 3 bullet points."
        }
      }
    ],
    "systemPrompt": "You are a concise summarizer.",
    "maxTokens": 200,
    "modelPreferences": {
      "hints": [{ "name": "claude-3-sonnet" }],
      "intelligencePriority": 0.8,
      "speedPriority": 0.5
    }
  }
}

// Response (Client → Server)
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "role": "assistant",
    "content": {
      "type": "text",
      "text": "• Key point 1\n• Key point 2\n• Key point 3"
    },
    "model": "claude-3-sonnet-20240307",
    "stopReason": "endTurn"
  }
}

7.2 帶工具的採樣

Server 可在採樣請求中包含工具定義:

{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "sampling/createMessage",
  "params": {
    "messages": [
      {
        "role": "user",
        "content": {
          "type": "text",
          "text": "What's the weather in Paris and London?"
        }
      }
    ],
    "tools": [
      {
        "name": "get_weather",
        "description": "Get current weather for a city",
        "inputSchema": {
          "type": "object",
          "properties": {
            "city": { "type": "string" }
          },
          "required": ["city"]
        }
      }
    ],
    "toolChoice": { "mode": "auto" },
    "maxTokens": 500
  }
}

工具選擇模式

  • auto:模型自行決定是否使用工具
  • required:必須使用至少一個工具
  • none:禁止使用工具

7.3 模型偏好

{
  "modelPreferences": {
    "hints": [
      { "name": "claude-3-opus" },
      { "name": "claude-3" },
      { "name": "claude" }
    ],
    "costPriority": 0.3,        // 0-1,越高越便宜
    "speedPriority": 0.8,       // 0-1,越高越快
    "intelligencePriority": 0.5  // 0-1,越高越智能
  }
}

重要:Sampling 應始終有 人類在環 (Human-in-the-loop),用戶可以審核和拒絕請求。


8. Client 功能:Elicitation (2025 新增)

Elicitation 允許 Server 請求用戶提供額外信息,支持交互式工作流。

8.1 基本請求

// Request (Server → Client)
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "elicitation/request",
  "params": {
    "message": "Please enter your API key to continue:",
    "requestedSchema": {
      "type": "object",
      "properties": {
        "apiKey": {
          "type": "string",
          "description": "Your API key"
        }
      },
      "required": ["apiKey"]
    }
  }
}

// Response (Client → Server)
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "action": "accept",
    "content": {
      "apiKey": "sk-abc123..."
    }
  }
}

8.2 URL 模式

2025-11-25 新增的 URL Mode 支持安全的帶外交互:

{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "elicitation/request",
  "params": {
    "mode": "url",
    "url": "https://auth.example.com/oauth/authorize?client_id=...",
    "message": "Please complete authentication in your browser"
  }
}

用途

  • OAuth 認證流程
  • 支付處理(PCI 合規)
  • 敏感憑證收集(不經過 MCP Client)

9. 實用功能

9.1 進度追蹤

// 發送進度通知
{
  "jsonrpc": "2.0",
  "method": "notifications/progress",
  "params": {
    "progressToken": "task-123",
    "progress": 45,
    "total": 100,
    "message": "Processing file 45 of 100..."
  }
}

9.2 取消請求

// 發送取消通知
{
  "jsonrpc": "2.0",
  "method": "notifications/cancelled",
  "params": {
    "requestId": 5,
    "reason": "User cancelled the operation"
  }
}

9.3 日誌

// Server 發送日誌
{
  "jsonrpc": "2.0",
  "method": "notifications/message",
  "params": {
    "level": "info",
    "logger": "github-server",
    "data": {
      "message": "Successfully fetched 50 issues",
      "duration_ms": 234
    }
  }
}

日誌級別:debug < info < notice < warning < error < critical < alert < emergency

9.4 Tasks (2025 新增)

Tasks 提供長時間運行操作的追蹤機制

// 創建任務
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tasks/create",
  "params": {
    "name": "data_analysis",
    "description": "Analyzing healthcare data"
  }
}

// 任務狀態更新
{
  "jsonrpc": "2.0",
  "method": "notifications/tasks/status",
  "params": {
    "taskId": "task-abc",
    "status": "working",        // working | input_required | completed | failed | cancelled
    "progress": 75,
    "message": "Generating report..."
  }
}

// 查詢任務狀態
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tasks/get",
  "params": { "taskId": "task-abc" }
}

10. 2025-11-25 版本新特性

10.1 主要更新

特性說明
Tasks長時間操作的追蹤抽象
URL Mode Elicitation安全的帶外用戶交互
Sampling with ToolsServer 端 Agentic 循環
Simplified Authorization基於 URL 的 Client 註冊
Extensions Framework可選、組合式協議擴展

10.2 擴展框架

新的 Extensions 機制允許可選的協議擴展:

{
  "capabilities": {
    "experimental": {
      "customExtension": {
        "version": "1.0.0"
      }
    }
  }
}

11. 安全考量

11.1 核心原則

┌─────────────────────────────────────────────┐
│              安全設計原則                    │
├─────────────────────────────────────────────┤
│  1. User Consent    用戶同意所有數據訪問     │
│  2. Data Privacy    保護用戶數據             │
│  3. Tool Safety     工具描述視為不可信       │
│  4. LLM Controls    用戶控制採樣請求         │
│  5. Human-in-Loop   敏感操作需人工確認       │
└─────────────────────────────────────────────┘

11.2 Server 安全職責

  • ✓ 驗證所有工具輸入
  • ✓ 實施訪問控制
  • ✓ 限制工具調用速率
  • ✓ 清理輸出數據

11.3 Client 安全職責

  • ✓ 敏感操作前提示用戶確認
  • ✓ 調用工具前顯示輸入
  • ✓ 驗證結果後再傳給 LLM
  • ✓ 實施調用超時
  • ✓ 記錄工具使用日誌

11.4 已知安全問題

2025 年 4 月,安全研究人員發現多個問題:

  • Prompt Injection:惡意輸入可能操縱 LLM
  • 工具權限:組合工具可能導致文件洩露
  • 仿冒工具:惡意工具可能冒充可信工具

緩解措施:僅使用受信任的 MCP Servers,審核工具描述,實施權限隔離。


12. 實現示例

12.1 Python Server 示例

from mcp import Server, Tool, Resource
from mcp.transport import StdioTransport

# 創建 Server
server = Server(
    name="example-server",
    version="1.0.0"
)

# 定義工具
@server.tool(
    name="calculate",
    description="Perform mathematical calculations",
    input_schema={
        "type": "object",
        "properties": {
            "expression": {"type": "string"}
        },
        "required": ["expression"]
    }
)
async def calculate(expression: str) -> dict:
    try:
        result = eval(expression)  # 生產環境請使用安全解析器
        return {"content": [{"type": "text", "text": f"Result: {result}"}]}
    except Exception as e:
        return {"content": [{"type": "text", "text": f"Error: {e}"}], "isError": True}

# 定義資源
@server.resource(uri="config://settings")
async def get_settings() -> dict:
    return {
        "uri": "config://settings",
        "mimeType": "application/json",
        "text": '{"debug": true}'
    }

# 運行 Server
async def main():
    transport = StdioTransport()
    await server.run(transport)

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

12.2 TypeScript Server 示例

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

const server = new Server(
  { name: "example-server", version: "1.0.0" },
  { capabilities: { tools: { listChanged: true } } }
);

// 列出工具
server.setRequestHandler("tools/list", async () => ({
  tools: [
    {
      name: "greet",
      description: "Generate a greeting",
      inputSchema: {
        type: "object",
        properties: {
          name: { type: "string" }
        },
        required: ["name"]
      }
    }
  ]
}));

// 調用工具
server.setRequestHandler("tools/call", async (request) => {
  if (request.params.name === "greet") {
    const name = request.params.arguments?.name || "World";
    return {
      content: [{ type: "text", text: `Hello, ${name}!` }]
    };
  }
  throw new Error(`Unknown tool: ${request.params.name}`);
});

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

13. 生態系統現狀

13.1 官方 SDK

語言套件月下載量
TypeScript@modelcontextprotocol/sdk50M+
Pythonmcp47M+
Javamcp-sdk-java進行中
C#ModelContextProtocol進行中

13.2 主要採用者

  • Anthropic:Claude Desktop, Claude Code
  • OpenAI:ChatGPT Desktop, Agents SDK, Responses API
  • Google:Gemini (計劃中)
  • Microsoft:VS Code, GitHub Copilot
  • JetBrains:IDE 整合

13.3 熱門 MCP Servers

Server功能
mcp-server-githubGitHub API 整合
mcp-server-postgresPostgreSQL 資料庫
mcp-server-filesystem本地文件系統
mcp-server-slackSlack 消息
mcp-server-puppeteer瀏覽器自動化
mcp-server-stripe支付處理

14. 與其他標準比較

特性MCPOpenAI Function CallingLangChain Tools
標準化開放協議廠商專有框架專有
傳輸stdio, HTTP, 自定義HTTP API進程內
雙向通信✓ (Sampling, Elicitation)
資源抽象✓ (Resources)
狀態管理有狀態會話無狀態取決於實現
多模型支持僅 OpenAI多模型

15. 總結

MCP 的核心價值在於:

  1. 統一標準:解決 N×M 整合問題,一次實現,處處可用
  2. 雙向通信:不只是工具調用,還支持 Server 主動請求
  3. 三原語設計:Tools(執行)、Resources(數據)、Prompts(模板)清晰分離
  4. 安全優先:內建用戶同意、權限控制、審計機制
  5. 開放治理:捐贈給 Linux Foundation,多廠商共同維護

隨著 OpenAI、Google 等主要 AI 提供商的加入,MCP 正在成為 AI 應用整合的事實標準。對於構建 AI Agent 應用的開發者來說,理解 MCP 已成為必備技能。


參考資料