采样

社区译文;来源: MCP 80041ab0

已弃用:采样功能自协议版本 2026-07-28 起已弃用 (SEP-2577 )。 根据功能生命周期策略(英文) ,该功能在本次修订发布后 至少十二个月内仍会保留在规范中,之后才可能被移除。新实现 SHOULD NOT 采用此功能;现有实现 SHOULD 迁移为直接集成 LLM 提供商 API。 参见弃用功能登记表 。

模型上下文协议(MCP)为服务器通过客户端向语言模型请求 LLM 采样(“补全”或“生成”) 提供了一种标准方式。此流程让客户端能够控制模型访问、选择和权限,同时使服务器无需 服务器 API 密钥即可利用 AI 能力。服务器可以请求基于文本、音频或图像的交互,并可选择 在提示词中包含来自 MCP 服务器的上下文。

用户交互模型

MCP 中的采样允许在其他 MCP 服务器功能内部_嵌套_发起 LLM 调用,从而让服务器实现 智能体行为。

实现可以自由采用符合自身需求的任何界面模式来公开采样;协议本身不规定具体的用户 交互模型。

出于信任、安全与防护考虑,采样流程始终 SHOULD 有人参与,并能够拒绝采样请求。

应用程序 SHOULD:

  • 提供便于直观审查采样请求的 UI
  • 允许用户在发送前查看和编辑提示词
  • 在交付前展示生成的响应供用户审查

采样中的工具

服务器可以在采样请求中提供 tools 数组以及可选的 toolChoice 配置,请求客户端的 LLM 在采样期间使用工具。tools 数组中的工具定义仅适用于该次采样请求,不必对应已注册 的工具。这样,服务器可以实现智能体行为:LLM 调用专门指定的工具、接收结果并继续对话, 整个过程都在一次采样请求流程内完成。

客户端要接收启用工具的采样请求,MUST 通过 sampling.tools 能力声明支持工具使用。 服务器 MUST NOT 向未通过 sampling.tools 能力声明支持工具使用的客户端发送启用工具 的采样请求。

能力

支持采样的客户端 MUST 在每个请求的 _meta.io.modelcontextprotocol/clientCapabilities 中声明 sampling 能力:

基础采样:

{
  "_meta": {
    "io.modelcontextprotocol/clientCapabilities": {
      "sampling": {}
    }
  }
}

支持工具使用:

{
  "_meta": {
    "io.modelcontextprotocol/clientCapabilities": {
      "sampling": {
        "tools": {}
      }
    }
  }
}

支持包含上下文(已弃用):

{
  "_meta": {
    "io.modelcontextprotocol/clientCapabilities": {
      "sampling": {
        "context": {}
      }
    }
  }
}
includeContext 参数值 "thisServer" 和 "allServers" 已根据 功能生命周期策略(英文) (SEP-2596 )弃用; 它们最迟会随采样功能一同移除。服务器 SHOULD 避免使用这些值(例如可以直接省略 includeContext,因为其默认值为 "none"),并且除非客户端声明了 sampling.context 能力,否则 SHOULD NOT 使用这些值。参见 弃用功能登记表 。

协议消息

创建消息

为了在处理客户端请求期间请求语言模型生成,服务器发送一个包含 sampling/createMessage 请求的 InputRequiredResult:

输入请求(在 InputRequiredResult.inputRequests 中传递):

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

客户端结果(在重试请求的 inputResponses 中返回):

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

使用工具进行采样

下图展示了使用工具进行采样的完整流程,包括多轮工具循环:

  sequenceDiagram
    participant Server
    participant Client
    participant User
    participant LLM

    Client->>Server: tools/call(id:1)
    note right of Server: Server needs more info
    Server->>Client: InputRequiredResult(<br/>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: tools/call(id:2, 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: InputRequiredResult(<br/>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: tools/call(id:3, Return final response)

    Note over Server: Server processes result<br/>(may continue conversation...)

要请求具备工具使用能力的 LLM 生成,服务器在请求中包含 tools,并可选择包含 toolChoice:

输入请求(服务器 -> 客户端,在 InputRequiredResult.inputRequests 中传递):

{
  "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
  }
}

客户端结果(客户端 -> 服务器,在重试请求的 inputResponses 中返回):

{
  "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"
}

多轮工具循环

收到 LLM 的工具使用请求后,服务器通常会:

  1. 执行请求的工具调用。
  2. 将工具结果追加到消息中,发送新的采样请求
  3. 接收 LLM 的响应(其中可能包含新的工具调用)
  4. 根据需要重复以上步骤(服务器可以限制最大迭代次数,例如在最后一次迭代中传入 toolChoice: {mode: "none"} 以强制获得最终结果)

包含工具结果的后续输入请求(服务器 -> 客户端,在 InputRequiredResult.inputRequests 中传递):

{
  "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
  }
}

最终客户端结果(客户端 -> 服务器,在重试请求的 inputResponses 中返回):

{
  "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"
}

消息内容约束

工具结果消息

当用户消息包含工具结果(类型为 "tool_result")时,该消息 MUST 仅包含工具结果。 不允许在同一消息中混合工具结果与其他内容类型(文本、图像、音频)。

此约束确保与使用专用角色承载工具结果的提供商 API 兼容(例如 OpenAI 的 "tool" 角色、Gemini 的 "function" 角色)。

有效 - 单个工具结果:

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

有效 - 多个工具结果:

{
  "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" }]
    }
  ]
}

