MCP và LLM: Công cụ

Giới thiệu về Model Context Protocol (MCP)

James Chapman

AI Curriculum Manager, DataCamp

Chuyển MCP Tools sang LLM Tools

 

Tích hợp Công cụ ↔ LLM phụ thuộc nhiều vào LLM

  • Mỗi LLM nhận công cụ theo cách và cú pháp khác nhau
  • Dùng Claude qua Messages API của Anthropic
  • Trọng tâm: quy trình và biến đổi

llm_mcp.png

Giới thiệu về Model Context Protocol (MCP)

Quy trình gọi công cụ

fct1.jpg

Giới thiệu về Model Context Protocol (MCP)

Quy trình gọi công cụ

fct2.jpg

Giới thiệu về Model Context Protocol (MCP)

Quy trình gọi công cụ

fct3.jpg

Giới thiệu về Model Context Protocol (MCP)

Quy trình gọi công cụ

fct4.jpg

Giới thiệu về Model Context Protocol (MCP)

Quy trình gọi công cụ

fct5.jpg

Giới thiệu về Model Context Protocol (MCP)

Quy trình gọi công cụ

fct6.jpg

Giới thiệu về Model Context Protocol (MCP)

Máy chủ 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")
Giới thiệu về Model Context Protocol (MCP)

Mở rộng mã phía khách hàng

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):
Giới thiệu về Model Context Protocol (MCP)

Thiết lập: Định dạng công cụ cho LLM

async def call_anthropic_llm(user_query: str):
    """Gọi Claude với công cụ MCP."""

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 uses JSON Schema format }
anthropic_tools.append(anthropic_tool)
Giới thiệu về Model Context Protocol (MCP)

1. Gửi truy vấn và công cụ tới 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, )
Giới thiệu về Model Context Protocol (MCP)

2. Kiểm tra việc gọi công cụ

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"Model decided to call: {name}") print(f"Arguments: {args}\n")
Giới thiệu về Model Context Protocol (MCP)

3. Gọi công cụ | 4. Tin nhắn tiếp theo

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, )
Giới thiệu về Model Context Protocol (MCP)

5. Phản hồi cuối cùng

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"\nAssistant: {final}") else: print("No follow-up message from model.")
else: text = next((b.text for b in response.content if b.type == "text"), "") print(f"\nAssistant: {text}") return str(text)
Giới thiệu về Model Context Protocol (MCP)

Kiểm thử hàm

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.
Giới thiệu về Model Context Protocol (MCP)

Quy trình gọi công cụ

fct6.jpg

Giới thiệu về Model Context Protocol (MCP)

Hãy luyện tập!

Giới thiệu về Model Context Protocol (MCP)

Preparing Video For Download...