Connecting Claude Desktop to MySQL
A Complete Guide to MCP Integration
Introduction
Ever wished your AI assistant could directly interact with your databases? With the Model Context Protocol (MCP), you can now connect Claude Desktop to your MySQL database, enabling powerful database operations through natural language. In this guide, I’ll walk you through my journey of setting up a complete integration that lets Claude read, insert, and update records in MySQL.
What is MCP and Why Does It Matter?
The Model Context Protocol (MCP) is an open protocol developed by Anthropic that standardizes how AI applications connect to data sources and tools. Think of it as a universal adapter that lets Claude Desktop interact with external systems—databases, APIs, file systems, and more—in a secure and structured way.
Key Benefits:
Direct Database Access: Query and modify your data using natural language
Type Safety: Structured tool definitions ensure reliable interactions
Extensibility: Easy to add new database operations as your needs grow
Security: Connections run locally on your machine
The Architecture: How It All Works
The setup consists of three main components:
Claude Desktop - The AI interface where you interact
MCP Server - A Python-based bridge that exposes database operations as tools
MySQL Database - Your data source
┌─────────────────┐
│ Claude Desktop │
└────────┬────────┘
│ (MCP Protocol)
│
┌────────▼────────┐
│ MCP Server │
│ (Python) │
└────────┬────────┘
│ (MySQL Connector)
│
┌────────▼────────┐
│ MySQL Database │
└─────────────────┘
Step 1: Database Utility Functions
First, I created a db_tools.py file containing all MySQL operations:
import mysql.connector
def conn():
return mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="zomato"
)
def read_tasks():
c = conn()
cur = c.cursor(dictionary=True)
cur.execute("SELECT * FROM items")
rows = cur.fetchall()
cur.close()
c.close()
return rows
def insert_task(title):
c = conn()
cur = c.cursor()
cur.execute("INSERT INTO tasks(title) VALUES(%s)", (title,))
c.commit()
cur.close()
c.close()
return {"status": "inserted"}
def update_task(task_id, title):
c = conn()
cur = c.cursor()
cur.execute("UPDATE items SET title=%s WHERE id=%s", (title, task_id))
c.commit()
cur.close()
c.close()
return {"status": "updated"}
Key Design Decisions:
Connection Management: Each function creates and closes its own connection for simplicity
Dictionary Cursor: Using
dictionary=Truereturns results as dictionaries, making them easier to work withError Handling: In a production environment, you’d want to add try-catch blocks and proper error handling
Step 2: Creating the MCP Server
The MCP server (db_mcp_server.py) acts as the bridge between Claude and your database:
from mcp.server.fastmcp import FastMCP
from db_tools import read_tasks, insert_task, update_task
mcp = FastMCP("mysql-tools")
@mcp.tool()
def read_tasks_tool():
return read_tasks()
@mcp.tool()
def insert_task_tool(title: str):
return insert_task(title)
@mcp.tool()
def update_task_tool(task_id: int, title: str):
return update_task(task_id, title)
if __name__ == "__main__":
mcp.run()
print("MCP SERVER STARTED")
What’s Happening Here:
FastMCP: A simplified framework for building MCP servers
@mcp.tool() Decorator: Automatically converts Python functions into tools Claude can call
Type Annotations: The
title: strandtask_id: intannotations tell Claude what parameters to expect
Step 3: Configuring Claude Desktop
The final piece is the configuration file that tells Claude Desktop about your MCP server. This file lives at:
Windows: C:\Users\[YourUsername]\AppData\Roaming\Claude\claude_desktop_config.json
{
"mcpServers": {
"mysql-tools": {
"command": "C:\\Users\\sbgow\\AppData\\Local\\Programs\\Python\\Python312\\python.exe",
"args": [
"C:\\lenovo_bkp\\C\\PycharmProjects\\pythonProject1\\mcp\\openai_without_mcp\\project_mcp\\db_mcp_server.py"
]
}
},
"preferences": {
"sidebarMode": "chat",
"coworkScheduledTasksEnabled": false
}
}
Configuration Breakdown:
mcpServers: Object containing all your MCP server definitions
mysql-tools: Your server’s unique identifier (matches the name in FastMCP)
command: Full path to your Python executable
args: Full path to your MCP server script
Important: Use double backslashes (\\) in Windows paths!
How to Use It
After restarting Claude Desktop, you can interact with your database naturally:
Example Queries:
“Show me all items in the database”
“Add a new task called ‘Buy groceries’”
“Update task 5 to say ‘Complete project documentation’”
Claude will automatically detect when to use your database tools and execute the appropriate operations.
Prerequisites
Before starting, make sure you have:
Claude Desktop: Downloaded and installed from claude.ai
Python 3.12+: With pip package manager
MySQL Server: Running locally or remotely
Required Python Packages:
pip install mysql-connector-pythonpip install mcp
Troubleshooting Common Issues
MCP Server Not Appearing in Claude
Restart Claude Desktop completely after editing the config file
Check that both Python and script paths are absolute and correct
Look for errors in Claude’s logs (Help > View Logs)
Connection Errors
Verify MySQL is running:
mysql -u root -pCheck your database credentials in
db_tools.pyEnsure the database exists:
SHOW DATABASES;
Table Mismatch Issues
I noticed in my code there’s inconsistency—read_tasks() queries the items table, but insert_task() inserts into tasks table. Make sure your table names are consistent!
Security Considerations
⚠️ Important Security Notes:
Never hardcode credentials: Use environment variables instead
import os
password=os.getenv('MYSQL_PASSWORD')
Use connection pooling: For production, implement proper connection pooling
Parameterized queries: Always use parameterized queries (which we do!) to prevent SQL injection
Limit permissions: Create a dedicated MySQL user with minimal required permissions
Extending the System
Want to add more capabilities? Here are some ideas:
Add DELETE functionality:
@mcp.tool()
def delete_task_tool(task_id: int):
c = conn()
cur = c.cursor()
cur.execute("DELETE FROM items WHERE id=%s", (task_id,))
c.commit()
cur.close()
c.close()
return {"status": "deleted"}
Add search functionality:
@mcp.tool()
def search_tasks_tool(keyword: str):
c = conn()
cur = c.cursor(dictionary=True)
cur.execute("SELECT * FROM items WHERE title LIKE %s", (f"%{keyword}%",))
rows = cur.fetchall()
cur.close()
c.close()
return rows
Real-World Applications
This setup opens up powerful possibilities:
Business Intelligence: Ask Claude to analyze sales data, generate reports, and identify trends
Data Cleaning: “Find all records with missing emails and flag them”
Automated Tasks: “Create weekly summary reports from transaction data”
Customer Support: Query customer information and order history conversationally
Conclusion
Integrating Claude Desktop with MySQL through MCP transforms how you interact with your data. Instead of writing SQL queries manually, you can ask questions in plain English and let Claude handle the technical details.
The setup might seem complex at first, but once configured, it provides an incredibly natural interface to your databases. As MCP support grows, we’ll see even more integrations with different data sources and tools.
What’s Next?
Add error handling and logging to your MCP server
Implement connection pooling for better performance
Add authentication and authorization layers
Explore other MCP integrations (file systems, APIs, cloud services)
Have you built any interesting MCP integrations? Share your experiences in the comments!


