MCP 与 LLM:工具

Model Context Protocol (MCP) 入门

James Chapman

AI Curriculum Manager, DataCamp

将 MCP 工具映射到 LLM 工具

 

工具 ↔ LLM 集成高度依赖具体 LLM

  • 不同 LLM 接受工具的方式与语法各异
  • 通过 Anthropic 的 Messages API 使用 Claude
  • 重点:流程与转换

llm_mcp.png

Model Context Protocol (MCP) 入门

工具调用工作流

fct1.jpg

Model Context Protocol (MCP) 入门

工具调用工作流

fct2.jpg

Model Context Protocol (MCP) 入门

工具调用工作流

fct3.jpg

Model Context Protocol (MCP) 入门

工具调用工作流

fct4.jpg

Model Context Protocol (MCP) 入门

工具调用工作流

fct5.jpg

Model Context Protocol (MCP) 入门

工具调用工作流

fct6.jpg

Model Context Protocol (MCP) 入门

MCP 服务器:timezone_server.py

from mcp.server.fastmcp import FastMCP
import requests

mcp = FastMCP("Timezone Converter")

@mcp.tool()
def convert_timezone(date_time: str, from_timezone: str, to_timezone: str) -> str:
    ...

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

扩展客户端代码

async def get_tools_from_mcp():
            # ... 
            return response.tools

async def call_mcp_tool(tool_name: str, arguments: dict) -> str:        
            # ...
            result = await session.call_tool(tool_name, arguments)
            return str(result.content[0].text)

async def call_anthropic_llm(user_query: str):
Model Context Protocol (MCP) 入门

准备:为 LLM 格式化工具

async def call_anthropic_llm(user_query: str):
    """使用 MCP 工具调用 Claude。"""

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, # MCP 使用 JSON Schema 格式 }
anthropic_tools.append(anthropic_tool)
Model Context Protocol (MCP) 入门

1. 向 LLM 发送查询与工具

from anthropic import AsyncAnthropic
async def call_anthropic_llm(user_query: str):
    # ...

client = AsyncAnthropic(api_key="<ANTHROPIC_API_TOKEN>")
response = await client.messages.create( model="claude-sonnet-4-6", max_tokens=1024, messages=[{"role": "user", "content": user_query}], tools=anthropic_tools, )
Model Context Protocol (MCP) 入门

2. 检查是否调用工具

async def call_anthropic_llm(user_query: str):
    # ...

    if response.stop_reason == "tool_use":

tool_use = next(b for b in response.content if b.type == "tool_use") name = tool_use.name args = tool_use.input print(f"模型决定调用:{name}") print(f"参数:{args}\n")
Model Context Protocol (MCP) 入门

3. 调用工具 | 4. 跟进消息

async def call_anthropic_llm(user_query: str):
    # ...

    if response.stop_reason == "tool_use":
        # ...

result = await call_mcp_tool(name, args)
tool_result = {"type": "tool_result", "tool_use_id": tool_use.id, "content": result} 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": [tool_result]}, ], tools=anthropic_tools, )
Model Context Protocol (MCP) 入门

5. 最终回复

async def call_anthropic_llm(user_query: str):
    # ...

    if response.stop_reason == "tool_use":
        # ...

final = next((b.text for b in followup.content if b.type == "text"), None) if final: print(f"\n助手:{final}") else: print("模型未返回跟进消息。")
else: text = next((b.text for b in response.content if b.type == "text"), "") print(f"\n助手:{text}") return str(text)
Model Context Protocol (MCP) 入门

测试函数

if __name__ == "__main__":
    asyncio.run(call_anthropic_llm("It is 9:50 AM in the UK in January. What time 
    is it in Lisbon, Portugal?"))
Assistant: It's 9:50 AM in Lisbon as well.
Model Context Protocol (MCP) 入门

工具调用工作流

fct6.jpg

Model Context Protocol (MCP) 入门

Let's practice!

Model Context Protocol (MCP) 入门

Preparing Video For Download...