AIによる翻訳。英語版は人による検証済みである。 原文を読む

Model Context Protocol の実践

教材キット

2026.11.19版(書籍の現行版)より。書籍が更新されると変わる。出典を明記すれば、自由に利用および改変できる。

シラバス

読書時間は章の本文に基づく。学習者はLabまたは自分のマシンでコード例も実行する。

週ごとに一章: 12 週

5 週間後

学習目標と概要

各章の学習目標はその冒頭の一文である。各構成案は章の節に従い、定義される用語、例を実行する前に求められる予測、各節が締めくくる規則を含む。 主要な用語と確認すべき予測は、クイズバンクが出題するとおり英語版のものである。

1. MCPをエンドツーエンドで理解する

読了まで約60分。5 例。

この章を読み終えると、既存の HTTP API を stdio 上の Model Context Protocol サーバの背後に置き、クライアントからそのツールを呼び出し、両者がやり取りするすべてのメッセージを読み、小さなホストを通じてモデルにツールを選ばせることができるようになる。

講義概要: 7 節
  1. ショップとその API
    • 実践ルール すでに運用している API をラップし、それを記録の正本として維持する。MCP サーバーは、自身の認証情報で API を呼び出して応答を変換する薄いアダプターにとどめる。そうすれば、API の検証、認可、ログは、モデルだけでなくすべてのクライアントに対して機能し続ける。データベースを直接利用して構築するのは、ラップすべき API がない場合に限り、その場合も、ビジネスルールは両方の種類のクライアントが共有する一か所に置く。
  2. Wrap one endpoint as a tool
    • 実践ルール Start with one read-only tool for one endpoint, and write its docstring for a model: what it does, what its inputs look like, what it returns. Raise ToolError with a message that tells the model what to do differently, and let unexpected exceptions stay generic so internal details never leave the server. Past a handful of endpoints, shape the tools around the tasks the model has to do rather than one per endpoint (Shape tools around tasks, not endpoints).
  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. Let a model choose the tool
    • 実践ルール Keep the host's prompt and the parsing of the model's reply in your own code, and test the loop against recorded replies rather than a live model. Record the model's raw text, not SDK objects, so an SDK release doesn't invalidate a recording, and make a replay fail when its input changes. Switch to a live model only for the measurement runs that decide which descriptions and which model you ship.
  6. What goes wrong in production
    • 実践ルール On the machine that launches a stdio server in production, check three things: nothing but JSON-RPC reaches standard output, every variable the server needs is passed explicitly, and the server answers server/discover within 10 seconds of starting. Keep the server's standard error in your logs, because that is where its real errors go.
  7. この章で下した決定

2. MCPがAPIに加えるもの

読了まで約66分。6 例。

この章を終えると、ホスト、クライアント、サーバーがそれぞれ何を担うかを説明できるようになる。

