你家一定有 USB 轉接頭。Type-C 轉 HDMI、Lightning 轉 3.5mm、各種奇奇怪怪的接頭。轉接頭本身不做任何事,它只是讓兩個本來講不同語言的東西能接上。螢幕不需要知道你的筆電是什麼牌子,筆電也不需要知道螢幕的解析度怎麼設定 — 轉接頭搞定一切。

MCP(Model Context Protocol)就是 AI 世界的 USB 轉接頭。

Anthropic 開發了這個開放協定,現在已經捐給 Linux Foundation AAIF。它讓 AI model 連接外部工具和資料來源,不管是資料庫、API、檔案系統,接上就能用。目前生態系已經長到 164M 月下載量、超過 2,400 個 server,Microsoft、GitHub、Cloudflare、Stripe 都在用。Claude Code、Cursor、Kiro 這些 AI coding 工具也全部支援。

這不是什麼還在實驗階段的新玩意。這已經是事實標準了。

MCP 的三個核心原語

在寫 code 之前,先搞懂 MCP 的三個核心概念。我用遙控器來比喻:

Tools(工具) — 遙控器上的按鈕。按下「計算」,AI 就去算數學;按下「查天氣」,AI 就去打 API。每個按鈕定義了一個動作,AI 決定什麼時候按。

Resources(資源) — 書架上的參考資料。AI 可以翻閱這些資料來回答問題,但它不會去修改書架上的東西。適合放設定檔、文件、靜態資料。

Prompts(提示) — 預設的操作手冊。你幫 AI 寫好一套 SOP,它可以直接拿來用,省去每次都要重新描述需求的麻煩。

技術上的定義是:MCP Server 透過 JSON-RPC 2.0 協定,向 MCP Client(像是 Claude Code)暴露 tools、resources 和 prompts。Client 負責呼叫,Server 負責執行。

環境準備

需要的東西很簡單:

  1. Python 3.10 以上(asyncio 的一些語法需要)
  2. MCP Python SDK
1
pip install mcp

就這樣。沒有其他依賴。

第一個 MCP Server:計算機

先從最小的東西開始。我們要做一個計算機 MCP Server,讓 AI 可以做加減乘除。

為什麼選計算機?因為邏輯簡單到不需要花腦力理解業務需求,可以把注意力全部放在 MCP 的架構上。

建一個 calculator_server.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent

app = Server("calculator")


@app.list_tools()
async def list_tools():
"""告訴 Client 我們有哪些工具可以用"""
return [
Tool(
name="calculate",
description="Perform basic arithmetic",
inputSchema={
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "Math expression like '2 + 3'"
}
},
"required": ["expression"]
}
)
]


@app.call_tool()
async def call_tool(name: str, arguments: dict):
"""Client 呼叫工具時,這裡處理邏輯"""
if name == "calculate":
try:
result = eval(arguments["expression"])
return [TextContent(type="text", text=str(result))]
except Exception as e:
return [TextContent(type="text", text=f"計算錯誤:{e}")]


async def main():
async with stdio_server() as (read, write):
await app.run(read, write, app.create_initialization_options())


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

⚠️ eval() 在這裡純粹是教學用。正式環境請用 ast.literal_eval() 或數學解析器,不然使用者傳一段惡意程式碼進來你就去吃泡麵了。

拆解一下這段 code 在做什麼:

  • Server("calculator") — 建立一個叫 calculator 的 MCP Server 實例
  • @app.list_tools() — 註冊一個 handler,當 Client 問「你有什麼工具?」時回應。這裡回傳一個 Tool 物件,定義工具名稱、描述、參數的 JSON Schema
  • @app.call_tool() — 註冊另一個 handler,當 Client 說「幫我執行這個工具」時處理。回傳 TextContent 包著結果
  • stdio_server() — 用標準輸入輸出做傳輸。MCP 支援 stdio 和 SSE 兩種傳輸方式,stdio 最簡單,本機開發直接用

整個流程就是:Client 連上 → 問有什麼工具 → 選一個工具呼叫 → Server 執行 → 回傳結果。跟你按遙控器一模一樣。

接上 Claude Code

Server 寫好了,接下來讓 Claude Code 認識它。

打開 Claude Code 的設定,把 MCP server 加進去。在你的專案根目錄建立 .claude/settings.json,或是加到全域設定 ~/.claude/settings.json

1
2
3
4
5
6
7
8
{
"mcpServers": {
"calculator": {
"command": "python3",
"args": ["/absolute/path/to/calculator_server.py"]
}
}
}

