始める無料で始める

リソースとしてのデータベース

次に、データベースの情報を MCP サーバーのリソースとして公開しましょう。これにより、LLM がリクエストした通貨コードのバリデーションや、ユーザーインターフェースでのドロップダウンやオートコンプリートによる通貨コード選択などに活用できます。

データベースは引き続き currencies.db として利用可能で、サーバーを初期化するコードはあらかじめ用意されています。

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

Model Context Protocol(MCP)入門

コースを見る

演習の手順

  • データベース(currencies.db)への接続を確立してください。
  • データベース接続用の MCP サーバーリソースを新たに作成してください。
  • get_currencies() 関数がデータベースの内容を返すように、データベースクエリを実行してください。

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

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

from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Currency Converter")

# Connect to the database on startup
conn = sqlite3.____("____")
conn.row_factory = sqlite3.Row

# Create an MCP resource
@mcp.____("db://currencies")
def get_currencies() -> str:
    """
    Get the list of currency names published by the European Central Bank for currency conversion.

    Returns:
        One line per currency (code - name), from the database.
    """
    try:
        # Query the database
        cursor = conn.____("SELECT code, name FROM currencies")
        rows = cursor.fetchall()
        return "\n".join(f"{row['code']} - {row['name']}" for row in rows)
    except sqlite3.Error as e: return f"Error: {e}"

result = get_currencies()
print(result[:200] + "..." if len(result) > 200 else result)
コードを編集して実行