由 AI 翻譯。經人工以英文驗證。 閱讀原文

Model Context Protocol 實務

教學套件

版次 2026.11.19 為本書目前的版次,會隨本書更新而變動。可自由使用與改編,但須標示本書出處。

課程大綱

閱讀時間僅計算本章的文字。學生也會在 Lab 或自己的電腦上執行範例。

每週一章:12 週

5 週後

學習目標與大綱

每章的學習目標即為其第一句。每份大綱依循該章各節,列出該節定義的名詞、執行範例前要求的預測,以及每節結尾所歸納的規則。 其關鍵術語與要提問的預測內容,依題庫所列,採用英文版次的內容。

1. MCP 端到端

閱讀約需 61 分鐘,含 5 個範例。

讀完本章,你將能把既有的 HTTP API 放在以 stdio 運作的 Model Context Protocol 伺服器之後,從用戶端呼叫它的工具,讀懂兩端交換的每一則訊息,並透過一個小型主機應用程式讓模型自行選擇工具。

課程大綱:7 節
  1. 認識商店與它的 API
    • 實用原則 包裝你已經在執行的 API,並讓它繼續作為紀錄的權威來源。MCP 伺服器應該是一個薄薄的轉接層,以自己的憑證呼叫 API 並轉譯回應,這樣 API 的驗證、授權與日誌,對每一種用戶端都持續有效,而不只是對模型。只有在沒有 API 可包裝時,才直接以資料庫為基礎來建置,而且要把商業規則集中在一處,讓兩種用戶端共用。
  2. 將一個端點包裝成工具
    • 實用原則 從針對單一端點的一個唯讀工具開始,並為模型撰寫它的 docstring:它做什麼、輸入長什麼樣子、回傳什麼。引發 ToolError 時,訊息要告訴模型該如何改變做法;至於非預期的例外,則保持通用,讓內部細節不會離開伺服器。端點超過少數幾個之後,應依模型必須完成的任務來設計工具,而不是每個端點一個工具(依任務而非端點設計工具)。
  3. Call the tool from a client
    • 實用原則 Connect with mcp.Client, launch stdio servers with sys.executable and an explicit env=, and give the client a name. Pass each variable the server needs and nothing else from your environment, so no server sees secrets meant for another program. When a tool fails with only the SDK's generic message, read the server's standard error before you change the client.
  4. Read the messages on the wire
    • 關鍵詞 server/discover
    • 實用原則 When a call behaves unexpectedly, trace the wire before you read the SDK's code: a relay that copies and logs lines works with any client and any server. Never write to standard output from a stdio server, not even a debugging print(), because the client reads every line there as a message. Use logging, which the SDK sends to standard error, or write to standard error yourself.
  5. 讓模型選擇工具
    • 實用原則 把主機的提示詞與模型回覆的解析留在自己的程式碼中,並以錄製下來的回覆而非即時模型來測試迴圈。請記錄模型的原始文字,而不是 SDK 物件,這樣 SDK 發行新版時就不會使錄製檔失效,並讓重播在輸入改變時失敗。只有在要決定採用哪些描述與哪個模型的衡量執行中,才改用即時模型。
  6. 正式環境中會出什麼問題
    • 實用原則 在正式環境中啟動 stdio 伺服器的機器上,檢查三件事:只有 JSON-RPC 會到達標準輸出、伺服器所需的每個變數都明確傳入,以及伺服器在啟動後 10 秒內回應 server/discover。請在日誌中保留伺服器的標準錯誤,因為它真正的錯誤都寫在那裡。
  7. 本章做出的決定

2. MCP 為 API 增添了什麼

閱讀約需 62 分鐘,含 6 個範例。

讀完本章,你將能說明主機(host)、用戶端(client)與伺服器(server)各自的職責,將商店的每項功能放進正確的 Model Context Protocol 原語(primitive),讀懂每個請求都會攜帶的版本與能力(capabilities),並判斷商店在何時應改為保留單純的 HTTP API。

