STEP 11 / 12 · 生產實戰

MCP:AI 應用的「USB-C」

Model Context Protocol——2024 由 Anthropic 發布、2025 進入 Linux Foundation 的開放標準,把工具與資料連接 LLM 的方式統一了。

Model Context Protocol — an open standard released by Anthropic in 2024, hosted by the Linux Foundation since 2025. It standardizes how LLMs connect to tools and data.

一、為什麼需要 MCP?

2024 年中之前,每個 agent 框架、每個 IDE 整合、每個 LLM 廠商都有自己的「工具」格式:

  • OpenAI function calling 用 JSON schema 一種寫法
  • Anthropic tool use 又一種
  • LangChain Tool 又一種
  • Cursor、Windsurf、Claude Desktop 也各自設計外掛機制

一個工具開發者要支援所有平台,得寫四套相同的東西。這就是 M×N 整合地獄。

2024 年 11 月,Anthropic 受到 LSP (Language Server Protocol) 啟發,發布 Model Context Protocol (MCP)——一個基於 JSON-RPC 2.0 的開放標準,讓任何 LLM 應用都能用同一套協定連接任何工具/資料源。

2025 年 4 月 OpenAI 採用,下載量從 200 萬/月跳到 2200 萬。2025 年 12 月 Anthropic 把 MCP 捐給 Agentic AI Foundation(Linux Foundation 下,由 Anthropic / Block / OpenAI 共同創立)。MCP 已成為事實上的業界標準。

Before mid-2024, every agent framework, IDE integration, and LLM vendor had its own "tool" format:

  • OpenAI function calling JSON schema
  • Anthropic tool use schema
  • LangChain Tool format
  • Cursor, Windsurf, Claude Desktop each had bespoke plugin mechanisms

A tool author had to write the same thing four times — M×N integration hell.

In November 2024, inspired by the LSP (Language Server Protocol), Anthropic published Model Context Protocol (MCP) — a JSON-RPC 2.0 open standard letting any LLM application connect to any tool/data source via one protocol.

OpenAI adopted MCP in April 2025; downloads jumped from 2M/month to 22M. In December 2025 Anthropic donated MCP to the Agentic AI Foundation (Linux Foundation, co-founded by Anthropic / Block / OpenAI). MCP is the de facto industry standard.

🔌
類比:MCP 之於 AI Agents,就像 USB-C 之於電子產品——一個接頭通用所有設備。也像 LSP 之於 IDE——一個協定支援所有編輯器。 Analogy: MCP : AI agents :: USB-C : consumer electronics — one connector for everything. Or LSP : IDEs — one protocol all editors can speak.

二、MCP 的客戶端 / 伺服器架構

┌──────────────────┐ ┌──────────────────┐ │ MCP Client (Host)│ ◄── JSON-RPC 2.0 ───► │ MCP Server │ │ │ (stdio or HTTP+SSE) │ │ │ Claude Desktop │ │ filesystem │ │ Cursor IDE │ │ github │ │ Custom agent │ │ postgres │ │ Cowork mode │ │ slack │ └──────────────────┘ │ ... thousands │ └──────────────────┘ Capabilities exposed by server: • tools (callable functions) • resources (files / DB rows) • prompts (parameterized templates)

關鍵概念:

  • Host:使用者面對的 LLM 應用(Claude Desktop、Cursor、Cowork、你自己的 agent)。
  • Server:暴露能力給 host 的後端。每個 server 通常包一個系統或服務(如 GitHub、Postgres、Slack)。
  • Transport:兩種——本地 stdio(子程序)或遠端 HTTP+SSE。2026 草案有 stateless HTTP 變體可水平擴展。
  • 三大原語
    • Tools:可被 LLM 呼叫的函式(最常用)
    • Resources:可被讀取的資料(檔案、DB 列、API 回應)
    • Prompts:可被使用者選用的參數化模板

Key concepts:

  • Host: the user-facing LLM app (Claude Desktop, Cursor, Cowork, your own agent).
  • Server: the backend exposing capabilities to the host. Each server usually wraps one system or service (GitHub, Postgres, Slack).
  • Transport: two — local stdio (subprocess) or remote HTTP+SSE. A 2026 draft adds stateless HTTP for horizontal scaling.
  • Three primitives:
    • Tools: functions the LLM can call (most common)
    • Resources: readable data (files, DB rows, API responses)
    • Prompts: parameterized templates users can pick