講義概要: 11 節
  1. ホスト、クライアント、サーバーを分離する
    • 重要用語 host, client, capability
    • 実践ルール ホストでは、サーバーごとに専用のクライアントを持たせ、会話とサーバーをまたぐ処理は、サーバーではなくホストのコードに置く。すべてのクライアントは、サーバーの提供内容を前提とせず、読み取ることから始める。そうすれば、サーバーがツールを変更してもホストが壊れない。サーバーを書くときは、サーバーに届いたリクエストしか見えないものと想定する。仕様がサーバーに見ることを許すのは、それだけだからである。
  2. 各機能を適切なプリミティブに置く
  3. ツールはモデルが選ぶアクションである
    • 重要用語 tool
    • 実践ルール 会話をもとに、モデルが利用するかどうかを判断すべき機能は、ツールにする。これには、顧客が書いた内容によって必要性が変わる照会と、返金のように何かを変更するすべてのアクションが含まれる。後者では、呼び出しの前にホストが同意を求める。
  4. リソースはアプリケーションが選ぶデータである
    • 重要用語 resource
    • 実践ルール ホスト自身のコードが必要になる場面を判断できるデータは、リソースにする。たとえば、既知の種類のチケットに適用されるポリシーや、ユーザーが開いたレコードがこれに当たる。会話を読んだモデルだけが必要かどうかを判断できるデータは、ツールのままにする。
  5. Prompts are templates the user chooses
    • 重要用語 prompt
    • 実践ルール Make a workflow a prompt when a person should start it and every run should follow the same steps, and keep the prompt's text on the server so that a change reaches every host at once. If no person chooses when it runs, it isn't a prompt: make the steps a tool, or put them in the host's own instructions.
  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. Handle a version the server doesn't support
    • 実践ルール When a server answers -32022, pick the newest version in both your list and its supported list, retry once, and show the user an error naming both lists if they share none. Don't retry in a loop, and don't guess a version the server didn't list. On your own server, keep the supported list exact, because clients choose from it.
  8. リスト結果のキャッシュ
    • 実践ルール すべての呼び出し元で同じになる一覧、たとえばショップのツール一覧には、TTL と "public" スコープを設定する。TTL は、デプロイ後に古い一覧を許容できる時間より長くしない。数時間ではなく数分にする。誰が問い合わせているかに依存するものには、SDK の既定値である "private" を保ち、cacheScope を認可チェックの代わりにしてはならない。クライアントでは、既定のキャッシュを維持する。このキャッシュは、client.listen(tools_list_changed=True) ストリームで変更通知が届くとエントリを破棄する(mcp/client/client.py)。このストリームは、リソースが変わったことをクライアントに知らせるが開くものと同じ種類である。このストリームがなければ通知はクライアントに届かないので、ストリームを開くこと。エントリを疑う別の理由があるときは、TTL に基づいてポーリングするのではなく、cache_mode="refresh" を使う。
  9. Keep an HTTP API where MCP adds nothing
    • 実践ルール Keep a plain HTTP API for callers whose code knows which endpoint to call, such as other services, fixed workflows and batch jobs, and put an MCP server in front of the same API for hosts where a model or a user chooses at run time. Measure the overhead on your own transport before you route high-volume traffic through MCP, and pin the protocol version in clients you control, so they skip the discovery probe. Keep auto mode for clients that may meet servers you don't control, which may speak only the 2025 protocol.
  10. 本番環境で何が問題になるか
    • 実践ルール 出荷しようとするサーバーでは、次の四点を確認する。各機能のプリミティブが、いつ実行するかを決める主体と一致していること。クライアントとサーバーの間に MCP の本文を編集するものがないこと。clientInfoに基づいて何かを決めていないこと。"public"のキャッシュヒントがすべて、どの呼び出し元に対しても同じデータだけを対象としていること。失敗したすべてのリクエストについて、プロトコルのバージョンとエラーコードをログに記録すること。バージョンやエンベロープのエラーは、クライアントまたはゲートウェイが変わったことを示す最初の兆候だからである。
  11. この章での決定事項

3. モデルが使えるツールを設計する

