Definire le risorse di un server MCP
Stai ampliando il tuo server MCP per la conversione valutaria per dargli accesso all'elenco delle valute supportate dall'API che stai usando. La Banca Centrale Europea pubblica un elenco di codici valuta in un file chiamato currencies.txt, disponibile nella directory del tuo server. Questo potrebbe essere usato dal client per assicurarsi che l'LLM passi i valori corretti degli argomenti alle funzioni dello strumento.
Il tuo compito è definire una risorsa MCP chiamata get_currencies() che legga il contenuto di currencies.txt.
Questo esercizio fa parte del corso
Introduzione al Model Context Protocol (MCP)
Istruzioni dell'esercizio
- Usa il decorator corretto e l'URI
"file://currencies.txt"per trasformare la funzioneget_currencies()in una risorsa. - Completa la funzione
get_currencies()per aprire e leggere il contenuto del filecurrencies.txt. - Stampa il risultato della chiamata a
get_currencies()per verificare che la risorsa funzioni correttamente.
esercizio interattivo pratico
Prova questo esercizio completando questo codice di esempio.
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(____)