課程大綱:11 節
  1. 區分主機、用戶端與伺服器
    • 關鍵詞 host, client, capability
    • 實用原則 在主機中為每個伺服器配置各自的用戶端,並把對話以及任何跨伺服器的事務留在主機的程式碼中,而不是放在伺服器裡。每個用戶端一開始都應讀取伺服器提供的內容,而不是預先假設,這樣伺服器更動其工具時,才不會讓主機失效。撰寫伺服器時,應假設它只看得到送給它的請求,因為規格書只允許它看到這些。
  2. 將每項能力放進正確的原語
  3. 工具是由模型選擇的動作
    • 關鍵詞 tool
    • 實用原則 當模型應該根據對話內容來決定是否使用某項功能時,就把它做成工具。這包括取決於顧客所寫內容的查詢,也包括每一項會變更資料的動作,例如退款;對於這類動作,主機會在呼叫之前先徵求同意。
  4. 資源是由應用程式決定如何使用的資料
    • 關鍵詞 resource
    • 實用原則 當主機端自己的程式碼能判斷何時需要某份資料時,就把它做成資源,例如適用於已知工單類型的政策,或使用者已開啟的紀錄。若只有模型閱讀對話後才能判斷是否需要,就維持為工具。
  5. 提示(Prompt)是由使用者選用的範本
    • 關鍵詞 prompt
    • 實用原則 當某個工作流程應由人員啟動,且每次執行都應遵循相同步驟時,就將它做成提示,並把提示的文字保留在伺服器上,讓變更能一次傳達到每個主機。如果沒有人決定它何時執行,它就不是提示:請把這些步驟做成工具,或放進主機自己的指示中。
  6. Carry the version and capabilities on every request
    • 實用原則 Read the version and the client's capabilities from each request, never from an earlier one, and answer -32021 when a call needs a capability the request didn't declare. Put the shop's own request metadata under its own reverse-DNS prefix, never under io.modelcontextprotocol/ or mcp. Log clientInfo and serverInfo for debugging, and decide nothing on them.
  7. 處理伺服器不支援的版本
    • 實用原則 當伺服器以 -32022 回應時,從你的清單與它的 supported 清單中同時存在的版本裡挑選最新者,重試一次;若兩者沒有交集,則向使用者顯示指明兩份清單的錯誤。不要以迴圈重試,也不要猜測伺服器未列出的版本。在你自己的伺服器上,請讓 supported 清單保持精確,因為用戶端會從中做選擇。
  8. 快取清單結果
    • 實用原則 對每位呼叫者都相同的清單(例如商店的工具清單),設定 TTL 與 "public" 範圍,並選擇一個不長於你在部署後能接受使用過期清單的 TTL:以分鐘計,而非以小時計。對任何取決於提問者身分的內容,維持 SDK 的預設值 "private",且絕不要讓 cacheScope 取代授權檢查。在用戶端,保留預設快取,它會在 client.listen(tools_list_changed=True) 串流上收到變更通知時移除對應項目(mcp/client/client.py),這類串流正是在資源變更時通知用戶端所開啟的。沒有該串流,就不會有通知送達用戶端,所以要開啟一個;當你有其他理由懷疑某個項目時,使用 cache_mode="refresh",而不是依 TTL 輪詢。
  9. 在 MCP 沒有加分之處保留 HTTP API
    • 實用原則 對於程式碼已知要呼叫哪個端點的呼叫者,例如其他服務、固定的工作流程與批次作業,請保留單純的 HTTP API;對於由模型或使用者在執行期做選擇的主機,則在同一個 API 前面放一個 MCP 伺服器。在把大量流量導入 MCP 之前,請在自己的傳輸上量測額外負擔,並在你掌控的用戶端中固定協定版本,使它們略過探測。自動模式則留給可能遇到你無法掌控的伺服器的用戶端,那些伺服器可能只支援 2025 年的協定。
  10. 正式環境中會出什麼問題
    • 實用原則 在出貨任何伺服器之前,檢查四件事:每項能力的原語與決定其執行時機的人相符;用戶端與伺服器之間沒有任何環節修改 MCP 本文;沒有任何決定是依據 clientInfo 做出的;每個 "public" 快取提示所涵蓋的資料,對每位呼叫者都相同。請記錄每個失敗請求的協定版本與錯誤碼,因為版本與信封(envelope)錯誤,是用戶端或閘道已變動的最早徵兆。
  11. 本章做出的決定

3. 設計模型能使用的工具

閱讀約需 85 分鐘,含 8 個範例。

讀完本章後,你可以將商店的 API 轉換為 Model Context Protocol 工具,使其名稱、描述、輸入結構描述、結果與錯誤都能讓模型據以行動,並且能衡量更動某個描述後,模型所選擇的工具會有什麼變化。

課程大綱:10 節
  1. Shape tools around tasks, not endpoints
    • 關鍵詞 Consent
    • 實用原則 Start from the tasks in your tickets or logs, not from your routes, and give each task one tool. Move every decision the model shouldn't make into the server, such as an amount or a sequence of calls. Use a handle when one task needs the result of another, state its lifetime in the description of the tool that creates it, make it unguessable, and check on every call that it belongs to the caller. Expose an endpoint as it stands only when the task and the endpoint are the same, as check_stock and GET /stock/{sku} are.
  2. 撰寫模型會讀的描述
    • 先詢問 Before you run it, predict how many first calls the vague set and the draft each get right.
    • 實用原則 每則描述以兩到四個句子撰寫:工具做什麼、何時應使用它而不是最容易與它混淆的工具、輸入長什麼樣子,以及它回傳什麼。以 description= 傳入,而不要依賴多行 docstring,讓模型讀到的正是你所寫的文字。接著,錄下你要上線的模型為真實工單選擇工具的過程,閱讀錯誤的選擇,並修改這些選擇所指向的描述。當你需要知道是哪項改動奏效時,每次錄製只改一件事,並用你撰寫該改動時沒有用過的工單來檢查結果。
  3. 以 JSON Schema 為輸入定型
    • 實用原則 在 API 允許的範圍內,盡可能窄地為每個引數定型:ID 用樣式(pattern),固定值用列舉(enum),數量用界限,日期用格式。讓 SDK 在你的程式碼執行之前拒絕錯誤的呼叫,並一次回傳所有失敗。不要把意義託付給綱要,因為有效的日期仍可能是錯誤的日期。在工具內部檢查綱要無法表達的內容,並在描述中說明,工單常常填得不完整的值應如何填寫。
  4. 以輸出綱要回傳結構化內容
    • 實用原則 讓每個工具都以 pydantic 模型作為回傳型別,這樣 SDK 會發布輸出綱要、回傳不含包裝的結構化內容,並為你加上文字區塊。主機端程式碼所做的每一項決策,都在模型中放一個欄位,例如 within_limit,而不是留在句子裡。只有結果不會被任何程式碼讀取的工具,才回傳裸字串。
  5. 將失敗回報為工具結果
    • 關鍵詞 protocol error, tool execution error
    • 實用原則 對於模型能夠修正的每一種失敗,都引發 ToolError,訊息中要指出錯在哪裡,以及應改送什麼;有效值不多時,一併列出。只有在沒有任何模型能修正的失敗(例如組態問題)時,才引發 MCPError,並讓非預期的例外維持泛用的訊息,使內部細節留在伺服器上。絕不要將錯誤當作純字串回傳。
  6. Mark what a tool changes with annotations
  7. 將註解視為提示,而非保證
    • 實用原則 為每個工具加上註解,因為省略提示會讓謹慎的主機端假設最壞的情況。只有在伺服器確實強制保證冪等性時,才將工具標示為冪等;退款、付款,以及其他只能發生一次的操作,都應由伺服器端的檢查把關。身為主機端,應只使用來自受信任伺服器的註解來決定向使用者顯示什麼內容,絕不能把它當作略過使用者同意的許可(在產生副作用前徵求同意),並將其他所有伺服器的註解視為未經驗證的主張。
  8. 讓工具清單保持精簡
    • 實用原則 讓每個伺服器只服務一種對象,並只提供該對象的任務所需的少數工具,同時測量清單在你的主機提示中的成本。把 token 花在結構描述,以及區分模型容易混淆的兩個工具的那一句話上,並刪去重複結構描述內容的描述文字。當主機需要的工具多到模型無法妥善選擇時,應把它們分散到多個伺服器,並且只連接某次對話所需的伺服器,而不是讓單一伺服器的清單取決於連線。
  9. 正式環境中會出什麼問題
    • 實用原則 在商店的工具上線到正式環境之前,請針對一份已標記的真實工單樣本,錄製您要發行的模型如何選擇工具,檢查模型有辦法修正的每一種失敗,是否都以附有實用訊息的 ToolError 回傳,並將每個輸出結構描述納入契約測試。發行之後,請監看工具選擇的次數、引數中的範例值,以及主機端的 RuntimeError。
  10. 本章的決策

