MCP MySQL Database Service
Provides MySQL database query capabilities through MCP protocol, enabling AI assistants to retrieve table metadata, execute SQL queries, and manage database interactions via Resources, Prompts, and Tools.
README
MCP MySQL数据库服务
这是一个基于FastMCP框架的MySQL数据库查询服务,提供Resources、Prompts、Tools三种服务类型,允许AI助手通过MCP协议执行数据库查询操作。
功能特性
Resources(资源服务)
database://tables- 获取数据库中所有表名database://table/{table_name}/data- 获取指定表的数据(支持分页)database://table/{table_name}/structure- 获取指定表的结构信息
Prompts(提示词服务)
sql_query_assistant- SQL查询助手提示词,根据用户需求生成SQL查询建议
Tools(工具服务)
execute_complex_query- 执行复杂的多表SQL查询
技术栈
- 语言: Python 3.8+
- MCP框架: FastMCP(基于标准MCP协议)
- 数据库驱动: PyMySQL
- 开发工具: mcp dev
- 测试工具: mcp inspector
安装和配置
1. 安装依赖
pip install -r requirements.txt
2. 配置数据库
编辑 .env 文件,配置MySQL数据库连接信息:
MYSQL_HOST=localhost
MYSQL_PORT=3307
MYSQL_USER=root
MYSQL_PASSWORD=root
MYSQL_DATABASE=mcp
3. 启动服务
开发模式(stdio)
使用MCP开发模式启动服务,适合开发和调试:
mcp dev mcp_server.py
服务启动后会显示:
Starting MCP inspector...
⚙️ Proxy server listening on localhost:6277
🔑 Session token: [token]
🚀 MCP Inspector is up and running at: http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=[token]
生产模式(SSE)
使用SSE(Server-Sent Events)模式启动HTTP服务,适合生产环境部署:
python mcp_server.py --mode sse --port 8000
服务启动后会显示:
🚀 启动MCP SSE服务器...
📡 服务地址: http://localhost:8000
🔗 MCP端点: http://localhost:8000/sse
📊 健康检查: http://localhost:8000/health
📖 API文档: http://localhost:8000/docs
命令行参数
python mcp_server.py [选项]
选项:
--mode {stdio,sse} 运行模式: stdio (默认) 或 sse
--host HOST SSE服务器主机 (默认: localhost)
--port PORT SSE服务器端口 (默认: 8000)
-h, --help 显示帮助信息
使用方法
1. 通过MCP Inspector测试
启动服务后,浏览器会自动打开MCP Inspector界面,你可以:
- 测试Resources: 查看数据库表列表、表数据、表结构
- 测试Prompts: 使用SQL查询助手生成查询建议
- 测试Tools: 执行复杂的SQL查询
2. 在Kiro IDE中配置
stdio模式配置(开发环境)
在Kiro的MCP配置中添加:
{
"mcpServers": {
"mysql-database": {
"command": "python",
"args": ["path/to/mcp_server.py"],
"disabled": false,
"autoApprove": []
}
}
}
SSE模式配置(生产环境)
在Kiro的MCP配置中添加:
{
"mcpServers": {
"mysql-database-sse": {
"command": "python",
"args": ["path/to/mcp_server.py", "--mode", "sse", "--port", "8000"],
"disabled": false,
"autoApprove": []
}
}
}
3. 通过HTTP API访问(SSE模式)
当服务以SSE模式运行时,可以通过HTTP接口访问:
- 健康检查:
GET http://localhost:8000/health - MCP SSE端点:
GET http://localhost:8000/sse - API文档:
GET http://localhost:8000/docs
API参考
Resources
获取表列表
- URI:
database://tables - 返回: 数据库中所有表名的JSON列表
{
"tables": ["users", "orders", "products"],
"count": 3,
"database": "mcp"
}
获取表数据
- URI:
database://table/{table_name}/data - 参数:
table_name- 表名 - 返回: 表数据和分页信息
{
"table_name": "users",
"data": [...],
"pagination": {
"limit": 1000,
"offset": 0,
"returned": 10,
"total": 100
}
}
获取表结构
- URI:
database://table/{table_name}/structure - 参数:
table_name- 表名 - 返回: 表结构信息
{
"table_name": "users",
"columns": [
{
"Field": "id",
"Type": "int(11)",
"Null": "NO",
"Key": "PRI"
}
],
"create_statement": "CREATE TABLE ..."
}
Prompts
SQL查询助手
- 名称:
sql_query_assistant - 参数:
query_description(必需) - 查询需求描述table_name(可选) - 目标表名
- 返回: SQL查询建议和说明
Tools
执行复杂查询
- 名称:
execute_complex_query - 参数:
sql_query(必需) - SQL查询语句limit(可选,默认1000) - 结果行数限制
- 返回: 查询结果
{
"sql": "SELECT * FROM users LIMIT 1000",
"results": [...],
"count": 10,
"limit": 1000,
"success": true
}
使用示例
1. 获取所有表名
在MCP Inspector中选择Resource database://tables,点击执行。
2. 查看用户表数据
选择Resource database://table/users/data,查看用户表的前1000条记录。
3. 获取SQL查询建议
使用Prompt sql_query_assistant:
{
"query_description": "查询最近一周注册的用户",
"table_name": "users"
}
4. 执行复杂查询
使用Tool execute_complex_query:
{
"sql_query": "SELECT u.name, COUNT(o.id) as order_count FROM users u LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.id",
"limit": 500
}
特性说明
安全特性
- 只读操作:仅支持SELECT查询
- 结果限制:默认最多返回1000行数据
- 错误处理:完善的异常处理和错误日志
性能特性
- 连接管理:自动管理数据库连接
- 查询超时:30秒查询超时保护
- 分页支持:支持大数据集的分页查询
开发特性
- 热重载:使用
mcp dev支持代码热重载 - 调试友好:通过MCP Inspector可视化调试
- 标准协议:完全兼容MCP标准协议
故障排除
1. 数据库连接失败
- 检查
.env文件中的数据库配置 - 确认MySQL服务正在运行
- 验证数据库用户权限
2. MCP服务启动失败
- 确认已安装所有依赖:
pip install -r requirements.txt - 检查Python版本(需要3.8+)
- 查看错误日志信息
3. Inspector无法连接
- 确认服务正常启动
- 检查端口是否被占用(6274, 6277)
- 使用正确的认证令牌
开发说明
项目结构
mcp-service/
├── mcp_server.py # 主服务文件
├── requirements.txt # 依赖配置
├── .env # 数据库配置
├── README.md # 使用说明
└── MCP需求.md # 需求文档
扩展开发
如需添加新功能,可以:
- 添加新的Resource、Prompt或Tool
- 使用
@mcp.resource()、@mcp.prompt()、@mcp.tool()装饰器 - 通过
mcp dev测试新功能
许可证
本项目仅用于学习和实践MCP协议开发。
部署说明
生产环境部署(SSE模式)
- 使用systemd服务(Linux):
创建服务文件 /etc/systemd/system/mcp-mysql.service:
[Unit]
Description=MCP MySQL Database Service
After=network.target mysql.service
[Service]
Type=simple
User=www-data
WorkingDirectory=/path/to/mcp-service
Environment=PATH=/path/to/venv/bin
ExecStart=/path/to/venv/bin/python mcp_server.py --mode sse --host 0.0.0.0 --port 8000
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
启动服务:
sudo systemctl enable mcp-mysql
sudo systemctl start mcp-mysql
sudo systemctl status mcp-mysql
- 使用Docker部署:
创建 Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "mcp_server.py", "--mode", "sse", "--host", "0.0.0.0", "--port", "8000"]
构建和运行:
docker build -t mcp-mysql-service .
docker run -d -p 8000:8000 --env-file .env mcp-mysql-service
- 使用nginx反向代理:
server {
listen 80;
server_name your-domain.com;
location / {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# SSE特殊配置
proxy_buffering off;
proxy_cache off;
proxy_set_header Connection '';
proxy_http_version 1.1;
chunked_transfer_encoding off;
}
}
更新日志
v1.1.0 (2025-01-08)
- ✅ 新增SSE(Server-Sent Events)模式支持
- ✅ 支持HTTP API访问
- ✅ 添加命令行参数配置
- ✅ 完善生产环境部署说明
- ✅ 支持健康检查和API文档端点
v1.0.0 (2025-01-08)
- ✅ 完成基础MCP服务实现
- ✅ 支持3个Resources服务
- ✅ 支持1个Prompts服务
- ✅ 支持1个Tools服务
- ✅ 通过MCP Inspector测试验证
- ✅ 支持mcp dev启动方式

Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.