构建消息并调用 LLM
现在您已经创建了 get_context_from_mcp(user_query) 辅助函数用于返回资源文本和提示文本,是时候把这些信息传给 LLM 了!
货币服务器、get_context_from_mcp()、get_tools_from_mcp()、call_mcp_tool() 以及 Claude 客户端都已在后台设置完成。您需要完成用于构建提示、调用模型,并处理直接消息或工具调用的函数。我们为您提供了含糊与不含糊的两种用户输入,以检验您的 MCP 提示是否带来了差异!
本练习是课程的一部分
Model Context Protocol (MCP) 入门
练习说明
- 在第 37 行,通过拼接
prompt_text、字符串"\n\nSupported currencies:\n",以及resource_text来构建full_prompt。 - 在第 47 行,将
full_prompt(作为用户消息内容)和anthropic_tools列表一起发送给模型。 - 在第 52-55 行,如果响应的
stop_reason为"end_turn",返回str(text)。 - 在第 58-60 行,如果响应的
stop_reason为"tool_use",将工具使用块的.name和.input传递给call_mcp_tool()。
交互式实操练习
通过完成这段示例代码来试试这个练习。
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def get_context_from_mcp(user_query: str) -> tuple[str, str]:
params = StdioServerParameters(command=sys.executable, args=["currency_server.py"])
async with stdio_client(params) as (reader, writer):
async with ClientSession(reader, writer) as session:
await session.initialize()
resource_result = await session.read_resource("file://currencies.txt")
resource_text = resource_result.contents[0].text
prompt_result = await session.get_prompt("convert_currency_prompt",
arguments={"currency_request": user_query})
prompt_text = prompt_result.messages[0].content.text
return resource_text, prompt_text
async def get_tools_from_mcp():
params = StdioServerParameters(command=sys.executable, args=["currency_server.py"])
async with stdio_client(params) as (reader, writer):
async with ClientSession(reader, writer) as session:
await session.initialize()
response = await session.list_tools()
return response.tools
async def call_mcp_tool(tool_name: str, arguments: dict) -> str:
params = StdioServerParameters(command=sys.executable, args=["currency_server.py"])
async with stdio_client(params) as (reader, writer):
async with ClientSession(reader, writer) as session:
await session.initialize()
result = await session.call_tool(tool_name, arguments)
return str(result.content[0].text)
async def call_llm_with_context(user_query: str):
"""Call the LLM with resource and prompt context from MCP."""
resource_text, prompt_text = await get_context_from_mcp(user_query)
# Combine the resource and prompt text
full_prompt = ____ + "\n\nSupported currencies:\n" + ____
client = AsyncAnthropic(api_key="")
mcp_tools = await get_tools_from_mcp()
anthropic_tools = [{"name": t.name, "description": t.description or "", "input_schema": t.inputSchema} for t in mcp_tools]
# Send full_prompt (as a user message) and the tools list to the model
response = await client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": ____}],
tools=anthropic_tools,
)
# Return the text response
if response.stop_reason == "____":
text = next((block.text for block in response.content if block.type == "text"), "")
print(f"\nAssistant: {text}")
return str(____)
# Call the tool requested in the LLM's tool use
if response.stop_reason == "____":
tool_use = next(block for block in response.content if block.type == "tool_use")
result = await call_mcp_tool(____.name, ____)
followup = await client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": full_prompt},
{"role": "assistant", "content": response.content},
{"role": "user", "content": [{"type": "tool_result", "tool_use_id": tool_use.id, "content": result}]},
],
tools=anthropic_tools,
)
final_text = next((block.text for block in followup.content if block.type == "text"), None)
if final_text:
print(f"\nAssistant: {final_text}")
return str(final_text)
print("=== Ambiguous request (prompt asks for clarification) ===")
asyncio.run(call_llm_with_context("Convert some euros to dollars"))
print("\n=== Unambiguous request (model calls tool) ===")
asyncio.run(call_llm_with_context("How much is 50 GBP in euros?"))