始める無料で始める

MCP サーバーリソースの定義

通貨換算用の MCP サーバーを拡張して、使用している API がサポートする通貨の一覧にアクセスできるようにします。European Central Bankcurrencies.txt というファイルに通貨コードの一覧を公開しており、このファイルはサーバーのディレクトリに用意されています。このリソースをクライアントが参照することで、LLM がツール関数に正しい引数値を渡せるようになります。

currencies.txt の内容を読み込む get_currencies() という MCP リソースを定義しましょう。

この演習はコースの一部です

Model Context Protocol(MCP)入門

コースを見る

演習の手順

  • 正しいデコレータと "file://currencies.txt" という URI を使って、get_currencies() 関数をリソースに変換します。
  • currencies.txt ファイルを開いて内容を読み込むよう、get_currencies() 関数を完成させます。
  • get_currencies() を呼び出した結果を表示して、リソースが正しく動作することを確認します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

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(____)
コードを編集して実行