読了まで約77分。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. Write descriptions the model reads
    • 先に確認する Before you run it, predict how many first calls the vague set and the draft each get right.
    • 実践ルール Write each description in two to four sentences: what the tool does, when to use it instead of the tool it's most often confused with, what its inputs look like, and what it returns. Pass it as description= rather than relying on a multi-line docstring, so the model reads exactly the text you wrote. Then record the model you ship choosing tools for real tickets, read the wrong choices, and change the descriptions those choices point to. Change one thing per recording when you need to know which change worked, and check the result on tickets you didn't use to write the change.
  3. JSON Schemaで入力に型を付ける
    • 実践ルール すべての引数に、API が許す限り狭い型を付ける。ID にはパターン、固定値には enum、件数には範囲、日付には形式を用いる。不正な呼び出しはコードが実行される前に SDK に拒否させ、すべての失敗を一度に返す。スキーマに意味を任せてはならない。有効な日付でも、誤った日付でありうるからである。スキーマで表現できないことはツールの内部で検査し、チケットで不完全になりがちな値については、どう埋めるかを説明に書く。
  4. 出力スキーマで構造化コンテンツを返す
    • 実践ルール すべてのツールに、戻り値の型として pydantic モデルを与える。そうすれば、SDK は出力スキーマを公開し、ラッパーなしで構造化コンテンツを返し、テキストブロックも自動で加える。ホストのコードが行う判断ごとに、たとえば within_limit のように、モデルにフィールドを置く。判断を文章の中に残してはならない。素の文字列を返してよいのは、結果をどのコードも読まないツールだけである。
  5. 失敗をツール結果として報告する
    • 重要用語 protocol error, tool execution error
    • 実践ルール モデルが修正できる失敗にはすべて ToolError を送出し、メッセージには何が誤っていたか、代わりに何を送るべきかを示す。有効な値が少数なら、それも含める。MCPError は、設定など、どのモデルにも直せない失敗にのみ送出する。予期しない例外は汎用的なままにして、内部の詳細がサーバー上にとどまるようにする。エラーを単なる文字列として返してはならない。
  6. アノテーションでツールが何を変更するかを示す
  7. アノテーションはヒントとして扱い、保証とは見なさない
    • 実践ルール すべてのツールにアノテーションを付ける。ヒントを省くと、慎重なホストは最悪の場合を想定するからである。ツールを冪等と記すのは、サーバーがそれを強制している場合に限る。返金や支払いなど、一度だけ行われなければならない処理は、サーバー側の検証の背後に置く。ホストとしては、信頼するサーバーのアノテーションを、ユーザーに何を表示するかの判断に使い、同意を省略する許可としては決して使わない(Ask for consent before side effects)。それ以外のサーバーのアノテーションは、すべて未検証の主張として扱う。
  8. ツールの一覧を小さく保つ
    • 実践ルール 各サーバーには 1 種類の利用者と、その利用者のタスクに必要な少数のツールだけを与え、一覧がホストのプロンプトで占めるコストを測ること。トークンは、スキーマと、モデルが混同する 2 つのツールを区別する文に使い、スキーマと重複する説明文は削ること。ホストが、モデルが適切に選べる数を超えるツールを必要とする場合は、1 つのサーバーの一覧を接続によって変えるのではなく、ツールを複数のサーバーに分け、会話に必要なサーバーだけを接続すること。
  9. 本番で起こる問題
    • 実践ルール ショップのツールを本番に出す前に、出荷するモデルが実際のチケットのラベル付きサンプルに対してツールを選ぶ様子を録画し、モデルが修正できる失敗がすべて有用なメッセージ付きのToolErrorとして返ることを確認し、各出力スキーマを契約テストの対象にする。リリース後は、ツール選択の回数、引数に現れる例の値、ホストに表示されるRuntimeErrorを監視する。
  10. Decisions this chapter made

4. Serve data as resources and prompts

読了まで約71分。5 例。

学習の終わりには、publish the shop's policies and records as Model Context Protocol resources, address many records with one resource template, complete an argument while a user types it, tell a client when a resource changes, and package a refund review as a prompt the user can pickできるようになる。

講義概要: 8 節
  1. Expose the policies as resources
    • 重要用語 annotations
    • 実践ルール Publish the documents a host should be able to put in front of a model as static resources, under a scheme that names your system, with a MIME type and a description the host can show. Use https:// only for resources the client can fetch without your server. Mark a result public only when every caller gets the same one, and give high priority only to the one or two documents every answer depends on, not to all of them.
  2. Address records with resource templates
    • 実践ルール Use a resource template for records that share one shape and an ID. Return the API's own JSON, and raise ResourceNotFoundError for a miss, which gives the client -32602 with the URI. Keep the scope private for anything that belongs to a user. Leave the SDK's ResourceSecurity on, and validate the variable's format yourself too. Exempt a variable from the check only when it must carry a path, and then check the path yourself.
  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. 呼び出しの途中でユーザーに尋ねる

読了まで約69分。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 モデルで宣言し、decline と cancel で処理を分けたい場合は ElicitationResult を受け取る。入力要求を手作業で組み立てるのは、状態を自分で制御する必要がある場合だけにする。
  5. 機微な手順は URL に送る
    • 実践ルール 秘密にすべきものや、人を別のサービスにサインインさせるものは、フォームではなく必ず URL モードで送る。フロー自身の ID を requestState に入れ、accept を「ユーザーがページへ移動した」と扱い、フローが完了したかどうかは再試行のたびにサーバー自身の記録から判断する。フローを完了させる人が開始した人であることを確認する。
  6. ラウンドトリップ状態を改ざんできないように保つ
    • 実践ルール すべてのrequestStateを SDK にシールさせ、金銭、アクセス、データに関わる状態では決してシールを無効にしない。状態は小さく不透明に保つ。レコードそのものではなく、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. 本番環境で何が問題になるか
    • 実践ルール 質問をするサーバーのレプリカには、本番に出す前に、ローテーション可能な共有の鍵を1つ与え、状態の有効期間を人が要する時間に合わせ、見積ストアと一度限りの記録をすべて共有ストレージに移す。トランスポートに呼び出し元がある場合は、各質問をその呼び出し元に結び付ける。そのうえで、-32602 はログに記録された理由ごとに、-32021 はホストごとに、そして呼び出しあたりのラウンド数を監視する。
  9. この章で行った決定