4. 以資源與提示提供資料

閱讀約需 77 分鐘,含 5 個範例。

讀完本章後,你將能把商店的政策與紀錄發布為 Model Context Protocol 資源,以單一資源範本定址多筆紀錄,在使用者輸入引數時為其補全,在資源變更時通知用戶端,並把退款審查包裝成使用者可以挑選的提示。

課程大綱:8 節
  1. 將政策公開為資源
    • 關鍵詞 annotations
    • 實用原則 將主機應能放到模型面前的文件,以靜態資源發布,使用能標示你的系統名稱的 scheme,並附上主機可顯示的 MIME 類型與描述。https:// 只用於用戶端不經你的伺服器就能取得的資源。只有在每位呼叫者得到的結果都相同時,才將結果標記為 public;高優先順序只給每個回答都依賴的一兩份文件,而不是全部文件。
  2. 以資源範本定址記錄
    • 實用原則 對於形狀相同且有 ID 的記錄,使用資源範本。回傳 API 本身的 JSON,找不到時引發 ResourceNotFoundError,這會讓用戶端收到 -32602 與 URI。凡屬於使用者的內容,一律保持 private 範圍。保持 SDK 的 ResourceSecurity 開啟,並自行驗證變數的格式。只有在變數必須攜帶路徑時,才讓它免於該項檢查,而且要自行檢查該路徑。
  3. 為使用者補全引數
    • 實用原則 只從呼叫者有權讀取的內容來補全引數,可讀範圍須由伺服器所代表的對象決定,而非由請求中的任何內容決定。請自行依輸入的前綴過濾,並將清單限制在 100 個值以內,因為 SDK 不會代勞。只要你過濾的來源本身被截斷,就要設定 has_more;只有在你數過每一筆符合的項目時,才回報 total。對無權存取的記錄,要給出與不存在的記錄相同的未找到回應,讀取與補全皆然。
  4. 在資源變更時通知用戶端
    • 實用原則 只監看主機已呈現給模型或使用者的資源,並將每個事件視為重新讀取的訊號,絕不可當成新的值。每次開啟串流時,包括第一次以及每次中斷之後,都要重新讀取你所依賴的一切內容,因為不會有任何事件被重送。請在造成變更的程式碼路徑中,針對用戶端所讀取的確切 URI 發布更新。
  5. Package a workflow as a prompt
    • 實用原則 Offer a prompt for a procedure a person starts by name, and keep its arguments to values with a format you can check. Embed the resources the procedure depends on, so the host needn't fetch them. Validate every argument before you use it, and raise MCPError with INVALID_PARAMS for a bad one, because the SDK's own checks answer with an internal error.
  6. 在資源與工具之間做選擇
    • 實用原則 當主機端會附加某筆紀錄、而模型也會查詢它時,就同時以資源和工具的形式提供,並由同一條程式碼路徑來服務兩者,使它們不會彼此不一致。當工具找到主機端可能保留的紀錄時,回傳指向這些紀錄的資源連結,而不是其內容。
  7. What goes wrong in production
    • 實用原則 Test resources and prompts with two callers before they reach production. Neither may see, complete or watch the other's records, and neither should see a list change without a list-changed notification. Check that every resources/read of a user's data carries the private scope, and that a host recovers from a dropped stream by re-listening and re-reading.
  8. Decisions this chapter made

5. 在呼叫進行中詢問使用者

閱讀約需 84 分鐘,含 6 個範例。

讀完本章後,你將能讓商店的退款工具在呼叫進行到一半時停下來,請主機端的人員確認退款,再帶著答覆繼續執行。

