Skip to content

Sampling

Documentation Index

完全なドキュメント索引を取得してください: modelcontextprotocol.io/llms.txt

さらに先へ進む前に、利用可能なすべてのページを把握するために、このファイルを使用してください。

The Model Context Protocol (MCP) は、client を通じて language model から LLM sampling("completions" または "generations")を request するための標準化された方法を server に提供します。このフローにより、server が AI 機能を活用できる一方で、model へのアクセス、選択、権限に対する制御は client が維持できます。server の API key は不要です。 server は、text、audio、image ベースのやり取りを request でき、任意で MCP server からの context を prompt に含めることもできます。

User Interaction Model

MCP における Sampling により、server は、ほかの MCP server feature の内側にネストされた形で LLM call を発生させることで、agentic な振る舞いを実装できます。

実装は、自身の要件に合う任意のインターフェイスパターンで sampling を公開して構いません。プロトコル自体は、特定のユーザーインタラクションモデルを義務付けていません。

trust & safety および security のために、sampling request を拒否できる人間が常に介在しているべきです (SHOULD)。

アプリケーションは次を行うべきです (SHOULD)。

  • sampling request を確認しやすく直感的な UI を提供する
  • 送信前にユーザーが prompt を閲覧・編集できるようにする
  • 配信前に生成された response を確認用に提示する

Tools in Sampling

server は、sampling request に tools 配列と任意の toolChoice 設定を含めることで、sampling 中に client の LLM が tool を使うよう request できます。これにより、server は、LLM が tool を呼び出し、結果を受け取り、その後会話を続けるような agentic な振る舞いを、単一の sampling request フローの中で実装できます。

tool 使用を伴う sampling request を受け取るために、client は sampling.tools capability による tool use サポートを宣言しなければなりません (MUST)。server は、sampling.tools capability による tool use サポートを宣言していない client に対して、tool 使用を伴う sampling request を送ってはなりません (MUST NOT)。

Capabilities

sampling をサポートする client は、初期化時に sampling capability を宣言しなければなりません (MUST)。

Basic sampling:

{
  "capabilities": {
    "sampling": {}
  }
}

With tool use support:

{
  "capabilities": {
    "sampling": {
      "tools": {}
    }
  }
}

With context inclusion support (soft-deprecated):

{
  "capabilities": {
    "sampling": {
      "context": {}
    }
  }
}

includeContext パラメータ値 "thisServer""allServers" は soft-deprecated です。server はこれらの値の使用を避けるべきです (SHOULD)(たとえば includeContext はデフォルトで "none" なので省略できます)。また、client が sampling.context capability を宣言していない限り、server はこれらの値を使用すべきではありません (SHOULD NOT)。これらの値は、将来の spec リリースで削除される可能性があります。

Protocol Messages

Creating Messages

language model による生成を request するために、server は sampling/createMessage request を送信します。

Request:

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "sampling/createMessage",
  "params": {
    "messages": [
      {
        "role": "user",
        "content": {
          "type": "text",
          "text": "What is the capital of France?"
        }
      }
    ],
    "modelPreferences": {
      "hints": [
        {
          "name": "claude-3-sonnet"
        }
      ],
      "intelligencePriority": 0.8,
      "speedPriority": 0.5
    },
    "systemPrompt": "You are a helpful assistant.",
    "maxTokens": 100
  }
}

Response:

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "role": "assistant",
    "content": {
      "type": "text",
      "text": "The capital of France is Paris."
    },
    "model": "claude-3-sonnet-20240307",
    "stopReason": "endTurn"
  }
}

Sampling with Tools

次の図は、複数ターンの tool loop を含む、tool 使用あり sampling の完全なフローを示しています。

