33_FastMCP 2.x 中文文档之FastMCP客户端核心业务:提示模板详解
一、提示
使用服务器端提示模板,支持自动参数序列化。
新版本:2.0.0 功能
提示是 MCP 服务器公开的可重用消息模板。它们可以接受参数,为 LLM 交互生成个性化的消息序列。
1.1 列出提示
使用 list_prompts() 检索所有可用的提示模板:
async with client:prompts = await client.list_prompts()# prompts -> list[mcp.types.Prompt]for prompt in prompts:print(f"提示: {prompt.name}")print(f"描述: {prompt.description}")if prompt.arguments:print(f"参数: {[arg.name for arg in prompt.arguments]}")# 访问标签和其他元数据if hasattr(prompt, '_meta') and prompt._meta:fastmcp_meta = prompt._meta.get('_fastmcp', {})print(f"标签: {fastmcp_meta.get('tags', [])}")
1.2 按标签筛选
新版本:2.11.0 功能
您可以使用 meta 字段根据提示的标签进行筛选:
async with client:prompts = await client.list_prompts()# 按标签筛选提示analysis_prompts = [prompt for prompt in prompts if hasattr(prompt, '_meta') and prompt._meta andprompt._meta.get('_fastmcp', {}) and'analysis' in prompt._meta.get('_fastmcp', {}).get('tags', [])]print(f"找到 {len(analysis_prompts)} 个分析提示")
注意:_meta 字段是标准 MCP 规范的一部分。FastMCP 服务器在 _fastmcp 命名空间(例如 _meta._fastmcp.tags)中包含标签和其他元数据,以避免与用户定义的元数据冲突。此行为可以通过服务器的 include_fastmcp_meta 设置控制 - 当禁用时,不会包含 _fastmcp 命名空间。其他 MCP 服务器实现可能不提供此元数据结构。
二、使用提示
2.1 基本用法
使用 get_prompt() 请求渲染后的提示,提供提示名称和参数:
async with client:# 无参数的简单提示result = await client.get_prompt("welcome_message")# result -> mcp.types.GetPromptResult# 访问生成的消息for message in result.messages:print(f"角色: {message.role}")print(f"内容: {message.content}")
2.2 带参数的提示
传递参数字典来自定义提示:
async with client:# 带简单参数的提示result = await client.get_prompt("user_greeting", {"name": "Alice","role": "administrator"})# 访问个性化消息for message in result.messages:print(f"生成的消息: {message.content}")
三、自动参数序列化
新版本:2.9.0 功能
FastMCP 根据 MCP 规范的要求,自动将复杂参数序列化为 JSON 字符串。这允许您直接传递类型化对象:
from dataclasses import dataclass@dataclass
class UserData:name: strage: intasync with client:# 复杂参数自动序列化result = await client.get_prompt("analyze_user", {"user": UserData(name="Alice", age=30), # 自动序列化为 JSON"preferences": {"theme": "dark"}, # 字典序列化为 JSON 字符串"scores": [85, 92, 78], # 列表序列化为 JSON 字符串"simple_name": "Bob" # 字符串原样传递})
客户端使用 pydantic_core.to_json() 处理序列化以确保格式一致。FastMCP 服务器可以自动将这些 JSON 字符串反序列化回预期的类型。
序列化示例
async with client:result = await client.get_prompt("data_analysis", {# 这些将自动序列化为 JSON 字符串:"config": {"format": "csv","include_headers": True,"delimiter": ","},"filters": [{"field": "age", "operator": ">", "value": 18},{"field": "status", "operator": "==", "value": "active"}],# 这个保持为字符串:"report_title": "月度分析报告"})
四、处理提示结果
get_prompt() 方法返回一个 GetPromptResult 对象,包含消息列表:
async with client:result = await client.get_prompt("conversation_starter", {"topic": "climate"})# 访问单个消息for i, message in enumerate(result.messages):print(f"消息 {i + 1}:")print(f" 角色: {message.role}")print(f" 内容: {message.content.text if hasattr(message.content, 'text') else message.content}")
五、原始 MCP 协议访问
要访问完整的 MCP 协议对象,请使用 *_mcp 方法:
async with client:# 原始 MCP 方法返回完整协议对象prompts_result = await client.list_prompts_mcp()# prompts_result -> mcp.types.ListPromptsResultprompt_result = await client.get_prompt_mcp("example_prompt", {"arg": "value"})# prompt_result -> mcp.types.GetPromptResult
六、多服务器客户端
使用多服务器客户端时,提示可以直接访问(与工具不同):
async with client: # 多服务器客户端# 任何服务器的提示都可以直接访问result1 = await client.get_prompt("weather_prompt", {"city": "London"})result2 = await client.get_prompt("assistant_prompt", {"query": "help"})
七、常见提示模式
7.1 系统消息
许多提示会为 LLM 配置生成系统消息:
async with client:result = await client.get_prompt("system_configuration", {"role": "helpful assistant","expertise": "python programming"})# 通常返回 role="system" 的消息system_message = result.messages[0]print(f"系统提示: {system_message.content}")
7.2 对话模板
提示可以生成多轮对话模板:
async with client:result = await client.get_prompt("interview_template", {"candidate_name": "Alice","position": "Senior Developer"})# 对话流的多个消息for message in result.messages:print(f"{message.role}: {message.content}")
提示:提示参数及其预期类型取决于具体的提示实现。请查看服务器的文档或使用 list_prompts() 查看每个提示的可用参数。