課程大綱:9 節
  1. 了解為何無狀態伺服器無法等待回答
    • 實用原則 絕不要在工具呼叫內等待只有用戶端才能提供的東西。在固定修訂版的連線上,應將每一次對 ctx.elicit() 或 ctx.elicit_url() 的呼叫視為錯誤,改為回傳輸入請求,如下一節所做的。只有在必須同時回應 2025 年代用戶端的伺服器上,才保留舊的呼叫,而且只能放在對 ctx.protocol_version 的檢查之後(透過相容期間同時服務新舊用戶端)。
  2. Return an input request instead of a result
    • 實用原則 When a tool can't finish without the user, return an InputRequiredResult with one input request per question and a requestState that says what the retry must finish. Check the client's declared capabilities before you ask. Put in the state only what the tool needs to carry on, and let the SDK seal it. Make every side effect before the question either idempotent or harmless when no one answers, because the client may never call again.
  3. Resume the call with the answer
    • 實用原則 Use Client.call_tool with an elicitation callback in a host, and let the SDK run the rounds. Drive the loop yourself with client.session.call_tool(..., allow_input_required=True) only when the host must keep the state across a restart or show each round, and then repeat the arguments exactly. On the server, read the answer and the state together. When your server always sends a state, treat an answer that arrives without it, or with a state for another record, as a question never asked.
  4. 以引導請求取得結構化輸入
    • 實用原則 只有主機端的人才能給出的答案,使用表單模式,並讓每個表單只保留工具實際用到的少數欄位,凡答案屬於已知集合時就使用列舉。以解析函式和 pydantic 模型宣告表單,當拒絕與取消應導向不同的處理路徑時,採用 ElicitationResult。只有在需要自行控制狀態時,才手動建立輸入請求。
  5. 將敏感步驟交給 URL
    • 實用原則 凡是機密內容,以及任何讓人登入其他服務的步驟,都應透過 URL 模式處理,絕不使用表單。將流程自己的 ID 放進 requestState,把 accept 視為「使用者已前往該頁面」,並在每次重試時依伺服器自己的紀錄判斷流程是否已完成。確認完成流程的人就是發起流程的人。
  6. 確保往返狀態無法遭竄改
    • 實用原則 讓 SDK 封印每一個 requestState,對於涉及金錢、存取或資料的狀態,絕不要關閉封印。讓狀態保持精簡且不透明:放 ID,而不是整筆記錄。對於任何必須只發生一次的步驟,請在伺服器上自行保存已回答狀態的記錄,並在副作用發生之前檢查,而不是之後。
  7. Choose elicitation or a tool argument
    • 實用原則 Make a value a tool argument when the model can know it, and validate it in the tool. Elicit it when only the person can give it, or when the policy says a person must decide, and never accept that kind of value as an argument. Use URL mode for every secret. When you aren't sure, ask who would be at fault if the value were wrong.
  8. 正式環境中會出什麼問題
    • 實用原則 在會提問的伺服器上線之前,請讓它的各個副本共用一把可輪替的金鑰,將狀態的有效期限設為人們實際所需的時間,並把報價儲存區與每一筆僅限一次的記錄移到共用儲存空間。只要傳輸層有呼叫者,就將每個問題綁定到該呼叫者。然後依記錄下來的原因監看 -32602,依主機監看 -32021,並監看每次呼叫的輪數。
  9. 本章做出的決定

6. 透過 Streamable HTTP 提供服務

閱讀約需 91 分鐘,含 6 個範例。

讀完本章後,你將能夠透過 Streamable HTTP 提供商店的 Model Context Protocol 伺服器服務,讀懂每個請求與回應所攜帶的內容,從長時間執行的呼叫串流回傳進度並加以取消,在單一位址後以多個副本執行伺服器而不使用黏性工作階段(sticky session),並拒絕瀏覽器被誘騙而送出的請求。

課程大綱:9 節
  1. Move the server from stdio to HTTP
    • 實用原則 Serve over Streamable HTTP with MCPServer.run(transport="streamable-http") and its loopback default while you develop, and give clients the endpoint's URL. Leave stateless_http alone unless you also serve clients on a 2025 revision, where it decides whether they get sessions. Keep stdio for servers that a host launches for one user, as Choose stdio or Streamable HTTP explains.
  2. 讀一次 HTTP 交換
    • 實用原則 HTTP 呼叫失敗時,先讀交換內容:三個路由標頭、本文中的_meta、狀態與內容類型。若有需要,可在閘道器依據Mcp-Method與Mcp-Name進行路由,並且絕不要在改寫本文時不同步改寫標頭,因為伺服器會以 -32020 拒絕這組不一致的內容。在僅支援鎖定版本的伺服器上,405 表示有較舊的用戶端正在開啟 GET 串流;SDK 的應用程式則會改為服務這些用戶端。
  3. Stream progress on a long call
    • 關鍵詞 Progress
    • 實用原則 Report progress from any tool that can run longer than a few seconds, with a total when you know it and a message a person can read. Keep the SDK's default response mode. Use json_response=True only for a server whose every tool is quick, and know that it drops every progress report and every cancellation without telling anyone.
  4. 取消用戶端不再需要的呼叫
    • 實用原則 在 Streamable HTTP 上,藉由取消正在等待呼叫的任務或透過逾時來取消呼叫,並讓 SDK 關閉串流。將長時間執行的工具寫成 async def,重新拋出取消例外,並把任何需要等待的清理工作放在受保護的範圍內。讓每個長時間執行的工具都能安全重試,因為中斷的串流會使呼叫遺失,而用戶端會再次送出。
  5. Run replicas without sticky sessions
    • 實用原則 Run replicas with no sticky sessions, and give every replica the same server name and the same requestState keys, injected from your secret store. Before you add a second replica, list every piece of state your tools keep in memory, such as handles, once-only records and subscriptions, and move each into storage that every replica reaches. Until one is moved, route the tools that depend on it to a single replica by Mcp-Name.
  6. 拒絕來自其他來源的請求
    • 實用原則 在開發者的機器上保留 SDK 的迴環預設值。部署在任何其他位址時,請傳入 transport_security=TransportSecuritySettings(allowed_hosts=[...], allowed_origins=[...]),並列出伺服器所回應的名稱,例如 mcp.fernhill.example,切勿依賴預設值。請將 Origin 驗證視為僅能防範瀏覽器的保護,並在所有除了自身主機之外還有其他來源可連到的伺服器前面加上授權。
  7. 選擇 stdio 或 Streamable HTTP
    • 實用原則 當伺服器是在使用者自己的機器上代表單一使用者行動時,以 stdio 提供。當它服務多個主機、保護主機無法連到的系統,或必須擴展時,以 Streamable HTTP 提供,並在第一位外部使用者使用之前,為它加上來源檢查與授權。同一份伺服器程式碼可以同時支援兩者,因此應依部署來選擇,而不是依伺服器來選擇。
  8. 正式環境中會出什麼問題
    • 實用原則 在商店的伺服器於某個位址上接收流量之前,請透過真實的代理伺服器路徑測試四件事:外來的 Origin 得到 403、呼叫執行期間進度會抵達、超過代理伺服器閒置上限的呼叫仍能存活,以及關閉呼叫的串流會使工具停止。然後依用戶端觀察 421、403 與 -32020,並依時間長度觀察取消。
  9. Decisions this chapter made