sequenceDiagram participant Server participant Client participant User participant LLM Note over Server,Client: Initial request with tools Server->>Client: sampling/createMessage<br/>(messages + tools) Note over Client,User: Human-in-the-loop review Client->>User: Present request for approval User-->>Client: Approve/modify Client->>LLM: Forward request with tools LLM-->>Client: Response with tool_use<br/>(stopReason: "toolUse") Client->>User: Present tool calls for review User-->>Client: Approve tool calls Client-->>Server: Return tool_use response Note over Server: Execute tool(s) Server->>Server: Run get_weather("Paris")<br/>Run get_weather("London") Note over Server,Client: Continue with tool results Server->>Client: sampling/createMessage<br/>(history + tool_results + tools) Client->>User: Present continuation User-->>Client: Approve Client->>LLM: Forward with tool results LLM-->>Client: Final text response<br/>(stopReason: "endTurn") Client->>User: Present response User-->>Client: Approve Client-->>Server: Return final response Note over Server: Server processes result<br/>(may continue conversation...)

tool use capability を伴う LLM 生成を request するために、server は request に tools と、任意で toolChoice を含めます。

Request (Server -> Client):

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "sampling/createMessage",
  "params": {
    "messages": [
      {
        "role": "user",
        "content": {
          "type": "text",
          "text": "What's the weather like in Paris and London?"
        }
      }
    ],
    "tools": [
      {
        "name": "get_weather",
        "description": "Get current weather for a city",
        "inputSchema": {
          "type": "object",
          "properties": {
            "city": {
              "type": "string",
              "description": "City name"
            }
          },
          "required": ["city"]
        }
      }
    ],
    "toolChoice": {
      "mode": "auto"
    },
    "maxTokens": 1000
  }
}

Response (Client -> Server):

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "role": "assistant",
    "content": [
      {
        "type": "tool_use",
        "id": "call_abc123",
        "name": "get_weather",
        "input": {
          "city": "Paris"
        }
      },
      {
        "type": "tool_use",
        "id": "call_def456",
        "name": "get_weather",
        "input": {
          "city": "London"
        }
      }
    ],
    "model": "claude-3-sonnet-20240307",
    "stopReason": "toolUse"
  }
}

Multi-turn Tool Loop

LLM から tool use request を受け取った後、server は通常次のように動作します。

  1. 要求された tool use を実行する
  2. tool result を追加した新しい sampling request を送信する
  3. LLM の response を受け取る(新たな tool use を含むこともある)
  4. 必要な回数だけこれを繰り返す(server は最大反復回数に上限を設けてもよく、たとえば最終反復では toolChoice: {mode: "none"} を渡して最終結果を強制してもよい)

Follow-up request (Server -> Client) with tool results:

{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "sampling/createMessage",
  "params": {
    "messages": [
      {
        "role": "user",
        "content": {
          "type": "text",
          "text": "What's the weather like in Paris and London?"
        }
      },
      {
        "role": "assistant",
        "content": [
          {
            "type": "tool_use",
            "id": "call_abc123",
            "name": "get_weather",
            "input": { "city": "Paris" }
          },
          {
            "type": "tool_use",
            "id": "call_def456",
            "name": "get_weather",
            "input": { "city": "London" }
          }
        ]
      },
      {
        "role": "user",
        "content": [
          {
            "type": "tool_result",
            "toolUseId": "call_abc123",
            "content": [
              {
                "type": "text",
                "text": "Weather in Paris: 18°C, partly cloudy"
              }
            ]
          },
          {
            "type": "tool_result",
            "toolUseId": "call_def456",
            "content": [
              {
                "type": "text",
                "text": "Weather in London: 15°C, rainy"
              }
            ]
          }
        ]
      }
    ],
    "tools": [
      {
        "name": "get_weather",
        "description": "Get current weather for a city",
        "inputSchema": {
          "type": "object",
          "properties": {
            "city": { "type": "string" }
          },
          "required": ["city"]
        }
      }
    ],
    "maxTokens": 1000
  }
}

Final response (Client -> Server):

{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "role": "assistant",
    "content": {
      "type": "text",
      "text": "Based on the current weather data:\n\n- **Paris**: 18°C and partly cloudy - quite pleasant!\n- **London**: 15°C and rainy - you'll want an umbrella.\n\nParis has slightly warmer and drier conditions today."
    },
    "model": "claude-3-sonnet-20240307",
    "stopReason": "endTurn"
  }
}

Message Content Constraints

Tool Result Messages

