iT邦幫忙

2025 iThome 鐵人賽

DAY 26
1

今天來介紹一個已經不知道被介紹多少遍的東西 MCP


MCP 是什麼

https://ithelp.ithome.com.tw/upload/images/20251010/20128319ZxtEK6VIQ1.png

ref: Model Context Protocol explained
這張圖我一直覺得很貼切

MCP 全名是 Model Context Protocol,它是一個讓 AI 模型 ↔ 工具/資料來源 可以互通的通訊協定。

我覺得它的概念很像「USB Hub」:

  • AI 模型(Claude、GPT…) = 電腦本體
  • 服務(Slack, Gmail, Calendar, Local files…) = 外接裝置
  • MCP = Hub,把大家都統一接起來

雖然 LLM 很強,但它不是萬能的,不能直接去開電風扇或打開冰箱。
這時候要靠 MCP,把外部服務用統一的方式包起來,讓 LLM 知道該怎麼用。


為何需要 MCP ?

換個角度來看:
假設我們有一堆 tools,要給 LLM 使用。問題來了 —— LLM 怎麼知道有哪些工具?怎麼確保大家溝通方式一致?

這就是 Protocol 的價值。
MCP 定義了兩個最核心的操作:

  • tools/list
    → 問 MCP server:「你有哪些工具?」
    → 回傳一個工具清單(包含 namedescriptioninput_schema

  • tools/call
    → 當 LLM 決定要用某個工具,就用統一格式傳送 request
    → MCP server 執行後把結果丟回來

https://ithelp.ithome.com.tw/upload/images/20251010/20128319Belv2lvO0t.png

這樣就消除了不同 API 格式的差異,所有工具都能以一個標準方式被 LLM 使用。


MCP Components

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

可以看到控制權很有意思:

  • Tools 是 model 主動觸發
  • Resources 是某個 application (db / file / ...) 暴露給 model 的上下文 (read only)
  • Prompts 則是使用者提供的任務模板

這樣分工後,整個協定的彈性就出來了。


使用 MCP

目前 MCP 支援兩種傳輸方式:

1. Stdio transport

  • 使用標準輸入/輸出 (stdin/stdout) 溝通
  • 適合在同一台機器的本地進程間傳遞訊息
  • 效能最佳,沒有網路延遲

2. Streamable HTTP transport

  • 用 HTTP POST 傳送訊息
  • 可以選擇用 SSE (Server-Sent Events) 來做 streaming
  • 適合跨網路情境(client ↔ server)

Example

Stdio

說了這麼多,還是要來一段實際的範例。
下面這段 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:

  • server 提供一個 hello 工具
  • client 問它有哪些工具,並呼叫 hello("Bob")
  • 最後得到回覆:Hello, Bob!

streamable Http

streamable http 可以有兩種使用方法,

  1. 你問完問題後,LLM 幫你呼叫 tools,然後整理整理再 return 給你 -> 你的 mcp server 在外網
  2. 你問完問題後,LLM 跟你說該用哪個 tools,你自己決定何時要 call tools -> 你的 mcp server 在內網

情境 1:讓 LLM 幫你 call tools

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)

情境 2:讓 LLM 幫你 call tools

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 可以直接用,不需要自己重頭實作。


上一篇
Day25: Todo List Memory Structure (2) - 實測與問題反思
下一篇
Day 27: register MCP servers on agent-brain
系列文
agent-brain: 從 0 開始打造一個 python package28
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言