6. Streamable HTTP で提供する

読了まで約74分。6 例。

この章を終えると、ショップの Model Context Protocol サーバーを Streamable HTTP で提供できるようになる。

講義概要: 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. Read one HTTP exchange
    • 実践ルール When an HTTP call fails, read the exchange first: the three routing headers, _meta in the body, the status and the content type. Route in a gateway on Mcp-Method and Mcp-Name if you need to, and never rewrite a body without rewriting its headers to match, because the server will refuse the pair with -32020. On a server that supports only the pinned revision, a 405 means an older client is opening a GET stream; the SDK's app serves those clients instead.
  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での呼び出しは、それをawaitしているタスクをキャンセルするか、タイムアウトによってキャンセルし、ストリームを閉じる処理はSDKに任せる。長いツールはasync defで書き、キャンセルを再送出し、awaitを伴うクリーンアップはシールドされたスコープの下に置く。長く実行されるツールはすべて再試行しても安全にする。ストリームが切れると呼び出しが失われ、クライアントがそれを再送するからである。
  5. スティッキーセッションなしでレプリカを動かす
    • 実践ルール スティッキーセッションを使わずにレプリカを動かし、すべてのレプリカに、同じサーバー名と、シークレットストアから注入した同じ requestState の鍵を与える。2つ目のレプリカを追加する前に、ハンドル、一度きりの記録、購読など、ツールがメモリ上に保持しているすべての状態を一覧にし、それぞれをすべてのレプリカが届くストレージへ移す。移し終えるまでは、それに依存するツールを Mcp-Name によって単一のレプリカへルーティングする。
  6. Reject requests from other origins
    • 実践ルール Keep the SDK's loopback default on a developer's machine. When you deploy on any other address, pass transport_security=TransportSecuritySettings(allowed_hosts=[...], allowed_origins=[...]) with the names your server answers to, such as mcp.fernhill.example, and never rely on the default. Treat Origin validation as protection against browsers only, and put authorization in front of every server that anything but its own host can reach.
  7. stdio と Streamable HTTP のどちらかを選ぶ
    • 実践ルール サーバが一人のユーザーのために、そのユーザーのマシン上で動作する場合は、stdio で提供する。複数のホストにサービスを提供する場合、ホストが到達できないシステムを守る場合、またはスケールが必要な場合は、Streamable HTTP で提供する。その際は、最初の外部ユーザーを迎える前にオリジンの検査と認可を備える。同じサーバのコードで両方を提供できるため、サーバごとではなく、デプロイごとに選ぶ。
  8. 本番環境で起こる問題
    • 実践ルール 店のサーバーをあるアドレスで受け付け可能にする前に、実際のプロキシ経路を通して四つの点をテストする。外部の Origin が 403 を得ること、呼び出しの実行中に進捗が届くこと、プロキシのアイドル上限より長い呼び出しが生き残ること、呼び出しのストリームを閉じるとツールが停止することである。その後、421、403、-32020 をクライアント別に、キャンセルを所要時間別に監視する。
  9. この章での決定事項

7. 長時間の処理をタスクとして実行する

