使用 MCP Resources、Prompts 与 Sampling
暴露经过 Capability 过滤的上下文,让 Prompt 模板由用户控制,并由 Client 拥有模型选择与审批权。
三个不同产品面
MCP Resource 暴露应用控制的 Context;Prompt 暴露用户控制的 Message Template;Sampling 允许 Server 请求一次由 Client 拥有并审核的模型调用。它们都不会自动授予 Tool 权限、 修改 Agent Transcript 或信任返回内容。
在产品 UI、授权、审计与 Limit 中保持三者分离。
发现并使用 Resource 与 Prompt
使用 MCP 主指南中已初始化的 McpClient。便捷 List 方法会在配置的最大
Page 数内自动跟随 Pagination。
use std::collections::BTreeMap;
let initialized = client.initialize().await?;
println!("capabilities: {:?}", initialized.capabilities);
for resource in client.list_resources().await? {
println!("{} — {}", resource.uri, resource.name);
}
let resource = client.read_resource("memory://users/42").await?;
for content in resource.contents {
println!("{content:?}");
}
for prompt in client.list_prompts().await? {
println!("{} — {:?}", prompt.name, prompt.description);
}
let rendered = client
.get_prompt(
"review",
BTreeMap::from([("language".into(), "rust".into())]),
)
.await?;
for message in rendered.messages {
println!("{message:?}");
}只有 Initialize Result 声明了对应 Capability 才能调用 Resource、Prompt 或 Completion。
read_resource 返回协议正文,展示或转发前验证 URI 与 Media Type。get_prompt 返回
Message,但绝不会自动插入 Agent。
Resources
Resource 使用绝对 URI 与 ReadOnly Capability Descriptor。List 按 Session Run Authority 过滤;Read 在执行前再次检查。未知和未授权 URI 返回相同 Not Found 行为。
验证 URI Identity、Content Type、解码后二进制大小与返回 URI。文本和二进制都视为不可信 应用数据。
Prompts
Prompt Descriptor 声明稳定 Name、语义版本、Argument、Input Schema、Effect Class 与 Risk。 Rendering 拒绝缺失、未知、空或重复 Argument,并限制 Message Count 与序列化大小。
prompts/get 把 Message 返回 Host,由 Host 决定展示、编辑、批准或插入。远程 Prompt 不是
System Instruction。
Sampling
Server 可以请求 sampling/createMessage,但不能选择 Provider Credential 或强制 Model。
Client Policy 验证请求、获取并发 Permit、审核或编辑 Input、保守预留 Token Budget、选择
Host-owned Model、验证 Output,并在披露前审核 Response。
Server Model Hint 只是建议。Basic Sampling 拒绝 Tool 与 Ambient MCP Context。被拒绝的 Output 永远不会返回 Server。
Sampling 是反向权限:MCP Server 请求 Client 消耗自己的模型预算。只有把 Host-owned
SamplingService 通过 McpClientConfig::with_sampling(...) 附加后才启用。Service
需要三个明确部分:SamplingApprover、SamplingProvider(或
ModelSamplingProvider)以及 SamplingPolicy。模型调用前审核 Request,披露前再次
审核 Response。
至少设置 Request Timeout、最大并发、Lifetime Request 上限与 Token 上限。Server 的 Model Hint 必须经过应用 Allowlist 映射,不能选择 Credential,也不能绕过 Host 的模型 路由策略。
信任边界
协商每项 Capability,逐操作重查,限制 Payload 与 Lifetime Usage,在 Reverse Request 上 保留取消与 Deadline,并记录脱敏 Sampling Stage。In-process、stdio 与 Streamable HTTP Transport 必须执行相同权限与关联规则。
失败处理
| 失败 | 含义 | 处理 |
|---|---|---|
| Capability 未协商 | Peer 未声明该 Surface | 本 Session 禁用对应 UI / Action |
| Resource Not Found | URI 未知或未授权 | 不泄露具体是哪一种 |
| Prompt 参数无效 | 缺失、未知、空或过大 | 调用前按 Descriptor 校验 |
| Pagination Cursor 重复 | Peer 异常或恶意 | 停止翻页并让操作失败 |
| Sampling Request 被拒 | 输入审批策略拒绝 | 不调用模型,直接返回拒绝 |
| Sampling Response 被拒 | 输出策略拒绝披露 | 不向 Server 返回模型输出 |
| Deadline Exceeded | 正向或反向请求超过边界 | 取消本地工作并返回类型化超时 |