ユーザーメッセージに tool result(type: "tool_result")が含まれる場合、そのメッセージは tool result のみを含まなければなりません (MUST)。同じメッセージの中で、tool result と他の content type(text、image、audio)を混在させることはできません。

この制約により、tool result のために専用の role を使う provider API(たとえば OpenAI の "tool" role や Gemini の "function" role)との互換性が確保されます。

Valid - single tool result:

{
  "role": "user",
  "content": {
    "type": "tool_result",
    "toolUseId": "call_123",
    "content": [{ "type": "text", "text": "Result data" }]
  }
}

Valid - multiple tool results:

{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "toolUseId": "call_123",
      "content": [{ "type": "text", "text": "Result 1" }]
    },
    {
      "type": "tool_result",
      "toolUseId": "call_456",
      "content": [{ "type": "text", "text": "Result 2" }]
    }
  ]
}

Invalid - mixed content:

{
  "role": "user",
  "content": [
    {
      "type": "text",
      "text": "Here are the results:"
    },
    {
      "type": "tool_result",
      "toolUseId": "call_123",
      "content": [{ "type": "text", "text": "Result data" }]
    }
  ]
}

Tool Use and Result Balance

sampling で tool use を使う場合、ToolUseContent block を含むすべての assistant message は、ほかの message が来る前に、必ず ToolResultContent block のみから成る user message によって続かなければなりません (MUST)。また、それぞれの tool use(たとえば id: $id)には、対応する tool result(toolUseId: $id)が一致する形で存在しなければなりません (MUST)。

この要件により、次が保証されます。

  • 会話が続く前に、tool use が常に解決される
  • provider API が複数の tool use を並行処理し、その結果を並列に取得できる
  • 会話が一貫した request-response パターンを維持する

Example valid sequence:

  1. User message: "What's the weather like in Paris and London?"
  2. Assistant message: ToolUseContent (id: "call_abc123", name: "get_weather", input: {city: "Paris"}) + ToolUseContent (id: "call_def456", name: "get_weather", input: {city: "London"})
  3. User message: ToolResultContent (toolUseId: "call_abc123", content: "18°C, partly cloudy") + ToolResultContent (toolUseId: "call_def456", content: "15°C, rainy")
  4. Assistant message: 両都市の天気を比較する text response

Invalid sequence - missing tool result:

  1. User message: "What's the weather like in Paris and London?"
  2. Assistant message: ToolUseContent (id: "call_abc123", name: "get_weather", input: {city: "Paris"}) + ToolUseContent (id: "call_def456", name: "get_weather", input: {city: "London"})
  3. User message: ToolResultContent (toolUseId: "call_abc123", content: "18°C, partly cloudy") ← call_def456 の結果が欠けている
  4. Assistant message: Text response(無効。すべての tool use が解決されていない)

Cross-API Compatibility

sampling specification は、複数の LLM provider API(Claude、OpenAI、Gemini など)をまたいで動作するように設計されています。互換性のための主な設計判断は次のとおりです。

Message Roles

MCP は 2 つの role を使います: "user""assistant"

tool use request は "assistant" role を持つ CreateMessageResult で送られます。 tool result は "user" role を持つ message として返送されます。 tool result を含む message は、ほかの種類の content を含めることはできません。

Tool Choice Modes

CreateMessageRequest.params.toolChoice は、model の tool use 可否を制御します。

  • {mode: "auto"}: model が tool を使うかどうかを決める(デフォルト)
  • {mode: "required"}: model は完了前に少なくとも 1 つの tool を使わなければならない
  • {mode: "none"}: model はいかなる tool も使ってはならない

Parallel Tool Use

MCP では、model が複数の tool use request を並列に行うことができます(ToolUseContent の配列を返す)。主要な provider API はすべてこれをサポートしています。

  • Claude: 並列 tool use をネイティブにサポートする
  • OpenAI: 並列 tool call をサポートする(parallel_tool_calls: false で無効化可能)
  • Gemini: 並列 function call をネイティブにサポートする

並列 tool use を無効化できる provider をラップする実装は、この機能を拡張として公開しても構いませんが、それは MCP core specification の一部ではありません (MAY)。

Message Flow