注意 args 裡面的路徑要用絕對路徑。弄了半天 server 連不上,結果是相對路徑的問題 — 這種坑真的會讓人懷疑人生。

設定好之後,重新啟動 Claude Code,你應該會看到它自動偵測到 calculator 這個 MCP Server。這時候你可以直接跟 Claude 說「幫我算 1024 * 768」,它就會透過 MCP 呼叫你寫的計算機工具。

跑起來那一刻蠻爽的。你寫的 Python 程式,被 AI 當成自己的工具在用。

進階:加上 Resources

Tools 是讓 AI 「做事」,Resources 是讓 AI 「讀資料」。

來提供一份數學公式表給 AI 參考。在同一個 server 裡加上 resource handler:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from mcp.types import Resource

@app.list_resources()
async def list_resources():
return [
Resource(
uri="math://formulas",
name="常用數學公式",
description="基礎數學公式速查表",
mimeType="text/plain"
)
]


@app.read_resource()
async def read_resource(uri: str):
if str(uri) == "math://formulas":
content = """
面積公式:
- 圓形:π × r²
- 三角形:底 × 高 ÷ 2
- 梯形:(上底 + 下底) × 高 ÷ 2

體積公式:
- 球體:4/3 × π × r³
- 圓柱:π × r² × h
"""
return content

這樣 AI 在需要的時候,可以自己去讀這份公式表,不用你每次都在 prompt 裡貼一大段。Resource 的 URI 格式是自定義的,你可以用 math://db://file://,只要 Client 和 Server 說好就行。

完整的 Server 長什麼樣

把 tools 和 resources 組合起來,完整的 calculator_server.py 如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent, Resource

app = Server("calculator")


@app.list_tools()
async def list_tools():
return [
Tool(
name="calculate",
description="Perform basic arithmetic",
inputSchema={
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "Math expression like '2 + 3'"
}
},
"required": ["expression"]
}
)
]


@app.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "calculate":
try:
result = eval(arguments["expression"])
return [TextContent(type="text", text=str(result))]
except Exception as e:
return [TextContent(type="text", text=f"計算錯誤:{e}")]


@app.list_resources()
async def list_resources():
return [
Resource(
uri="math://formulas",
name="常用數學公式",
description="基礎數學公式速查表",
mimeType="text/plain"
)
]


@app.read_resource()
async def read_resource(uri: str):
if str(uri) == "math://formulas":
return """
面積公式:
- 圓形:π × r²
- 三角形:底 × 高 ÷ 2
- 梯形:(上底 + 下底) × 高 ÷ 2

體積公式:
- 球體:4/3 × π × r³
- 圓柱:π × r² × h
"""


async def main():
async with stdio_server() as (read, write):
await app.run(read, write, app.create_initialization_options())


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

一個檔案,70 行不到,你就有一個完整的 MCP Server,同時提供計算工具和參考資料。

接下來的路

你現在有了一個能跑的 MCP Server。計算機當然只是起點。

真正有趣的事情在後面。MCP 的價值不在於讓 AI 做加法,而在於你可以把任何系統變成 AI 的工具。資料庫、內部 API、CI/CD pipeline、監控系統 — 只要你能寫 Python 去操作它,你就能把它包成 MCP Server,讓 AI 直接用。

幾個值得探索的方向:

  • Database MCP — 讓 AI 直接查資料庫。不用再複製貼上 SQL 結果。MCP 生態系已經有現成的 DBHub 可以用
  • API MCP — 包裝你公司的內部 API。AI 能直接呼叫,省掉人工轉介
  • 認證機制 — MCP 的 OAuth 2.1 授權框架,讓 remote server 安全地接受外部連線
  • Remote MCP Server — 用 SSE(Server-Sent Events)傳輸,部署到雲端,多個 Client 共用

這些東西有一個共通的思維模式:你不是在寫「給人用的工具」,你是在寫「給 AI 用的介面」。設計 inputSchema 的時候,你在想的不是 UI 怎麼排版,而是 AI 怎麼理解參數的意義。Tool 的 description 不是給人讀的說明文件,是給 AI 判斷「這個工具能不能解決當前問題」的依據。

這是一種完全不同的軟體設計思維。當你掌握了這個框架,你看待自己寫的每一個 function、每一個 API endpoint 的眼光都會不一樣。不是「使用者會怎麼操作」,而是「AI 會怎麼理解和使用」。

Anthropic Academy 有免費的 MCP 課程,想深入的話可以從那邊開始。


參考來源:Model Context Protocol (MCP) - Anthropic Academy
官方文件:MCP Documentation