読了まで約74分。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に対応しないホストが失うものをビューだけにする。モデルに呼ばせたくないアプリ専用ツールには、visibilityとして["app"]を指定する。なお、それを強制するのはサーバーではなくホストであることを忘れないこと。
  6. タスク、進捗通知、通常の呼び出しから選ぶ
    • 実践ルール ホストとサーバーの間にあるどのタイムアウトにも十分に収まる時間で結果が返る場合は、通常の呼び出しを使う。処理が長く、呼び出し側が開いたままに保たれると信頼できる接続上で待機し、表示用の数値を求める場合は、進捗通知を使う。処理が接続より長く続く可能性がある場合、または呼び出し側がいったん離れて戻ってきたい場合は、タスクを使う。タスクが返すのはステータスメッセージだけであることを受け入れ、拡張を持たないクライアントのために、通常の呼び出しによるフォールバックを用意するか、明確な -32021 を返す。
  7. What goes wrong in production
    • 実践ルール Move tasks' storage to where every replica can read it before they go to production, record each task's owner and check it on every task request, and set a TTL with a purge that runs on a schedule. Then watch -32602 from tasks/get by replica, the ratio of tasks/get to tools/call, the number of stored tasks, and how long work runs after a cancel.
  8. Decisions this chapter made

8. OAuthでクライアントを認可する

読了まで約93分。7 例。

この章を終えると、ショップの Model Context Protocol サーバーを OAuth で保護できるようになる。

講義概要: 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. メタデータ文書でクライアントを識別する
    • 実践ルール すべてのホストに、安定した https:// の URL で Client ID Metadata Document を一つ与える。文書には使用するリダイレクト URI だけを記し、シークレットは含めない。この URL を client_metadata_url として SDK に渡す。認可サーバーが資格情報を発行している場合は、それが最優先なので事前登録の資格情報を使い、Dynamic Client Registration は、ほかに何も対応していない認可サーバーに対してのみ残す。ループバック上のテストでは、クライアント ID を https:// の URL のままにし、本番のサーバーが受理しない http:// の ID をクライアントに与える代わりに、テスト用認可サーバーの中で文書のローカルな写しと関連付ける。
  3. Get a token with PKCE
    • 実践ルール Let the SDK's OAuthClientProvider run the authorization code flow, and check once, from the authorization server's side, what it sends: S256, state, and a resource equal to the server's URL in both requests. Add the check the SDK skips, and refuse an authorization server whose metadata doesn't list S256. On an authorization server you run, accept only S256, make codes single-use and short-lived, and bind each code to its client, its redirect URI and its resource.
  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. トークンが許可する範囲でツールのスコープを定める
    • 実践ルール すべてのツールをそのスコープに対応付け、リクエストの認可は、ヘッダーだけに頼らず、SDK が認証するのとまったく同じ資格情報を用いて、パース済みのリクエストに対して行うこと。Authorization ヘッダーが 2 個あるリクエストと、マップが扱わないメソッドは拒否する。Mcp-Name はヒントとして扱い、デコード後にボディと一致しなければならないものとする。サーバーと同じ方法で正確にパースできないボディは拒否する。スコープが不足している場合は、そのツールのすべてのスコープを示す 403 insufficient_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. ツールを悪用から守る

読了まで約67分。6 例。

本章を終えると、Model Context Protocol サーバーとそのホストの周囲に信頼境界を引き、トークンのパススルーを拒否し、サーバーが confused deputy(混乱した代理人)として動くのを防ぎ、ツール定義を固定して変更を検出し、チケットの文面をデータとして扱い、副作用のあるツール呼び出しの前に必ずユーザーへ確認できるようになる。

講義概要: 9 節
  1. 信頼境界を描く
    • 実践ルール MCP サーバーやホストを出荷する前に、その境界表を書くこと。データや権限をやり取りする当事者のすべての組について 1 行を設け、何が越えるか、誰が検査するかを記す。検査者が「モデル」や「相手側」である行は穴である。自分で制御できる検査でその穴を塞ぎ、モデルが読むテキストのように検査が成り立たない場合は、その背後にあるツールにできることを制限する。
  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. サーバーが混乱した代理人として振る舞うのを防ぐ
    • 実践ルール 操作する利用者を、ツールの引数から取ってはならない。検証済みトークンのサブジェクトから取り、複数の発行者を受け入れる場合は発行者も併せて用いる。顧客がサインインする場合、サブジェクトは顧客である。担当者がサインインする場合、サブジェクトは担当者であり、顧客はサーバーが ID で引いたレコードから取り、その人が扱ってよいものかどうかを照合する。呼び出しが触れるすべてのレコードを、それに照らして検査する。サーバーが発行するハンドルは、それを発行した利用者に紐づけ、他の利用者のレコードやハンドルには「見つからない」と応答する。サーバーがサードパーティの OAuth API を代理する場合は、セキュリティガイドの confused deputy の節にも従い、何かを転送する前にクライアントごとに自前の同意ページを表示する。
  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. 本番で何がうまくいかなくなるか
    • 実践ルール セキュリティ制御は、本番に出す前に、少なくとも 2 人のユーザーの本物のトークンを使い、HTTP 越しにテストする。ハンドルの所有者は、すべてのレプリカが読める場所に保存し、トークンは読み取りスコープから始め、サーバーがホストに渡すコマンドと URL を検証する。そのうえで、発行されたトークンと実際に使われたスコープ、レプリカごとの「見積もりなし」エラー、サーバーごとの同意の質問数、ユーザーが答える速さを監視する。
  9. この章で下した決定

