MCP-serverresources definiëren
Je breidt je MCP-server voor valutaconversie uit zodat deze toegang heeft tot de lijst met valuta's die worden ondersteund door de API die je gebruikt. De Europese Centrale Bank publiceert een lijst met valutacodes in een bestand genaamd currencies.txt, dat beschikbaar is in je servermap. Dit kan door de client worden gebruikt om ervoor te zorgen dat het LLM de juiste argumentwaarden doorgeeft aan de toolfuncties.
Jouw taak is om een MCP-resource te definiëren, get_currencies(), die de inhoud van currencies.txt leest.
Deze oefening maakt deel uit van de cursus
Introductie tot Model Context Protocol (MCP)
Oefeninstructies
- Gebruik de juiste decorator en de URI
"file://currencies.txt"om de functieget_currencies()om te zetten in een resource. - Maak de functie
get_currencies()af zodat deze het bestandcurrencies.txtopent en de inhoud leest. - Print het resultaat van het aanroepen van
get_currencies()om te controleren of de resource goed werkt.
Interactieve oefening met praktijkervaring
Probeer deze oefening door deze voorbeeldcode aan te vullen.
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(____)