7. 以工作任務執行長時間作業

閱讀約需 89 分鐘,含 4 個範例。

讀完本章,你將能協商 Model Context Protocol 的擴充功能,把耗時的補貨報表當作由用戶端輪詢的任務來執行,讓任務到期或將其取消,並說明 MCP Apps 為工具增添了什麼。

課程大綱:8 節
  1. Negotiate an extension
    • 實用原則 Turn an extension on only on a side that implements it, through the SDK's extension classes, never by writing the identifier into capabilities by hand. Decide, for each tool on the server, what a client without the extension gets: an ordinary result when the work can finish within a normal call, and error -32021 when it can't. Check the client's declaration on every request, because at the pinned revision each request declares its own.
  2. Start a task instead of waiting
    • 實用原則 Answer with a task when the work can outlive the connection, and decide per call, not per tool, when some calls are short. Store the task before you return the handle, and generate its ID from a cryptographic random source, with at least 128 bits. Run the same code a plain call runs, so a task's result never differs from a plain result. Never return a task to a request that didn't declare the extension.
  3. Poll a task and fetch its result
    • 實用原則 Poll at the server's pollIntervalMs, re-read it on every reply, and stop at the first terminal status. Treat completed as the original call's result, isError and all, and failed as a protocol error. Hide the polling in a client extension so the rest of the host sees plain calls. When a host must survive a restart, store each task ID before the first poll, and resume from it.
  4. Expire and cancel tasks
    • 實用原則 Give every task a TTL that covers the longest wait you expect between the work finishing and the client fetching it, and purge after it; for the shop's restock report, that is an hour. Make long work check for cancellation at each natural step, such as each product, and clean up there. In the client, treat a cancel's acknowledgement as "asked", not "stopped", and treat -32602 from tasks/get as a task that is gone for good.
  5. 了解 MCP Apps 增添了什麼
    • 實用原則 當結果需要文字以外的形式才能據以行動,例如要排序的表格或每列各一個選項,而且使用者所用的主機支援此擴充功能時,才採用 MCP Apps。請讓每個啟用 UI 的工具的文字結果保持完整,使不支援 Apps 的主機只損失檢視。當模型不應呼叫僅供應用程式使用的工具時,請將其可見性設為 ["app"],並記得強制執行這項限制的是主機,而不是你的伺服器。
  6. 選擇任務、進度回報或一般呼叫
    • 實用原則 當結果能在主機與伺服器之間所有逾時限制內從容傳回時,使用一般呼叫。當工作很長、呼叫端在一條可信賴會保持開啟的連線上等待,而且想要顯示數值時,使用進度回報。當工作可能比連線更長,或呼叫端想先離開再回來時,使用任務。要接受任務只能回報狀態訊息這一點,並為沒有該擴充功能的用戶端保留一般呼叫的備援方式,或明確回傳 -32021。
  7. 正式環境中會出什麼問題
    • 實用原則 在上線之前,先把任務的儲存移到每個副本都能讀取的地方,記錄每個任務的擁有者並在每個任務請求中檢查,並設定 TTL 與按排程執行的清除。接著依副本監看 tasks/get 回應的 -32602、tasks/get 與 tools/call 的比例、已儲存的任務數量,以及取消後工作仍執行多久。
  8. 本章做出的決定

8. 以 OAuth 授權用戶端

閱讀約需 123 分鐘,含 7 個範例。

讀完本章後,你能以 OAuth 保護商店的 Model Context Protocol 伺服器。