10. チケットを処理するホストを構築する

読了まで約82分。6 例。

この章を終えると、次のことができるようになる。

講義概要: 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. Run the host loop
    • 実践ルール Keep the loop in the host, short and bounded: route each call through your own map, pass it through consent, give it a timeout, and send every outcome back to the model, errors included, in a format your own code writes. Cap the model calls per ticket. Anything longer than a few turns, such as planning across tickets or memory, belongs in an agent framework, not in the host's protocol code.
  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. サーバをテストし、動作を観察する

読了まで約78分。6 例。

この章を終えるまでに、Model Context Protocol サーバのツールをメモリ上と HTTP 経由の両方でテストし、クライアントを壊すスキーマ変更を出荷前に検出し、記録したホストの実行を回帰テストとして再生し、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. 本番環境で起きる問題
    • 実践ルール トレースやスコアを信頼する前に、それが何を対象としているかを確認する。対象とは、どのトランスポート、どのモデル、各スキーマのどのリリースかである。スパン名の種類には上限を設け、引数は既定ではスパンに入れない。ダッシュボードが使う属性名は、名前を付けた規約のバージョンに固定する。契約テストとリプレイは、レプリカに届く前のすべてのリリースに対して実行する。
  8. この章で下した決定

12. 2025年版サーバの移行

読了まで約75分。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 を今も使うホストが記録されていないかぎり、サーバーから HTTP+SSE トランスポートを移植せずに削除する。記録されている場合は、Streamable HTTP のエンドポイントと並べて古いエンドポイントを提供し、それらへのすべての接続をクライアントごとにログへ記録し、削除する日付を決めて各ホストの所有者に伝える。このトランスポートは、猶予期間が 12 か月ではなく 3 か月だったので、すでに削除の対象になっているものとして扱う。
  4. Replace sampling, roots and logging
    • 実践ルール Move every pushed elicitation into a resolver, which serves both eras. Delete sampling rather than move it: let the host's model do model work, or call a provider from the server with the server's own credentials. Turn roots into a parameter checked against an allow-list in the server's configuration, and send log lines to stderr and your traces, never to the client.
  5. 動的クライアント登録の置き換え
    • 実践ルール すべてのホストについてクライアント ID メタデータドキュメントを公開し、その URL を client_metadata_url として渡す。自分が運用するすべての認可サーバに、そのサポートを通知させる。登録エンドポイントは、それを必要とするホストが移行し終えるまでに限って残す。各トークンがどの種類のクライアント ID に対して発行されたかを記録し、登録のトラフィックが止まった時点を確認できるようにする。
  6. Port the code from SDK 1.x to 2.x
    • 実践ルール Keep a 2025-era server pinned to mcp<2 until its port passes its tests, then port in one change: the imports and renames the errors point at, then each silent break from the migration guide, checked with a test against what a client sees. Pin the 2.x release exactly afterwards, and treat each 2.x release as a change to test, since the SDK's warnings and defaults move between releases.
  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. What goes wrong in production
    • 実践ルール Prove the port through the real proxy path before it takes traffic, with four tests: a 2025 client completes a confirmation, a 2026 client completes the same one, a 2025 session survives a deployment, and the version header reaches the server. Then watch requests by era, 404s by client and every deprecation warning, until the 2025 count reaches zero.
  9. この章で下した判断

問題バンク

全章の設問と解答を、認証済み教育者向けに提供する。各解答は該当する節に紐づいている。 入手方法