在 MCP 服务器中定义 Prompt
您正在为货币转换 MCP 服务器添加一个可复用的提示,让 LLM 知道如何处理转换请求,以及在何时需要澄清(例如缺少金额或货币代码)。这可以减少用户的提示负担,并让助手更可靠。
一个 MCP 服务器实例已经创建。请使用 @mcp.prompt() 装饰器添加一个提示,并编写返回提示模板且附加用户请求的函数。
本练习是课程的一部分
Model Context Protocol (MCP) 入门
练习说明
- 使用
@mcp.prompt()装饰一个函数,并将标题设置为"Currency Conversion"。 - 定义一个函数,接收
currency_request: str,返回包含提示模板与用户请求的字符串。 - 使用一个示例请求调用该提示函数,并打印结果以验证其工作正常。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Define a prompt for currency conversion
____
def ____(currency_request: str) -> str:
return f"""You are a currency conversion assistant.
Your task is to:
1. Extract the amount and source currency from the user's natural language input.
2. Identify the target currency.
3. Use the conversion tool to convert the amount.
Rules:
- If the amount or currencies are ambiguous or missing, ask the user for clarification.
- Use only supported currency codes (e.g., USD, EUR, GBP).
User's currency conversion request: {currency_request}"""
# Test the prompt function
print(____("100 USD to EUR"))