> ## Documentation Index
> Fetch the complete documentation index at: https://mcp.vyagent.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 采样

> 让你的服务器从 LLM 请求补全

采样（Sampling）是 MCP 的一个强大功能，它允许服务器通过客户端请求 LLM 补全，在保持安全性和隐私性的同时实现复杂的代理行为。

<Info>
  Claude Desktop 客户端目前尚不支持 MCP 的这个功能。
</Info>

## 采样如何工作

采样流程遵循以下步骤：

1. 服务器向客户端发送 `sampling/createMessage` 请求
2. 客户端审查请求并可以修改它
3. 客户端从 LLM 采样
4. 客户端审查补全结果
5. 客户端将结果返回给服务器

这种人在环路（human-in-the-loop）的设计确保用户能够控制 LLM 看到和生成的内容。

## 消息格式

采样请求使用标准化的消息格式：

```typescript
{
  messages: [
    {
      role: "user" | "assistant",
      content: {
        type: "text" | "image",

        // For text:
        text?: string,

        // For images:
        data?: string,             // base64 encoded
        mimeType?: string
      }
    }
  ],
  modelPreferences?: {
    hints?: [{
      name?: string                // Suggested model name/family
    }],
    costPriority?: number,         // 0-1, importance of minimizing cost
    speedPriority?: number,        // 0-1, importance of low latency
    intelligencePriority?: number  // 0-1, importance of capabilities
  },
  systemPrompt?: string,
  includeContext?: "none" | "thisServer" | "allServers",
  temperature?: number,
  maxTokens: number,
  stopSequences?: string[],
  metadata?: Record<string, unknown>
}
```

## 请求参数

### 消息

`messages` 数组包含要发送给 LLM 的对话历史。每条消息都有：

* `role`：可以是 "user" 或 "assistant"
* `content`：消息内容，可以是：
  * 带有 `text` 字段的文本内容
  * 带有 `data`（base64）和 `mimeType` 字段的图像内容

### 模型偏好

`modelPreferences` 对象允许服务器指定其模型选择偏好：

* `hints`：客户端可以用来选择合适模型的模型名称建议数组：
  * `name`：可以匹配完整或部分模型名称的字符串（例如 "claude-3"、"sonnet"）
  * 客户端可以将提示映射到不同提供商的等效模型
  * 多个提示按优先顺序评估

* 优先级值（0-1 标准化）：
  * `costPriority`：最小化成本的重要性
  * `speedPriority`：低延迟响应的重要性
  * `intelligencePriority`：高级模型能力的重要性

客户端根据这些偏好和其可用模型做出最终的模型选择。

### 系统提示

可选的 `systemPrompt` 字段允许服务器请求特定的系统提示。客户端可以修改或忽略这个提示。

### 上下文包含

`includeContext` 参数指定要包含的 MCP 上下文：

* `"none"`：不包含额外上下文
* `"thisServer"`：包含来自请求服务器的上下文
* `"allServers"`：包含来自所有已连接 MCP 服务器的上下文

客户端控制实际包含的上下文。

### 采样参数

微调 LLM 采样的参数：

* `temperature`：控制随机性（0.0 到 1.0）
* `maxTokens`：生成的最大标记数
* `stopSequences`：停止生成的序列数组
* `metadata`：额外的提供商特定参数

## 响应格式

客户端返回补全结果：

```typescript
{
  model: string,  // Name of the model used
  stopReason?: "endTurn" | "stopSequence" | "maxTokens" | string,
  role: "user" | "assistant",
  content: {
    type: "text" | "image",
    text?: string,
    data?: string,
    mimeType?: string
  }
}
```

## 请求示例

这是一个从客户端请求采样的示例：

```json
{
  "method": "sampling/createMessage",
  "params": {
    "messages": [
      {
        "role": "user",
        "content": {
          "type": "text",
          "text": "What files are in the current directory?"
        }
      }
    ],
    "systemPrompt": "You are a helpful file system assistant.",
    "includeContext": "thisServer",
    "maxTokens": 100
  }
}
```

## 最佳实践

在实现采样时：

1. 始终提供清晰、结构良好的提示
2. 适当处理文本和图像内容
3. 设置合理的标记限制
4. 通过 `includeContext` 包含相关上下文
5. 在使用响应前进行验证
6. 优雅地处理错误
7. 考虑采样请求的速率限制
8. 记录预期的采样行为
9. 使用各种模型参数进行测试
10. 监控采样成本

## 人在环路控制

采样的设计考虑到了人工监督：

### 对于提示

* 客户端应该向用户展示建议的提示
* 用户应该能够修改或拒绝提示
* 系统提示可以被过滤或修改
* 上下文包含由客户端控制

### 对于补全

* 客户端应该向用户展示补全结果
* 用户应该能够修改或拒绝补全
* 客户端可以过滤或修改补全
* 用户控制使用哪个模型

## 安全考虑

在实现采样时：

* 验证所有消息内容
* 净化敏感信息
* 实现适当的速率限制
* 监控采样使用情况
* 加密传输中的数据
* 处理用户数据隐私
* 审计采样请求
* 控制成本暴露
* 实现超时机制
* 优雅地处理模型错误

## 常见模式

### 代理工作流

采样支持的代理模式包括：

* 读取和分析资源
* 基于上下文做出决策
* 生成结构化数据
* 处理多步骤任务
* 提供交互式帮助

### 上下文管理

上下文的最佳实践：

* 请求最少必要的上下文
* 清晰地组织上下文
* 处理上下文大小限制
* 根据需要更新上下文
* 清理过期上下文

### 错误处理

健壮的错误处理应该：

* 捕获采样失败
* 处理超时错误
* 管理速率限制
* 验证响应
* 提供回退行为
* 适当记录错误

## 限制

请注意以下限制：

* 采样依赖于客户端能力
* 用户控制采样行为
* 上下文大小有限制
* 可能应用速率限制
* 需要考虑成本
* 模型可用性不同
* 响应时间不同
* 不是所有内容类型都支持