sequenceDiagram participant Server participant Client participant User participant LLM Note over Server,Client: Server initiates sampling Server->>Client: sampling/createMessage Note over Client,User: Human-in-the-loop review Client->>User: Present request for approval User-->>Client: Review and approve/modify Note over Client,LLM: Model interaction Client->>LLM: Forward approved request LLM-->>Client: Return generation Note over Client,User: Response review Client->>User: Present response for approval User-->>Client: Review and approve/modify Note over Server,Client: Complete request Client-->>Server: Return approved response

Data Types

Messages

sampling message には次のものを含められます。

Text Content

{
  "type": "text",
  "text": "The message content"
}

Image Content

{
  "type": "image",
  "data": "base64-encoded-image-data",
  "mimeType": "image/jpeg"
}

Audio Content

{
  "type": "audio",
  "data": "base64-encoded-audio-data",
  "mimeType": "audio/wav"
}

Model Preferences

MCP における model 選択では、server と client が異なる AI provider と異なる model 提供を使う可能性があるため、慎重な抽象化が必要です。server は単に特定の model 名を request することはできません。なぜなら、client がその正確な model にアクセスできない可能性があり、あるいは別 provider の同等 model を使いたいかもしれないからです。

これを解決するために、MCP は、抽象的な capability の優先度と任意の model hint を組み合わせた preference system を実装しています。

Capability Priorities

server は 0〜1 に正規化された 3 つの priority 値を使って要件を表現します。

  • costPriority: コスト最小化がどれほど重要か。値が高いほど、より安価な model を優先する
  • speedPriority: 低レイテンシがどれほど重要か。値が高いほど、より高速な model を優先する
  • intelligencePriority: 高度な能力がどれほど重要か。値が高いほど、より高性能な model を優先する

Model Hints

priority は特性に基づいて model を選ぶ助けになりますが、hints により server は特定の model や model family を提案できます。

  • hint は、柔軟に model 名へ一致できる部分文字列として扱われる
  • 複数の hint は優先順に評価される
  • client は、hint を別 provider の同等 model にマッピングしてもよい
  • hint は助言的なものであり、最終的な model 選択は client が行う

たとえば:

{
  "hints": [
    { "name": "claude-3-sonnet" }, // Sonnet-class model を優先
    { "name": "claude" } // どの Claude model でもよいので次候補
  ],
  "costPriority": 0.3, // コストはそれほど重要ではない
  "speedPriority": 0.8, // 速度は非常に重要
  "intelligencePriority": 0.5 // 能力要件は中程度
}

client は、これらの preference を処理して、自身が利用可能な選択肢の中から適切な model を選びます。たとえば client が Claude model にはアクセスできないが Gemini を使える場合、同等の能力に基づいて sonnet hint を gemini-1.5-pro にマッピングするかもしれません。

Error Handling

client は、一般的な失敗ケースに対して error を返すべきです (SHOULD)。

  • ユーザーが sampling request を拒否した: -1
  • request に tool result が欠けている: -32602(Invalid params)
  • tool result がほかの content と混在している: -32602(Invalid params)

error の例:

{
  "jsonrpc": "2.0",
  "id": 3,
  "error": {
    "code": -1,
    "message": "User rejected sampling request"
  }
}
{
  "jsonrpc": "2.0",
  "id": 4,
  "error": {
    "code": -32602,
    "message": "Tool result missing in request"
  }
}

Security Considerations

  1. client は、ユーザー承認コントロールを実装すべきである (SHOULD)
  2. 双方は、message content を検証すべきである (SHOULD)
  3. client は、model preference hint を尊重すべきである (SHOULD)
  4. client は、rate limiting を実装すべきである (SHOULD)
  5. 双方は、機密データを適切に扱わなければならない

sampling で tool が使われる場合、追加の security consideration が適用されます。

  1. server は、stopReason: "toolUse" に応答する際、各 ToolUseContent item に対して、一致する toolUseId を持つ ToolResultContent item で応答し、かつその user message が tool result のみを含むことを保証しなければならない
  2. 双方は、tool loop に対する反復上限を実装すべきである (SHOULD)