三、寫一個最小 MCP Server

下方用 Anthropic 官方 SDK 寫一個「天氣查詢」MCP server。完成後它可被 Claude Desktop、Cursor、Cowork 等所有 host 立刻使用。

Below: a "weather lookup" MCP server using Anthropic's official SDK. Once running, it's instantly usable from Claude Desktop, Cursor, Cowork, and any MCP host.

# pip install mcp httpx
from mcp.server.fastmcp import FastMCP
import httpx

app = FastMCP("weather")

@app.tool()
async def get_weather(city: str) -> str:
    """Get current weather for a city. Returns a one-line summary."""
    async with httpx.AsyncClient() as c:
        r = await c.get(f"https://wttr.in/{city}?format=3")
        return r.text.strip()

@app.resource("weather://history/{city}")
async def history(city: str) -> str:
    """Return last 7-day weather log for a city."""
    return load_history(city)

@app.prompt()
def trip_planner(destination: str, days: int) -> str:
    """Build a packing checklist using current weather."""
    return f"Plan a {days}-day trip to {destination}. Check the weather first via get_weather."

if __name__ == "__main__":
    app.run(transport="stdio")   # local; use "sse" for remote
// npm install @modelcontextprotocol/sdk
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:"weather", version:"1.0.0" });

server.tool("get_weather",
  { city: z.string().describe("City name") },
  async ({ city }) => {
    const r = await fetch(`https://wttr.in/${city}?format=3`);
    return { content:[{ type:"text", text:await r.text() }] };
  }
);

await server.connect(new StdioServerTransport());
把這個 server 加到 Claude Desktop:編輯 ~/Library/Application Support/Claude/claude_desktop_config.json,加入:
{"mcpServers":{"weather":{"command":"python","args":["/path/to/server.py"]}}}
重啟 Claude Desktop,使用者立刻能說「東京現在天氣?」由 LLM 自動呼叫工具。
Wire this to Claude Desktop: edit ~/Library/Application Support/Claude/claude_desktop_config.json:
{"mcpServers":{"weather":{"command":"python","args":["/path/to/server.py"]}}}
Restart Claude Desktop — users can now ask "what's the weather in Tokyo?" and the LLM auto-invokes the tool.

四、在自己的 Agent 中當 MCP Client

反過來,如果你自己寫 agent,也可以用 MCP client SDK 連接別人寫好的 MCP server(GitHub、Slack、Postgres 都有官方 server):

Conversely, your own agent can act as an MCP client and connect to existing MCP servers (GitHub, Slack, Postgres all ship official servers):

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
import anthropic

# 1) Launch GitHub MCP server as subprocess
params = StdioServerParameters(command="npx", args=["-y","@modelcontextprotocol/server-github"],
                                env={"GITHUB_TOKEN": os.environ["GH_TOKEN"]})

async with stdio_client(params) as (read, write):
    async with ClientSession(read, write) as session:
        await session.initialize()
        tools = await session.list_tools()

        # 2) Convert MCP tools to Anthropic tool schema
        ant_tools = [{"name":t.name, "description":t.description,
                      "input_schema":t.inputSchema} for t in tools.tools]

        # 3) Run agent loop, route tool calls back to MCP server
        client = anthropic.Anthropic()
        messages = [{"role":"user","content":"List open issues in my repo modelcontextprotocol/python-sdk"}]
        while True:
            r = client.messages.create(model="claude-sonnet-4-6", max_tokens=1024,
                                       tools=ant_tools, messages=messages)
            if r.stop_reason == "end_turn": break
            messages.append({"role":"assistant","content": r.content})
            results = []
            for b in r.content:
                if b.type == "tool_use":
                    out = await session.call_tool(b.name, b.input)
                    results.append({"type":"tool_result","tool_use_id":b.id,
                                    "content": str(out.content)})
            messages.append({"role":"user","content": results})

五、2026 MCP 生態圖譜

📦 官方 Servers

GitHub、Slack、Postgres、Filesystem、Brave Search、Puppeteer、Google Drive……Anthropic 與社群維護的 reference 實作。

GitHub, Slack, Postgres, Filesystem, Brave Search, Puppeteer, Google Drive… reference implementations from Anthropic and the community.

