การกำหนด Resource ใน MCP Server
คุณกำลังขยาย MCP server สำหรับแปลงสกุลเงินเพื่อให้เข้าถึงรายการสกุลเงินที่ API รองรับ European Central Bank เผยแพร่รายการรหัสสกุลเงินในไฟล์ชื่อ currencies.txt ซึ่งอยู่ในไดเรกทอรีของ server นี้ ข้อมูลนี้จะช่วยให้ client ตรวจสอบได้ว่า LLM ส่ง argument ที่ถูกต้องให้กับฟังก์ชัน tool
ให้กำหนด MCP resource ชื่อ get_currencies() ที่อ่านเนื้อหาจากไฟล์ currencies.txt
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Model Context Protocol (MCP) เบื้องต้น
คำแนะนำการฝึกหัด
- ใช้ decorator ที่ถูกต้องพร้อม URI
"file://currencies.txt"เพื่อแปลงฟังก์ชันget_currencies()ให้เป็น resource - เติมโค้ดในฟังก์ชัน
get_currencies()เพื่อเปิดและอ่านเนื้อหาของไฟล์currencies.txt - พิมพ์ผลลัพธ์จากการเรียก
get_currencies()เพื่อตรวจสอบว่า resource ทำงานได้ถูกต้อง
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Currency Converter")
# Define a resource for the currencies file
____
def get_currencies() -> str:
"""
Get the list of currency names published by the European Central Bank for currency conversion.
Returns:
Contents of the currencies.txt file with currency names
"""
# Open currencies.txt and read the data
try:
with open('____', 'r') as f:
content = f.____
return content
except FileNotFoundError:
return "currencies.txt file not found"
# Test the resource function
print(____)