Skip to main content
Glama
zhaojw-php

MySQL ReadOnly MCP Server

by zhaojw-php
README.md
# MySQL ReadOnly MCP Server

🔒 **生产就绪** 的 MySQL 只读 MCP (Model Context Protocol) 服务器,提供安全、高性能的数据库查询服务。

## ✨ 核心特性

- 🔒 **只读安全**: 仅允许 SELECT 查询,多层安全防护
- 🚀 **高性能**: 连接池、自动LIMIT、查询优化
- 🛡️ **企业级安全**: SQL注入防护、配置验证、SSL支持
- 🧪 **测试覆盖**: 17个全面的单元测试
- 📝 **TypeScript**: 完整类型支持
- 🔧 **多平台支持**: Claude Desktop、Claude Code、Gemini CLI

## 🚀 快速开始

### 1. 安装依赖

```bash
git clone https://github.com/jway8975/mysql-readonly-mcp.git
cd mysql-readonly-mcp
npm install
```

### 2. 配置数据库连接

```bash
cp .env.example .env
```

编辑 `.env` 文件:

```env
# 基本连接配置
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=your_mysql_username
MYSQL_PASSWORD=your_mysql_password
MYSQL_DATABASE=your_database_name

# SSL 配置(可选)
# MYSQL_SSL_CA=path/to/ca.pem
# MYSQL_SSL_CERT=path/to/cert.pem
# MYSQL_SSL_KEY=path/to/key.pem
# MYSQL_SSL_REJECT_UNAUTHORIZED=true
```

### 3. 构建项目

```bash
npm run build
```

### 4. 配置到您的AI客户端

选择以下任一配置方式:

