今天來介紹一個已經不知道被介紹多少遍的東西 MCP。
ref: Model Context Protocol explained
這張圖我一直覺得很貼切
MCP 全名是 Model Context Protocol,它是一個讓 AI 模型 ↔ 工具/資料來源 可以互通的通訊協定。
我覺得它的概念很像「USB Hub」:
雖然 LLM 很強,但它不是萬能的,不能直接去開電風扇或打開冰箱。
這時候要靠 MCP,把外部服務用統一的方式包起來,讓 LLM 知道該怎麼用。
換個角度來看:
假設我們有一堆 tools,要給 LLM 使用。問題來了 —— LLM 怎麼知道有哪些工具?怎麼確保大家溝通方式一致?
這就是 Protocol 的價值。
MCP 定義了兩個最核心的操作:
tools/list
→ 問 MCP server:「你有哪些工具?」
→ 回傳一個工具清單(包含 name
、description
、input_schema
)
tools/call
→ 當 LLM 決定要用某個工具,就用統一格式傳送 request
→ MCP server 執行後把結果丟回來
這樣就消除了不同 API 格式的差異,所有工具都能以一個標準方式被 LLM 使用。
MCP 其實不只有 tools,它把能力拆成三個大組件:
Feature | Explanation | Examples | Who controls it |
---|---|---|---|
Tools | 主動可被呼叫的功能 | Search flights / Send messages / Create calendar events | Model |
Resources | 被動資料來源,讀取資訊用 | Retrieve documents / Read calendars / Access DB schema | Application |
Prompts | 預先定義好的提示模板 | Plan a vacation / Summarize meetings / Draft an email | User |
可以看到控制權很有意思:
這樣分工後,整個協定的彈性就出來了。
目前 MCP 支援兩種傳輸方式:
說了這麼多,還是要來一段實際的範例。
下面這段 code 展示了如何用 fastmcp
建立一個簡單的 MCP server,並且用 client 呼叫它:
import asyncio
from fastmcp import Client
client = Client("./server_stdio.py")
async def main():
async with client:
# 基本 server 測試
await client.ping()
# 列出 server 提供的能力
tools = await client.list_tools()
resources = await client.list_resources()
prompts = await client.list_prompts()
print("Tools:", tools)
print("Resources:", resources)
print("Prompts:", prompts)
# 呼叫工具
result = await client.call_tool("hello", {"name": "Bob"})
print(result)
asyncio.run(main())
server_stdio.py
的實作則如下:
from fastmcp import FastMCP
mcp = FastMCP(name="MyServer")
@mcp.tool
def hello(name: str) -> str:
"""return a greeting message by given name"""
return f"Hello, {name}!"
if __name__ == "__main__":
mcp.run()
這樣就完成了一個最小可行的 MCP server + client:
hello
工具hello("Bob")
Hello, Bob!
streamable http 可以有兩種使用方法,
fastmcp 目前支援 3 個大廠,openai / gemini / claude
https://gofastmcp.com/integrations/openai
from openai import OpenAI
# Your server URL (replace with your actual URL)
url = 'https://your-server-url.com'
client = OpenAI()
resp = client.responses.create(
model="gpt-4.1",
tools=[
{
"type": "mcp",
"server_label": "dice_server",
"server_url": f"{url}/mcp/",
"require_approval": "never",
},
],
input="Roll a few dice!",
)
print(resp.output_text)
https://gofastmcp.com/clients/tools
這其實跟上面的 stdio 方法大同小異。但你要自己控制 client 的連線
async with client:
# With timeout (aborts if execution takes longer than 2 seconds)
result = await client.call_tool(
"long_running_task",
{"param": "value"},
timeout=2.0
)
# With progress handler (to track execution progress)
result = await client.call_tool(
"long_running_task",
{"param": "value"},
progress_handler=my_progress_handler
)
MCP 的出現有點像是 LLM 生態系的「共通語言」。
不管你是 Claude、GPT,還是未來的大廠 model,只要支援 MCP,就能直接使用 MCP server 提供的功能。
而且 官方 GitHub 上已經有一大堆 MCP server 可以直接用,不需要自己重頭實作。