Featured

Deploy OpenClaw in 60 seconds — 20% off logoDeploy OpenClaw in 60 seconds — 20% off

Launch OpenClaw on Hostinger in about 60 seconds and keep your agent live 24/7. Our referral link gives you 20% off, no coupon code needed.

Launch on Hostinger
Run your Hermes agent on Hostinger, fully managed logoRun your Hermes agent on Hostinger, fully managed

Launch Hermes on Hostinger in one click, fully managed, no VPS knowledge needed. Use code ZACAARON10 for 10% off.

Launch on Hostinger
Crawl and scrape any site into clean data, 10% off logoCrawl and scrape any site into clean data, 10% off

Firecrawl crawls and scrapes any site into clean markdown for your agent. Get 1,000 free credits, and new users get 10% off their first purchase.

Try Firecrawl free
6,000+ web scrapers for your AI agent, start free logo6,000+ web scrapers for your AI agent, start free

Apify gives your agent live web data: 6,000+ prebuilt scrapers and actors, MCP-ready. Sign up free with $5 in usage credits.

Try Apify free
One API to scrape, enrich, and extract the internet. logoOne API to scrape, enrich, and extract the internet.

Context.dev gives your agents a single API to scrape, enrich, and extract live web data — no proxies, no parsers, no maintenance.

Start building free
SetupClaw: done-for-you OpenClaw for founders & exec teams logoSetupClaw: done-for-you OpenClaw for founders & exec teams

White-glove OpenClaw for founders and exec teams (4–50+ employees): we install, harden, integrate your tools, and maintain it — secured from day one.

Get it set up for you
SEO data APIs for your agent, $1 free credit logoSEO data APIs for your agent, $1 free credit

DataForSEO gives your agent live access to SERP results, keyword data, backlinks, and on-page SEO data through one API. New accounts get a $1 credit, good for up to 20,000 keyword or backlink lookups.

Try DataForSEO free
Reach 48,000+ AI builders

A flat monthly placement in front of developers actively installing AI tools. No lock-in, cancel anytime.

Advertise here

Works with

Claude CodeClaude DesktopCursorVS CodeClineCodex CLIOpenClaw+ any MCP client

Install to Claude Code

This server doesn't publish a one-line install command. Follow the setup in the source repository.

Summary

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

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: ``json { "query_description": "查询最近一周注册的用户", "table_name": "users" } ``

4. 执行复杂查询

使用Tool execute_complex_query: ``json { "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        # 需求文档

扩展开发

如需添加新功能,可以:

  1. 添加新的Resource、Prompt或Tool
  2. 使用@mcp.resource()@mcp.prompt()@mcp.tool()装饰器
  3. 通过mcp dev测试新功能

许可证

本项目仅用于学习和实践MCP协议开发。

部署说明

生产环境部署(SSE模式)

  1. 使用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

启动服务: ``bash sudo systemctl enable mcp-mysql sudo systemctl start mcp-mysql sudo systemctl status mcp-mysql ``

  1. 使用Docker部署

创建 Dockerfile: ```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"] ```

构建和运行: ``bash docker build -t mcp-mysql-service . docker run -d -p 8000:8000 --env-file .env mcp-mysql-service ``

  1. 使用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启动方式

!img.png

See related servers & alternatives →

Related MCP servers

Browse all →

Related guides

Hand-picked reading to help you choose and use Databases servers.