MCP 服务器中的提示(Prompts)

Model Context Protocol (MCP) 入门

James Chapman

AI Curriculum Manager, DataCamp

什么是 MCP 提示?

 

Prompts(提示):可复用模板,用于让 LLM 针对特定任务表现最佳

  • 工作流与行为
  • 减少用户的提示负担

提示示意图

Model Context Protocol (MCP) 入门

为何需要提示

含糊输入示例

Model Context Protocol (MCP) 入门

时区转换器提示

You are a timezone conversion engine.

Your task is to:
1. Extract the source datetime from the user's natural language input.
2. Identify the source timezone (explicit or inferred).
3. Convert the datetime into the target timezone.

Rules:
- If the date is ambiguous (e.g., "next Friday"), resolve it relative to the provided datetime.
- If the input cannot be resolved confidently, seek clarification.

→ 将此提示用于时区转换任务

Model Context Protocol (MCP) 入门

定义 MCP 服务器提示

@mcp.prompt(title="Timezone Conversion")

def convert_timezone_prompt(user_input: str) -> str:
return f"""You are a timezone conversion engine. Your task is to: 1. Extract the source datetime... Rules: - If the date is ambiguous (e.g., "next Friday"), resolve it relative to the provided datetime. - If the input cannot be resolved confidently, seek clarification. User's timezone conversion request: {user_input}"""
Model Context Protocol (MCP) 入门

本地 MCP 服务器:timezone_server.py

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Timezone Converter")

# Tools and resources from before...

@mcp.prompt(title="Timezone Conversion")
def convert_timezone_prompt(timezone_request: str) -> str:
    # ...

if __name__ == "__main__":
    mcp.run(transport="stdio")
Model Context Protocol (MCP) 入门

客户端:列出提示

async def list_prompts():
    """列出 MCP 服务器上所有可用的提示。"""
    params = StdioServerParameters(command=sys.executable, args=["timezone_server.py"])

    async with stdio_client(params) as (reader, writer):
        async with ClientSession(reader, writer) as session:
            await session.initialize()

# 列出可用的提示 prompts = await session.list_prompts() print(f"Available prompts: {[p.name for p in prompts.prompts]}")
Model Context Protocol (MCP) 入门

客户端:列出提示

print(asyncio.run(list_prompts()))
Available prompts: ['convert_timezone_prompt']

提示的 nametitle 不同

@mcp.prompt(title="Timezone Conversion")
def convert_timezone_prompt(timezone_request: str) -> str:
    # ...
Model Context Protocol (MCP) 入门

客户端:列出提示

print(asyncio.run(list_prompts()))
Available prompts: ['convert_timezone_prompt']

提示的 nametitle 不同

# 列出可用的提示
prompts = await session.list_prompts()
print(f"Available prompts: {[p.name for p in prompts.prompts]}")
  • 在客户端中使用 .name 属性(不是 .title
Model Context Protocol (MCP) 入门

客户端:获取提示

async def read_prompt(user_input: str, prompt_name: str = "convert_timezone_prompt") -> str:
    """从 MCP 服务器获取带用户输入的提示。"""
    params = StdioServerParameters(command=sys.executable, args=["timezone_server.py"])

    async with stdio_client(params) as (reader, writer):
        async with ClientSession(reader, writer) as session:
            await session.initialize()

            prompts = await session.list_prompts()

# 获取指定提示 if prompts.prompts: prompt = await session.get_prompt(prompt_name, arguments={"timezone_request": user_input})
print(f"Prompt result: {prompt.messages[0].content.text}") return prompt.messages[0].content.text
Model Context Protocol (MCP) 入门
print(asyncio.run(read_prompt(user_input="It is 9:50 AM in the UK in January. What time is
    it in Lisbon, Portugal?")))
You are a timezone conversion engine.

Your task is to:
1. Extract the source datetime from the user's natural language input.
2. Identify the source timezone (explicit or inferred).
3. Convert the datetime into the target timezone.

Rules:
- If the date is ambiguous (e.g., "next Friday"), resolve it relative to the...
- If the input cannot be resolved confidently, seek clarification.

User's timezone conversion request: It is 9:50 AM in the UK in January. What time is it in
Lisbon, Portugal?
Model Context Protocol (MCP) 入门

Passons à la pratique !

Model Context Protocol (MCP) 入门

Preparing Video For Download...