开始使用免费开始使用

在 MCP 服务器中使用 LLM 工具

您已经构建了一个 MCP 服务器,其中包含使用最新汇率进行货币转换的工具。将其与 LLM 集成后,LLM 将能够准确回答有关货币和汇率的问题——这些并非它默认就能做到。

本题的大部分代码已为您提供,重点在于理解工作流而非语法细节。

本练习是课程的一部分

Model Context Protocol (MCP) 入门

查看课程

练习说明

  • 将用户查询(user_query)和已格式化的工具列表(anthropic_tools)发送给 Claude。
  • 使用从工具调用块中提取的名称和参数,调用由 LLM 选择的 MCP 工具。
  • 将结果(result)返回给 Claude,以生成最终回复。

交互式实操练习

通过完成这段示例代码来试试这个练习。

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def call_anthropic_llm(user_query: str):
    """Call Claude with MCP tools."""
    
    print(f"\nUser: {user_query}\n")

    mcp_tools = await get_tools_from_mcp()
    
    anthropic_tools = []
    for tool in mcp_tools:
        anthropic_tool = {
            "name": tool.name,
            "description": tool.description or "",
            "input_schema": tool.inputSchema,
        }
        anthropic_tools.append(anthropic_tool)
    
    # Send the user query and formatted tools to the LLM
    client = AsyncAnthropic(api_key="")

    response = await client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        messages=____,
        tools=____,
    )

    if response.stop_reason == "tool_use":
        tool_use = next(block for block in response.content if block.type == "tool_use")
        name = tool_use.name
        args = tool_use.input

        print(f"Model decided to call: {name}")
        print(f"Arguments: {args}\n")

        # Call the MCP tool
        result = await call_mcp_tool(____, ____)

        # Send the result back to Claude for the final response
        followup = await client.messages.create(
            model="claude-sonnet-4-6",
            max_tokens=1024,
            messages=[
                {"role": "user", "content": user_query},
                {"role": "assistant", "content": response.content},
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "tool_result",
                            "tool_use_id": tool_use.id,
                            "content": ____,
                        }
                    ],
                },
            ],
            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)
        else:
            print("No follow-up message from model.")

    else:
        text = next((block.text for block in response.content if block.type == "text"), "")
        print(f"\nAssistant: {text}")
        return str(text)


if __name__ == "__main__":
    asyncio.run(call_anthropic_llm("How much is 250 US dollars in euros?"))
编辑并运行代码