課程大綱:9 節
  1. Find the authorization server from the resource
    • 實用原則 Give every protected server an AuthSettings with its endpoint's URL as resource_server_url, exactly as clients will type it, and the smallest required_scopes that every request needs. Check the chain with one request that carries no token: a 401, a resource_metadata URL, metadata whose resource is the endpoint, and authorization server metadata whose issuer is the URL you fetched it from. When a value differs by a trailing slash or a port, fix the configuration rather than relaxing the client.
  2. Identify the client with a metadata document
    • 實用原則 Give every host one Client ID Metadata Document at a stable https:// URL, with only the redirect URIs it uses and no secret, and pass that URL to the SDK as client_metadata_url. Use pre-registered credentials where an authorization server has issued them, since they rank first, and keep Dynamic Client Registration only for authorization servers that support nothing else. In tests on loopback, keep the client ID an https:// URL and associate it with a local copy of the document in the test authorization server, rather than giving the client an http:// ID that no production server accepts.
  3. 以 PKCE 取得權杖
    • 實用原則 讓 SDK 的 OAuthClientProvider 執行授權碼流程,並從授權伺服器的一側檢查一次它送出的內容:S256、state,以及在兩個請求中都等於伺服器 URL 的 resource。補上 SDK 略過的檢查,並拒絕中繼資料未列出 S256 的授權伺服器。在由你自己執行的授權伺服器上,只接受 S256,讓授權碼只能使用一次且有效期短,並將每個授權碼綁定到其用戶端、重新導向 URI 與資源。
  4. Bind each token to one server
    • 實用原則 Set validate_token_resource=True on every protected server, and make the token verifier fill AccessToken.resource from the token's aud. Treat an MCPDeprecationWarning from AuthSettings as a failed deployment, not as noise. Test the check with a token for another resource from the same authorization server, which must get 401. A server that calls another service on a client's behalf gets its own token for that service and never passes the client's token on (Never pass a client's token through).
  5. Validate the issuer of each response
    • 實用原則 Send iss from every authorization server you run, and advertise it with authorization_response_iss_parameter_supported: true, so that clients reject an answer without it. In a host, keep the SDK's check, add no normalisation around it, and treat a mismatch as an attack: show the user none of that response's error text. When a host must use an authorization server that doesn't send iss, keep the host to an allow-list of authorization servers, and refuse or warn the user about any server not on it. Don't count on a separate redirect URI per server when the host is identified by a metadata document.
  6. 依權杖允許的範圍來限定工具
    • 實用原則 將每個工具對照到其所需的 scope,並且只使用 SDK 所驗證的那份憑證來授權已解析的請求,絕不單憑標頭。拒絕出現兩個 Authorization 標頭的請求,以及對照表未涵蓋的任何方法。將 Mcp-Name 視為解碼後必須與本文相符的提示,並拒絕任何無法以與伺服器完全相同的方式解析的本文。對缺少的 scope 以 403 insufficient_scope 挑戰回應,列出該工具的所有 scope,並讓 required_scopes 僅限於每個請求都需要的內容。
  7. 在呼叫需要時要求更多權限範圍
    • 實用原則 讓 SDK 執行提升授權,並保留它對權限範圍取聯集的做法。請列出呼叫者可能經由提升授權取得的每一個工具,因為被隱藏的工具永遠不會收到啟動提升授權的 403。在主機端,比較權杖回應所授予的權限範圍與質詢所要求的權限範圍。兩者不同時,應視為一項決定,而不是故障:告訴使用者這次呼叫需要哪個權限範圍,並把工單轉交給持有該權限的人。切勿讓授權伺服器經由提升授權授予使用者角色所不允許的權限。用戶端只負責要求,決定權在授權伺服器。
  8. What goes wrong in production
    • 實用原則 Run three probes against the deployment before the shop's server takes traffic. A request without a token gets 401 with a resource_metadata URL. A token for another resource gets 401. A refund with a read-only token gets 403 with scope="refunds:write", and the same refund with a second Authorization header gets 400. Then check the metadata of every authorization server your hosts use for S256, iss support and metadata document support, and watch the 401s, 403s and authorization requests per host.
  9. Decisions this chapter made

9. 保護工具以防濫用

閱讀約需 81 分鐘,含 6 個範例。

讀完本章後,你將能夠為 Model Context Protocol 伺服器及其主機劃定信任邊界、拒絕權杖直通(token passthrough)、避免伺服器淪為混淆代理人(confused deputy)、固定工具定義以便發現被更動的定義、將工單文字視為資料,並在任何有副作用的工具呼叫之前詢問使用者。

課程大綱:9 節
  1. 劃定信任邊界
    • 實用原則 在發布 MCP server 或 host 之前,先寫出它的邊界表:每一對交換資料或權限的當事方各占一列,寫明跨越的內容與由誰檢查。檢查者是「模型」或「另一方」的那一列,就是缺口。用你能掌控的檢查來補上它;當根本無法設置任何檢查時,例如模型所讀的文字,就限制其背後的工具能做的事。
  2. Never pass a client's token through
    • 實用原則 Accept only tokens whose audience is your server, and turn the check on explicitly, since the SDK doesn't by default. Call every upstream service with a credential of the server's own: an API key, a client-credentials token, or a token for the user from the upstream's own authorization server. Never forward the bearer token you received, even to a service that would accept it, and log the caller's identity yourself, because the upstream's logs will show only your server.
  3. 避免伺服器淪為混淆代理人
    • 實用原則 絕不從工具引數取得執行動作的使用者。要從已驗證權杖的 subject 取得,若接受不只一個簽發者,則連同簽發者一併採用。顧客自行登入時,subject 就是顧客;客服人員登入時,subject 是該客服人員,而顧客來自伺服器依 ID 查詢的紀錄,並對照該人員可處理的範圍加以檢查。每一次呼叫所碰觸的每筆紀錄,都要以它來檢查。把伺服器簽發的每個控制代碼綁定到被簽發的使用者,對於其他使用者的紀錄與控制代碼,一律回應為找不到。若你的伺服器代理第三方的 OAuth API,也要遵循安全指南中關於混淆代理人的章節,並在轉送任何內容之前,針對每個用戶端顯示你自己的同意頁面。
  4. Catch poisoned tool descriptions
    • 先詢問 Before you run the example, predict how many of the three poisoned runs call track_parcel.
    • 實用原則 Treat every definition from a server you don't operate as untrusted input to the model. When a user first enables a server, show the full definitions, not only titles, and look for free-text parameters the tool doesn't need, which are a poisoned description's channel. Don't count on the model or a scanner. Limit what each server can receive and each tool can do, and gate the calls.
  5. Pin tool definitions and flag changes
    • 實用原則 Pin every tool definition the user approves, by a hash over its name, title, description, schemas and annotations, per server. On a list-changed notification or a cache refresh, compare, keep any changed or new tool from the model, and show the user the difference before enabling it again. Accept that harmless rewordings ask again too: a definition the model reads is part of what the user agreed to.
  6. 將工單文字視為不受信任的資料
    • 實用原則 假設客戶所寫的任何文字,總有一天會以指令的形式到達模型,並設計工具,使服從這些文字所造成的傷害有其界限。金額、擁有者與上限要取自伺服器自己的紀錄,絕不取自模型根據文字填入的引數,並將副作用置於伺服器端的檢查與主機端的同意之後。請記錄工具所忽略的引數,因為在不接受該引數的呼叫上出現 amount,就是文字遭注入的徵兆。
  7. 在產生副作用之前先徵求同意
    • 實用原則 對每一個不在主機端自有「無副作用呼叫」清單上的工具呼叫,都要先詢問使用者,並依你所知道的資訊為每個伺服器分別建立該清單,絕不依據註解建立。顯示確切的引數,使用者展開時要完整顯示,並將每項決定連同該呼叫一併記錄。即使伺服器自己會要求確認,也要把同意機制保留在主機端,因為你不信任的伺服器不會去詢問。
  8. 正式環境中會出什麼問題
    • 實用原則 安全控制在上線前,應以 HTTP 搭配至少兩位使用者的真實權杖進行測試。把控制代碼的擁有者存放在每個副本都能讀取的地方,權杖一開始只給讀取範圍,並驗證伺服器交給主機的指令與 URL。接著觀察已簽發權杖與實際使用範圍的對比、各副本的「查無報價」錯誤、每個伺服器提出的同意問題數量,以及使用者回答的速度。
  9. 本章做出的決定

