Template Explanation

Template Explanation

Let's look at how the template code works and review how you will update the code later.

There are three main parts to understand:

  1. The SQLite database and how to update it

  2. The MCP server and how to update it

  3. The client code for testing changes before publishing

The SQLite Database

The template uses an SQLite database to manage custom content for use with the MCP server. One way of loading your own data into a database is by providing a CSV file of your data, like the example provided with ai_news.csv.

ai_news.csv
id,release_date,title,source,link,tags,description
1,2024-11-15,OpenAI Announces GPT-5 Preview with Enhanced Reasoning,The Verge,https://example.com/news/1,"OpenAI, GPT-5, LLM, Technical","OpenAI has teased the upcoming release of GPT-5, promising significant improvements in logical reasoning and long-horizon task planning compared to its predecessor."
2,2024-11-20,EU AI Act Comes into Full Effect,TechCrunch,https://example.com/news/2,"Regulation, EU, Policy, Safety","The European Union's comprehensive AI Act officially enters into force today, setting strict guidelines for high-risk AI applications and transparency requirements."
3,2024-12-05,Google DeepMind Reveals Gemini 2.0 Multimodal Capabilities,Wired,https://example.com/news/3,"Google, DeepMind, Gemini, Multimodal","DeepMind showcases Gemini 2.0, demonstrating near-instantaneous video and audio processing capabilities that surpass human reaction times in specific benchmarks."
4,2024-12-12,Anthropic Raises $4B to Scale Claude Infrastructure,Bloomberg,https://example.com/news/4,"Anthropic, Funding, Business, Claude","Anthropic secures a massive $4 billion funding round led by Amazon and Google to expand its compute infrastructure for the next generation of Claude models."

We can then convert the CSV file of data into an SQLite database table using the generate_db.py program. Let's break down how this program works and how you can adapt it.

Part of generate_db.py
    # Paths
    base_dir = os.path.dirname(os.path.abspath(__file__))
    csv_path = os.path.join(base_dir, "ai_news.csv")
    db_path = os.path.join(base_dir, "ai_news.db")

Above we simply provide 1) the CSV filename to read the data from and 2) a name for the SQLite database that will be created. Once you create your own CSV file for a table, you can change these two names appropriately.

Next, let's look at how the database table columns are defined to match the CSV data.

Part of generate_db.py
    # Create table
    cursor.execute(
        """
        CREATE TABLE IF NOT EXISTS news (
            id INTEGER PRIMARY KEY,
            release_date TEXT NOT NULL,
            title TEXT NOT NULL,
            source TEXT NOT NULL,
            link TEXT NOT NULL,
            tags TEXT NOT NULL,
            description TEXT NOT NULL
        )
    """
    )

Above we use SQL ( CREATE TABLE ) to properly define the table name and columns. You want this SQL statement to map to the data you are providing in the CSV file. Don't forget to use appropriate data types (e.g. TEXT, INTEGER, etc)

Next, we will again ensure the Python program is mapping to the CSV data to read the data correctly and write it, row by row, to the database table.

Part of generate_db.py
    # Read CSV and insert data
    try:
        with open(csv_path, "r", newline="", encoding="utf-8") as f:
            reader = csv.DictReader(f)
            to_db = []
            for row in reader:
                to_db.append(
                    (
                        int(row["id"]),
                        row["release_date"],
                        row["title"],
                        row["source"],
                        row["link"],
                        row["tags"],
                        row["description"],
                    )
                )

        cursor.executemany(
            "INSERT OR REPLACE INTO news (id, release_date, title, source, link, tags, description) VALUES (?, ?, ?, ?, ?, ?, ?)",
            to_db,
        )
        conn.commit()
        print(f"Successfully created database at {db_path} with {len(to_db)} records.")
    except FileNotFoundError:
        print(f"Error: Could not find {csv_path}")
    except Exception as e:
        print(f"Error: {e}")
    finally:
        conn.close()

Above you will see that 1) the row keys (e.g. release_date in row["release_date"],) match the CSV column labels and 2) the SQL INSERT OR REPLACE INTO statement uses the correct table name and column labels.

The MCP Server Code

Let's look at two important parts of the MCP server code (server.py) — 1) we connect to the database and 2) define tools the MCP server will offer an LLM in a chat conversation.

First, we name our MCP server and connect to the SQLite database.

Part of server.py
mcp = FastMCP("AI and Robotics News Server")

# Path to the database file.
DB_PATH = "database/ai_news.db"

Above the title of the server ("AI and Robotics News Server") is defined. This is description is important, because the LLM will use this title to understand how your server can be used in a chat. When you are ready to adapt the template server provide an appropriate title and correct database filename.

Next, let's look at how a tool is defined. you will want to change the tool definitions to match your database and intended features. Below is a single example.

Part of server.py
@mcp.tool
def get_latest_stories() -> list[dict]:
    """Returns the latest 5 stories based on release date."""
    with get_db_connection() as conn:
        cursor = conn.cursor()

        # SQL query to select all columns from the 5 newest stories.
        cursor.execute("SELECT * FROM news ORDER BY release_date DESC LIMIT 5")
        rows = cursor.fetchall()

        # Convert each row into a python dictionary (object) to support a JSON result.
        list = [dict(row) for row in rows]
        return list

Above you see the definition of one MCP tool get_latest_stories() that simply 1) connects to the database, 2) retrieves the latest 5 news stories and 3) returns it as a list (array). Notice that a tool should have a very clear description (e.g. Returns the latest 5 stories based on release date.) This description helps the LLM use the appropriate tool at the appropriate time.

Note: An MCP server can have many tools available for the LLM to use as needed. We are just looking at one as an example.

For any tool you create that connects to your database, you will want to carefully contstruct the SQL and use the appropriate Python code to return content to the LLM. You will usually choose to return one of the following types of content that is compatible with JSON: string, dict (e.g. object with key-value pairs), or list (array of items).

The Client Code (for testing)

coming ...

Next, get started with developing your MCP server by modifying the template.

Last updated