- [Claude Desktop](#claude-desktop-配置)
- [Claude Code](#claude-code-配置)
- [Gemini CLI](#gemini-cli-配置)

## 🔧 配置方法

### Claude Desktop 配置

找到 Claude Desktop 配置文件:

**macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
**Windows**: `%APPDATA%\Claude\claude_desktop_config.json`

添加以下配置:

```json
{
  "mcpServers": {
    "mysql-readonly": {
      "command": "node",
      "args": ["完整路径/mysql-readonly-mcp/dist/index.js"],
      "env": {
        "MYSQL_HOST": "localhost",
        "MYSQL_PORT": "3306",
        "MYSQL_USER": "your_username",
        "MYSQL_PASSWORD": "your_password",
        "MYSQL_DATABASE": "your_database"
      }
    }
  }
}
```

**⚠️ 重要提醒**:
- 使用**绝对路径**,例如:`/Users/username/projects/mysql-readonly-mcp/dist/index.js`
- 确保路径中有正确的项目名称 `mysql-readonly-mcp`
- 配置完成后重启 Claude Desktop

### Claude Code 配置

Claude Code 会自动识别项目中的 `.claude_config` 文件。在项目根目录创建:

```bash
# 创建 Claude Code 配置文件
cat > .claude_config << 'EOF'
tools:
  mysql-readonly:
    type: mcp
    command: node
    args: ["./dist/index.js"]
    env:
      MYSQL_HOST: ${MYSQL_HOST}
      MYSQL_PORT: ${MYSQL_PORT}
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_PASSWORD: ${MYSQL_PASSWORD}
      MYSQL_DATABASE: ${MYSQL_DATABASE}
EOF
```

**使用步骤**:

1. **构建项目**:
```bash
npm run build
```

2. **设置环境变量**:
```bash
export MYSQL_HOST="localhost"
export MYSQL_USER="your_username"
export MYSQL_PASSWORD="your_password"
export MYSQL_DATABASE="your_database"
```

3. **验证配置**:
```bash
# Claude Code 会自动发现并配置 MCP 工具
claude-code "列出数据库中的所有表"
```

### Gemini CLI 配置

1. **安装 Gemini CLI**:
```bash
npm install -g @google/generative-ai-cli
```

2. **创建 MCP 配置文件**:
```bash
mkdir -p ~/.gemini
cat > ~/.gemini/mcp_config.json << 'EOF'
{
  "servers": {
    "mysql-readonly": {
      "command": "node",
      "args": ["完整路径/mysql-readonly-mcp/dist/index.js"],
      "env": {
        "MYSQL_HOST": "localhost",
        "MYSQL_USER": "your_username",
        "MYSQL_PASSWORD": "your_password",
        "MYSQL_DATABASE": "your_database"
      }
    }
  }
}
EOF
```

3. **配置 Gemini CLI**:
```bash
export GEMINI_MCP_CONFIG="$HOME/.gemini/mcp_config.json"
export GEMINI_API_KEY="your_gemini_api_key"
```

4. **测试连接**:
```bash
gemini "请帮我查询用户表的前10条记录" --use-mcp mysql-readonly
```

## 📋 环境变量说明

| 变量名 | 必需 | 默认值 | 说明 |
|--------|------|--------|------|
| `MYSQL_HOST` | ✅ | localhost | MySQL 服务器地址 |
| `MYSQL_PORT` | ❌ | 3306 | MySQL 服务器端口 |
| `MYSQL_USER` | ✅ | - | MySQL 用户名 |
| `MYSQL_PASSWORD` | ✅ | - | MySQL 密码 |
| `MYSQL_DATABASE` | ❌ | - | 默认连接的数据库 |
| `MYSQL_SSL_CA` | ❌ | - | SSL CA 证书路径 |
| `MYSQL_SSL_CERT` | ❌ | - | SSL 客户端证书路径 |
| `MYSQL_SSL_KEY` | ❌ | - | SSL 客户端密钥路径 |
| `MYSQL_SSL_REJECT_UNAUTHORIZED` | ❌ | true | 是否拒绝未授权的 SSL 证书 |

## 🛠️ 可用工具

### 1. `mysql_query` - 执行SQL查询
执行只读 SQL 查询。

**参数**:
- `query` (string, 必需): 要执行的 SQL 查询(仅允许 SELECT 语句)

**示例**:
```json
{
  "query": "SELECT * FROM users WHERE age > 18 ORDER BY name LIMIT 10"
}
```

### 2. `mysql_list_tables` - 列出表
列出数据库中的所有表。

**参数**:
- `database` (string, 可选): 数据库名称(默认使用配置的数据库)

**示例**:
```json
{
  "database": "my_app_db"
}
```

### 3. `mysql_describe_table` - 表结构
获取表的结构和列信息。

**参数**:
- `table` (string, 必需): 要描述的表名
- `database` (string, 可选): 数据库名称

**示例**:
```json
{
  "table": "users",
  "database": "my_app_db"
}
```

### 4. `mysql_list_databases` - 列出数据库
列出所有可用的数据库(排除系统数据库)。

**参数**:无

## 🔒 安全特性

- **多层只读验证**: 严格的 SELECT 语句检查
- **SQL注入防护**: 检测危险关键词和注入模式
- **自动LIMIT**: 为查询添加默认限制,防止大数据集
- **配置验证**: 启动时验证必需配置
- **连接池**: 高效的连接管理,防止连接泄露
- **SSL支持**: 加密数据库连接

## 🧪 测试

```bash
# 运行所有测试
npm test

# 运行测试并生成覆盖率报告
npm run test:coverage

# 监视模式运行测试
npm run test:watch
```

## 📊 性能优化

- **连接池**: 复用数据库连接,减少连接开销
- **查询限制**: 自动添加 LIMIT 子句,防止大查询
- **智能缓存**: 优化重复查询性能
- **内存管理**: 流式处理大型结果集

## 🔍 故障排除

### 连接问题
- ✅ 检查 MySQL 服务是否运行
- ✅ 验证 `.env` 文件中的凭据
- ✅ 确保用户具有数据库的 SELECT 权限
- ✅ 检查网络连接和防火墙设置

### 配置问题
- ✅ 确保使用了绝对路径
- ✅ 验证环境变量设置
- ✅ 检查 SSL 配置(如适用)

### 常见错误
- `"Access denied"`: 检查用户名/密码和权限
- `"Connection refused"`: MySQL 服务未运行或端口错误
- `"Unknown database"`: 数据库不存在
- `"Only SELECT statements are allowed"`: 尝试执行非只读查询

## 🚀 开发

### 开发模式
```bash
npm run dev
```

### 构建生产版本
```bash
npm run build
```

### 运行生产版本
```bash
npm start
```

## 📈 版本历史

- **v1.0.0** - 初始版本,基础功能
- **v1.1.0** - 添加连接池和性能优化
- **v1.2.0** - 增强安全特性和测试覆盖

## 🤝 贡献

1. Fork 仓库
2. 创建特性分支 (`git checkout -b feature/amazing-feature`)
3. 提交更改 (`git commit -m 'Add amazing feature'`)
4. 推送到分支 (`git push origin feature/amazing-feature`)
5. 创建 Pull Request

## 📄 许可证

本项目采用 MIT 许可证 - 查看 [LICENSE](LICENSE) 文件了解详情。

## 🆘 支持

如果您遇到问题或有疑问,请:

1. 查看 [故障排除](#故障排除) 部分
2. 检查 [Issues](https://github.com/jway8975/mysql-readonly-mcp/issues) 页面
3. 创建新的 Issue 描述您的问题

---

**🎉 感谢使用 MySQL ReadOnly MCP Server!**

现在您可以安全地让 AI 助手查询您的 MySQL 数据库了。

TDQS

A3.5/5.0

Scored across 4 tools

Disambiguation5/5

Each tool has a clearly distinct purpose with no overlap: describe_table focuses on schema details, list_databases and list_tables handle enumeration at different levels, and query provides general read-only execution. An agent can easily distinguish between these four functions.

Naming Consistency5/5

All tools follow a consistent 'mysql_verb_noun' pattern with snake_case throughout (e.g., mysql_describe_table, mysql_list_databases). This predictable naming scheme makes the tool set easy to navigate and understand.

Tool Count4/5

Four tools is a reasonable number for a read-only MySQL server, covering core operations like listing databases/tables, describing structure, and executing queries. It's slightly lean but well-scoped, with no obvious bloat or missing essentials for the stated purpose.

Completeness4/5

For a read-only MySQL server, the tool set covers key operations: enumeration (databases, tables), schema inspection (describe_table), and data retrieval (query). Minor gaps might include tools for viewing indexes or constraints, but agents can work around this with queries, making it largely complete.

Maintenance

ActivityInactive
ResponsivenessNo issues