10. 建構處理工單的主機端

閱讀約需 104 分鐘,含 6 個範例。

讀完本章,你將能把主機端(host)連接到數個 Model Context Protocol 伺服器,為它們的工具命名以避免衝突,執行一個簡短的迴圈讓模型呼叫工具並讀取結果,代替使用者回應伺服器的輸入請求,把資源放進模型的上下文,並用以上所有機制處理一個工單佇列。

課程大綱:8 節
  1. Connect one client per server
    • 實用原則 Give each server its own Client, in auto mode, under a key from the host's configuration. Cache each server's era for as long as its process or origin lasts, reuse it across restarts of the same configuration if you like, and probe again when a request fails with a version error. Don't use ClientSessionGroup at mcp 2.3.0: its connect_to_server speaks only the 2025 handshake, and given Client sessions it adds merged lists but not the retry rounds or the host's own names. Check again at each SDK release, because a group that probes would remove the need for your own map.
  2. Name tools across servers
    • 實用原則 Prefix every tool name with a key from the host's configuration, joined by . or _, and route each call back through your own map, never by serverInfo.name. Prefix all names, not only the ones that collide, so names stay stable when a server changes. Send an unknown or unprefixed name back to the model as an error instead of guessing.
  3. 執行主機迴圈
    • 實用原則 讓迴圈留在主機中,保持簡短且有界限:每個呼叫都經過你自己的對照表來路由、通過同意關卡、設有逾時,並把每一種結果(包括錯誤)以你自己的程式碼所寫的格式送回模型。限制每張工單的模型呼叫次數。任何超過數輪的工作,例如跨工單的規劃或記憶,應該交給代理程式框架,而不是放在主機的協定程式碼中。
  4. Answer input requests for the user
    • 實用原則 Give each client its own elicitation callback that knows which server it belongs to, and show the user that server's name with its message, the fields and a way to decline. Return a decline to the model as the server's error, not as silence, so the model can say what happened. Keep consent in the host as well, because the server's question covers only what the server chooses to ask.
  5. Put resources in the model's context
    • 實用原則 Decide in the host which resources reach the model, by rules you can state: a fixed list, or annotations from servers you trust, with a cap on their size. Read them through the client's cache. Let the user add a resource for one ticket when the rule misses it, and never let the model or a ticket's text choose on its own.
  6. Work through the ticket queue
    • 實用原則 Treat the model's last reply as a draft and the host's call log as what happened. Before a reply reaches a customer, compare its promises with the calls that ran, and send a ticket to a person when they differ, such as a refund ticket with no refund made. Strip any handle, such as a quote_id, from a reply before it goes out. Score a run on outcomes, not only on the first tool, and record a run of the whole queue each time you change the prompt, a description or the model.
  7. What goes wrong in production
    • 實用原則 Make the host log, per ticket, the tools offered, every call with its outcome, every consent question and input request, and the model's last reply, before it goes to production, so a bad answer can be traced to the turn that caused it. Watch the size of the tool list per model call, reconnect and retry on a lost call, and keep every server's tool list and pins under the host's control.
  8. 本章做出的決定

11. 測試伺服器並觀察其執行

閱讀約需 103 分鐘,含 6 個範例。

讀完本章,你將能夠在記憶體內與透過 HTTP 測試 Model Context Protocol 伺服器的工具、在發布前找出會破壞用戶端的結構描述變更、將錄製的主機執行過程重播為迴歸測試、以 OpenTelemetry 追蹤工具呼叫、衡量模型選對工具的頻率,以及在不破壞既有用戶端的前提下淘汰一項工具。