无效 - 混合内容:

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

工具使用与结果的平衡

在采样中使用工具时,每条包含 ToolUseContent 块的 assistant 消息 MUST 紧接一条 完全由 ToolResultContent 块组成的 user 消息,并且每次工具使用(例如 id: $id)都要有 对应的工具结果(toolUseId: $id),之后才能出现任何其他消息。

此要求确保:

  • 对话继续前,所有工具使用都已得到处理
  • 提供商 API 可以并发处理多次工具使用,并行获取结果
  • 对话保持一致的请求-响应模式

有效序列示例:

  1. 用户消息:“What’s the weather like in Paris and London?”
  2. Assistant 消息:ToolUseContent(id: "call_abc123", name: "get_weather", input: {city: "Paris"})+ ToolUseContent(id: "call_def456", name: "get_weather", input: {city: "London"})
  3. 用户消息:ToolResultContent(toolUseId: "call_abc123", content: "18°C, partly cloudy")+ ToolResultContent(toolUseId: "call_def456", content: "15°C, rainy")
  4. Assistant 消息:比较两个城市天气的文本响应

无效序列 - 缺少工具结果:

  1. 用户消息:“What’s the weather like in Paris and London?”
  2. Assistant 消息:ToolUseContent(id: "call_abc123", name: "get_weather", input: {city: "Paris"})+ ToolUseContent(id: "call_def456", name: "get_weather", input: {city: "London"})
  3. 用户消息:ToolResultContent(toolUseId: "call_abc123", content: "18°C, partly cloudy")← 缺少 call_def456 的结果
  4. Assistant 消息:文本响应(无效,因为并非所有工具使用都已得到处理)

跨 API 兼容性

采样规范旨在兼容多个 LLM 提供商 API(Claude、OpenAI、Gemini 等)。主要兼容性 设计决策如下:

消息角色

MCP 使用两个角色:"user" 和 "assistant"。

工具使用请求通过 CreateMessageResult 以 "assistant" 角色发送。 工具结果在消息中以 "user" 角色发回。 包含工具结果的消息不能包含其他类型的内容。

工具选择模式

CreateMessageRequest.params.toolChoice 控制模型的工具使用能力:

  • {mode: "auto"}:由模型决定是否使用工具(默认)
  • {mode: "required"}:模型完成前 MUST 至少使用一个工具
  • {mode: "none"}:模型 MUST NOT 使用任何工具

并行工具使用

MCP 允许模型并行发出多个工具使用请求(返回 ToolUseContent 数组)。所有主要提供商 API 都支持此功能:

  • Claude:原生支持并行工具使用
  • OpenAI:支持并行工具调用(可通过 parallel_tool_calls: false 禁用)
  • Gemini:原生支持并行函数调用

封装了支持禁用并行工具使用的提供商的实现 MAY 将其作为扩展公开,但这不属于 MCP 核心规范。

消息流

  sequenceDiagram
    participant Server
    participant Client
    participant User
    participant LLM

    Client->>Server: tools/call(id:1)
    note right of Server: Server needs more info
    Server->>Client: InputRequiredResult(<br/>sampling/createMessage<br/>(messages + tools))

    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: Replay Request with approved response
    Client-->>Server: tools/call(id:3, Return approved response)

数据类型

消息

采样消息 MUST 包含值为 "user" 或 "assistant" 的 role 字段,以及表示消息数据 的 content 字段。

单独的采样请求之间 SHOULD NOT 保留消息列表。

content 字段可以包含:

文本内容

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

图像内容

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

音频内容

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

模型偏好

