Aan de slagGa gratis aan de slag

Databases as Resources

Now to take that database information and make it available as a resource in the MCP server. This can be used downstream to validate that the LLM is requesting supported currency codes, or even in the user interface to make the currency code a dropdown or autocomplete selection.

The database is still available as currencies.db, and the code to instantiate a server has been provided for you.

Deze oefening maakt deel uit van de cursus

Introduction to Model Context Protocol (MCP)

Cursus bekijken

Oefeninstructies

  • Establish a connection to the database (currencies.db).
  • Create a new MCP server resource for the database connection.
  • Execute the database query so that the get_currencies() function returns the database's contents.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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)
Code bewerken en uitvoeren