Can Gemini AI Directly Query MySQL? A FastMCP Walkthrough

This article demonstrates how to set up a FastMCP server for MySQL, load the Sakila sample database, expose query tools to Gemini, experiment with different model versions and temperature settings, and observe the generated SQL queries and results, providing a practical guide for AI‑driven database access.

Aikesheng Open Source Community
Aikesheng Open Source Community
Aikesheng Open Source Community
Can Gemini AI Directly Query MySQL? A FastMCP Walkthrough

Using FastMCP to Create a MySQL MCP Server

FastMCP abstracts most of the work; you only need to specify how to connect to MySQL. The following Python script creates an MCP server named "MySQL demo" with a query_data tool that executes arbitrary SQL queries against the sakila database and returns JSON‑encoded results.

import json
import mysql.connector
from fastmcp import FastMCP

mcp = FastMCP(name="MySQL demo")

@mcp.tool()
def query_data(sql_query: str) -> str:
    """Execute MySQL queries safely for the actors table inside the test database and return structured JSON response."""
    DB_NAME = "sakila"
    DB_USER = "mcpreader"
    DB_PASS = "secret"
    DB_HOST = "localhost"
    DB_PORT = "3306"
    conn = None
    cursor = None
    try:
        conn = mysql.connector.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)
        cursor = conn.cursor()
        cursor.execute(sql_query)
        rows = cursor.fetchall()
    finally:
        if cursor is not None:
            cursor.close()
        if conn is not None:
            conn.close()
    return json.dumps(rows, indent=2)

if __name__ == "__main__":
    mcp.run()

MySQL Target Database

Install MySQL 8.0 on Ubuntu, download the Sakila sample database, load its schema and data, and create a read‑only user mcpreader with password secret:

sudo apt-get install mysql-server-8.0
cd /tmp
curl -O https://downloads.mysql.com/docs/sakila-db.tar.gz
tar zxvf sakila-db.tar.gz
sudo mysql
source /tmp/sakila-db/sakila-schema.sql;
source /tmp/sakila-db/sakila-data.sql;
create user 'mcpreader'@'localhost' identified by 'secret';
grant select on sakila.* to 'mcpreader'@'localhost';

Running the MCP Server

Use uv to create a virtual environment, install dependencies, and start the server with SSE transport:

curl -LsSf https://astral.sh/uv/install.sh | sh
uv venv e1
source e1/bin/activate
uv pip install fastmcp mysql-connector-python
fastmcp run -t sse mcp-mysql.py

The server starts at http://127.0.0.1:8000/sse/.

Testing the Database Integration

In the same environment, launch an IPython session, create a FastMCP client, list available tools, and call query_data:

from fastmcp import Client
client = Client("http://127.0.0.1:8000/sse/")
async with client:
    tools = await client.list_tools()
    result = await client.call_tool("query_data", {"sql_query": "select count(*) from actor"})
    print(result.structured_content['result'])

The AI receives the tool description and can invoke it to retrieve data.

Accessing the Database via Gemini

Create a second virtual environment, install google‑genai and fastmcp, and set the Gemini API key:

uv venv e2
source e2/bin/activate
uv pip install fastmcp google-genai
export GEMINI_API_KEY="<redacted>"

Instantiate both clients:

from fastmcp import Client
from google import genai

mcp_client = Client("http://127.0.0.1:8000/sse/")
gemini_client = genai.Client()

Ask Gemini a question that requires a multi‑table query, e.g., “Which films feature Morgan McDormand and are suitable for a general audience?” and include the MCP session as a tool:

question = "Which films feature Morgan McDormand and are suitable for a general audience?"
response = await gemini_client.aio.models.generate_content(
    model="gemini-2.0-flash",
    contents=question,
    config=genai.types.GenerateContentConfig(
        temperature=0,
        tools=[mcp_client.session]
    )
)

Gemini initially replies with a clarification request; adjusting the temperature (e.g., 0.1) or switching to a more capable model improves the result.

Different LLMs Yield Different Results

Using the newer gemini-2.5-pro model without a temperature setting, Gemini successfully returns a list of movies with a "G" rating starring Morgan McDormand:

DIVORCE SHINING

SAGEBRUSH CLUELESS

The underlying SQL queries executed by the MCP server are logged, showing the step‑by‑step discovery of the actor and the final join query.

Lesson Learned

Choosing the right LLM and prompt parameters is crucial for efficient AI‑driven database access; a more powerful model can produce correct queries without excessive trial‑and‑error.

databaseMySQLGeminiAI integrationFastMCP
Aikesheng Open Source Community
Written by

Aikesheng Open Source Community

The Aikesheng Open Source Community provides stable, enterprise‑grade MySQL open‑source tools and services, releases a premium open‑source component each year (1024), and continuously operates and maintains them.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.