🌐 第三方 Registry

2026 年湧現的「MCP 應用商店」:mcp.so、Smithery、PulseMCP……搜尋、評分、安裝皆有 GUI。

"MCP app stores" rose in 2026: mcp.so, Smithery, PulseMCP… searchable with reviews and one-click install.

🧑‍💼 企業內部

各公司把自家 API(CRM、ERP、內部 DB)包裝成 MCP server,員工的 Cursor / Cowork 直接連,免去十幾種整合。

Companies wrap internal APIs (CRM, ERP, DBs) as MCP servers — employee's Cursor / Cowork connects directly, replacing a dozen integrations.

🛠️ Cowork / Claude Desktop

使用者端的 MCP host:直接點 GUI 連線到任意 server,看到的「工具」就是 server 暴露的 tools。

User-facing MCP hosts: connect to any server via GUI; the "tools" you see are the server's exposed tools.

🔐 安全層

2026 出現的 MCP gateway / proxy(如 Microsoft Agent Governance Toolkit):集中審計、權限、注入過濾。

MCP gateways / proxies (e.g., Microsoft Agent Governance Toolkit) emerged 2026: centralized audit, permissions, injection filtering.

🚀 2026 Roadmap

無狀態 HTTP transport(水平擴展用)、Tasks 原語(長跑非同步任務)、官方註冊表治理(Linux Foundation)。

Stateless HTTP transport (horizontal scaling), Tasks primitive (long-running async), official registry governance (Linux Foundation).

六、MCP 的安全責任邊界

MCP 是協定,本身不保證安全。它把「LLM ↔ 工具」的接口統一了,但沒有解決:

  • 使用者裝了惡意 MCP server → 等於開後門
  • MCP 工具被 prompt injection 觸發 → 可能執行未授權動作
  • 遠端 MCP server 認證 / OAuth → 你必須自己加
  • 多 MCP server 間的權限隔離 → host 端負責

2026 業界的解法:

  1. 官方註冊表 + 簽章:類似 npm + Sigstore,可驗證 server 來源
  2. 權限粒度設定:host 提供 GUI 讓使用者勾選「這個 server 可以做什麼」
  3. 沙箱執行:每個 server 在獨立 process / container 中
  4. 注入過濾:MCP gateway 攔下高風險工具回應再給 LLM

詳細安全討論見 Step 12

MCP is a protocol; it does not guarantee security on its own. It unifies the "LLM ↔ tools" interface but does not solve:

  • User installs a malicious MCP server → effectively opens a backdoor
  • MCP tools triggered by prompt injection → may execute unauthorized actions
  • Remote MCP server auth / OAuth → you must add it
  • Permission isolation between multiple MCP servers → host's responsibility

2026 industry mitigations:

  1. Official registry + signing (npm + Sigstore-style) for source verification
  2. Granular permissions: host provides a GUI to opt-in per capability
  3. Sandbox execution: each server in its own process / container
  4. Injection filtering: MCP gateway sanitizes risky tool responses before forwarding to LLM

Full security discussion in Step 12.

🎓 章節小測

Q1. MCP 主要解決什麼問題?

Q1. What problem does MCP primarily solve?

A) 提升 LLM 推理品質
B) 標準化 LLM 應用與工具的整合介面
C) 取代 RAG
D) 訓練更快
✅ MCP 是接口協定,類似 LSP 之於 IDE。✅ MCP is an interface protocol — LSP-for-agents.

Q2. MCP 的三大原語是?

Q2. The three MCP primitives?

A) Server / Client / Host
B) Tools / Resources / Prompts
C) Plan / Act / Observe
D) JSON / RPC / 2.0
✅ Tools 是可呼叫函式、Resources 是可讀資料、Prompts 是參數化模板。✅ Tools are callable, resources are readable data, prompts are templates.

Q3. 下列哪一項對 MCP 的描述不正確

Q3. Which statement about MCP is incorrect?

A) 由 Anthropic 2024 年發布
B) 基於 JSON-RPC 2.0
C) OpenAI 已採用
D) 內建解決所有安全問題
✅ MCP 是協定,不是安全方案;認證、權限、沙箱要自己加。✅ MCP is a protocol, not a security solution — auth, permissions, sandbox are your job.