> For the complete documentation index, see [llms.txt](https://docs.launchboard.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.launchboard.org/quick-projects/ai-chats-with-mcp+sqlite/template-explanation.md).

# Template Explanation

{% embed url="<https://www.loom.com/share/4f9a8b5c7b33436c923c73a3b37c14e7>" %}

**Let's look at how the template code works and review how you will update the code later.**&#x20;

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*.

{% code title="ai\_news.csv" fullWidth="false" expandable="true" %}

```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."
```

{% endcode %}

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.

{% code title="Part of generate\_db.py" %}

```python
    # 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")
```

{% endcode %}

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.&#x20;

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

{% code title="Part of generate\_db.py" %}

```python
    # 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
        )
    """
    )
```

{% endcode %}

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)&#x20;

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.

{% code title="Part of generate\_db.py" %}

```python
    # 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()
```

{% endcode %}

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.

{% hint style="success" %}
If you provide custom CSV file **and** update the python program correctly, you can then run the *generate\_db.py* program using `python generate_db.py` in the terminal of Github codespaces (or your programming environment) to make your custom database. If all goes well, you should see a message of success in the terminal.
{% endhint %}

#### 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.

{% code title="Part of server.py" %}

```python
mcp = FastMCP("AI and Robotics News Server")

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

{% endcode %}

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.

{% code title="Part of server.py" %}

```python
@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
```

{% endcode %}

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.&#x20;

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).

**Next, get started with** [**developing your MCP server**](/quick-projects/ai-chats-with-mcp+sqlite/developing-your-mcp-server.md) **by modifying the template.**


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.launchboard.org/quick-projects/ai-chats-with-mcp+sqlite/template-explanation.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