MCP 中的模型选择需要谨慎抽象,因为服务器和客户端可能使用不同的 AI 提供商,而各 提供商提供的模型也不相同。服务器不能简单地按名称请求特定模型,因为客户端可能无法 访问该模型,或者更倾向于使用其他提供商的同等模型。

为解决此问题,MCP 实现了一套偏好系统,将抽象能力优先级与可选的模型提示结合起来:

能力优先级

服务器通过三个归一化优先级值(0-1)表达需求:

  • costPriority:降低成本有多重要?值越高,越偏向较便宜的模型。
  • speedPriority:低延迟有多重要?值越高,越偏向较快的模型。
  • intelligencePriority:高级能力有多重要?值越高,越偏向能力更强的模型。

模型提示

优先级有助于根据特征选择模型,而 hints 允许服务器建议特定模型或模型系列:

  • 提示被视为子字符串,可以灵活匹配模型名称
  • 多个提示按偏好顺序依次评估
  • 客户端 MAY 将提示映射到不同提供商的同等模型
  • 提示仅供参考,最终模型选择由客户端决定

例如:

{
  "hints": [
    { "name": "claude-3-sonnet" }, // Prefer Sonnet-class models
    { "name": "claude" } // Fall back to any Claude model
  ],
  "costPriority": 0.3, // Cost is less important
  "speedPriority": 0.8, // Speed is very important
  "intelligencePriority": 0.5 // Moderate capability needs
}

客户端处理这些偏好,从其可用选项中选择适当的模型。例如,如果客户端无法访问 Claude 模型但可以访问 Gemini,它可能根据相近能力将 sonnet 提示映射到 gemini-1.5-pro。

系统提示词

可选的 systemPrompt 字段允许服务器请求特定的系统提示词。 客户端 MAY 修改或忽略此字段,而不必告知服务器。

包含上下文

includeContext 参数指定客户端预期在响应中包含哪些上下文信息:

  • "none":不包含额外上下文。
  • "thisServer":包含来自发起请求的服务器的上下文。
  • "allServers":包含来自所有已连接 MCP 服务器的上下文。

"thisServer" 和 "allServers" 值已弃用;参见能力 。

客户端 MAY 修改或忽略此字段,而不必告知服务器。例如,客户端可能判断在特定请求中 遵从此字段会导致向服务器共享敏感信息,并据此限制其响应。

采样参数

可以使用以下参数微调 LLM 采样:

  • temperature:控制模型响应的随机性。值越高,随机性越强;值越低,输出越稳定。 有效范围取决于模型提供商。
  • maxTokens:要生成的最大 token 数;必填。
  • stopSequences:停止生成的序列数组。
  • metadata:其他提供商专用参数。

客户端 MUST 遵守 maxTokens 参数。

客户端 MAY 修改或忽略 temperature、stopSequences 和 metadata。例如,客户端 可能使用不支持其中一个或多个参数的模型,因此无法利用这些参数。

结果字段

采样结果包含以下字段:

  • role:消息角色;参见消息 。

  • content:消息内容。它可以是:

    • 当响应仅包含一个内容块时,为单个内容块,例如单个文本响应。
    • 当响应包含一个或多个内容块时,为内容块数组,例如多个工具使用或混合内容。

    有关内容块类型,参见消息 。

  • model:生成消息的模型名称。

  • stopReason:采样停止的原因(如果已知)。规范定义了以下非穷举的停止原因,不过实现 MAY 提供任意自定义值:

    • "endTurn":参与方将对话交给另一方。
    • "stopSequence":消息生成遇到请求的某个 stopSequences。
    • "maxTokens":已达到 token 限制。
    • "toolUse":模型希望使用一个或多个工具。

错误处理

如果发生错误或用户拒绝采样请求,客户端无需携带错误消息重放初始调用,因为采用 InputRequiredResult 模式时,服务器并未等待响应。

安全注意事项

  1. 客户端 SHOULD 实施用户审批控制
  2. 双方 SHOULD 验证消息内容
  3. 客户端 SHOULD 尊重模型偏好提示
  4. 客户端 SHOULD 实施速率限制
  5. 双方 MUST 妥善处理敏感数据

在采样中使用工具时,还需考虑以下安全事项:

  1. 服务器 MUST 确保在回复 stopReason: "toolUse" 时,每个 ToolUseContent 项都由 一个具有匹配 toolUseId 的 ToolResultContent 项响应,并且用户消息仅包含工具结果 (不含其他内容类型)
  2. 双方 SHOULD 为工具循环实施迭代次数限制