課程大綱:8 節
  1. Test tools in memory
    • 實用原則 Test each tool in memory with Client(server, raise_exceptions=True), and assert on structured_content fields and is_error, not on whole results. Keep at least one test per transport you ship that goes over it on loopback, for the header, origin and streaming checks an in-memory test can't reach, and put the tests of trace propagation and list changes there too.
  2. Check schemas as a contract
    • 實用原則 Keep the last release's tools/list in the repository, and in CI validate every structured result your tests produce against it as well as against the new schema, each by the dialect it declares and by 2020-12 when it declares none. Treat a removed, renamed or retyped output field and a new required input as a breaking change: add the new field beside the old one, or add a new tool, and retire the old shape through a window (Change tools without breaking clients). Don't rely on a short TTL to protect clients that are already connected.
  3. Replay recorded host runs
    • 實用原則 Replay a recorded run of the whole queue in CI, assert on each ticket's tool sequence, and run a check that compares each reply's promises with the calls that returned a result. Keep generated IDs and clocks fixed in the servers a replay runs against, or it stops for reasons that aren't changes. Then treat RecordingMismatch as a signal, not as a flaky test: when you change a description, a prompt or a tool's output, record again with the recording script and compare the new run's scores with the old run's before you ship.
  4. Trace calls with OpenTelemetry
    • 實用原則 Install an OpenTelemetry SDK and exporter in every server and host you run, and let the SDK's middleware make the server spans. Build dashboards on the attributes the SDK emits, mcp.method.name, gen_ai.tool.name and error.type, and label them as following a Development-status convention at a named version, because the names may change. Don't validate method names against the pinned conventions package. Test propagation over a real transport, and wrap in-memory calls in a span of your own when a test needs a parent.
  5. 衡量正確選用工具的頻率
    • 實用原則 每次記錄的執行,都要依標籤針對第一個工具評分,而不只看整體,並將引數分開評分,分別對照工單給模型的內容與真實情況。先處理造成最大混淆的描述,重新記錄,並比較兩次記錄之間各標籤的分數。每個分數旁都要標明模型、提示詞與工單集,且絕不要在不同設定之間比較分數。
  6. Change tools without breaking clients
    • 實用原則 Retire a tool in three releases: add the replacement and mark the old tool deprecated in its description, keep both working through a window you announce, then answer the old name with an execution error that names the replacement. Shorten ttlMs on tools/list while the change is under way, publish a list change at each release, and open a subscriptions/listen stream in every host you control. Say in your changelog that the window is your policy, since the protocol defines none.
  7. 正式環境中會出什麼問題
    • 實用原則 在你依賴某個追蹤或分數之前,先檢查它涵蓋了什麼:哪種傳輸方式、哪個模型,以及每個結構描述的哪個版本。讓 span 名稱保持有界,並預設不將引數放入 span,把儀表板使用的屬性名稱固定在具名的慣例版本,並在每個版本抵達副本之前,對它執行契約測試與重播。
  8. 本章做出的決定

12. 遷移 2025 年代的伺服器

閱讀約需 84 分鐘,含 6 個範例。

讀完本章後,你可以將依 2025 年各修訂版與 Python SDK 1.x 版本線所撰寫的 Model Context Protocol 伺服器,遷移到修訂版 2026-07-28 的規範與 mcp 2.3.0。

課程大綱:9 節
  1. Inventory what the old server depends on
    • 實用原則 Inventory before you change anything, and sort the list by status. Fix every removed dependency before you let a client at the pinned revision connect, because there is no window for it, and count every request the server pushes mid-call as removed, even when the feature it asks for is only deprecated. Give each deprecated one a date of your own, earlier than the registry's earliest removal, and don't wait for warnings: run a scan like this one in CI, because the SDK is silent about some deprecated features.
  2. 移除 initialize 與工作階段 ID
    • 實用原則 在舊伺服器中搜尋所有使用工作階段、其 ID,以及任何依連線保存之內容的地方,並把每一份狀態轉換成代號:由一個工具傳回,下一個工具以引數接收。讓代號保持不透明,給它一個由建立它的工具之說明所載明的到期時間,在每次呼叫時檢查呼叫者是否可使用它,並把它存放在每個副本都能讀取的地方。後續呼叫所需的任何內容,都不要放在以工作階段為鍵的字典中,即使是仍然有工作階段的 2025 年代用戶端也一樣。
  3. 從 HTTP+SSE 遷移到 Streamable HTTP
    • 實用原則 除非日誌顯示仍有主機使用 HTTP+SSE,否則請從伺服器刪除該傳輸方式,而不是移植它。若有,則在 Streamable HTTP 端點旁提供舊端點,依用戶端記錄每一次對它們的連線,並訂出移除日期,告知每個主機的擁有者。請將該傳輸方式視為已可移除,因為它的寬限期是三個月,而非十二個月。
  4. 取代 sampling、roots 與 logging
    • 實用原則 將每一個推送式的 elicitation 移入解析器,它能同時服務兩個時期的用戶端。刪除 sampling,而不是搬移它:讓主機端的模型負責模型的工作,或由伺服器以自己的憑證呼叫供應商。把 roots 改為參數,並對照伺服器設定中的允許清單來檢查;日誌行則送往 stderr 與你的追蹤系統,絕不送給用戶端。
  5. Replace dynamic client registration
    • 實用原則 Publish a Client ID Metadata Document for every host and pass its URL as client_metadata_url. Make every authorization server you run advertise support for it, keep its registration endpoint only until the hosts that need it have moved, and log which kind of client ID each token was issued to, so that you can see when registration traffic has stopped.
  6. 將程式碼從 SDK 1.x 移植到 2.x
    • 實用原則 在移植通過測試之前,讓 2025 年代的伺服器固定在 mcp<2,然後在一次變更中完成移植:先處理錯誤訊息所指出的匯入與更名,再處理遷移指南中每一項無聲的不相容變更,並以對照用戶端所見內容的測試加以檢查。移植後請精確固定 2.x 的版本,並把每個 2.x 版本都視為需要測試的變更,因為 SDK 的警告與預設值會在版本之間變動。
  7. Serve old and new clients through the window
    • 實用原則 Serve both eras from one streamable_http_app() through the window, write every question a tool asks as a resolver, and route requests that carry Mcp-Session-Id to the replica that minted it. Count requests by era. When the 2025 count has stayed at zero for as long as your slowest host takes to upgrade, serve the pinned revision only, and answer initialize with an error that names the versions you support, as the specification asks.
  8. 正式環境中會出什麼問題
    • 實用原則 在移植版本接收流量之前,先透過真實的代理伺服器路徑加以驗證,並進行四項測試:2025 用戶端完成一次確認、2026 用戶端完成同一次確認、2025 工作階段在部署後仍然存續,以及版本標頭能抵達伺服器。接著依時代觀察 requests、依用戶端觀察 404,並留意每一則棄用警告,直到 2025 的計數降為零。
  9. 本章做出的決定

測驗題庫

每章皆附習題與解答,供經驗證的教育工作者使用。每個解答都對應其所屬的節。 如何取得