@yidun/mysql-mcp-server
v1.0.1
Published
MySQL MCP Server - Model Context Protocol server for MySQL database read-only access
Downloads
161
Readme
MySQL MCP 服务器
MySQL MCP 服务器是一个基于模型上下文协议(MCP)的服务器实现,为 AI 编程助手提供对 MySQL 数据库的只读访问能力。
特性
- ✅ 只读访问: 严格限制只读操作,确保数据库安全
- 🔒 安全验证: 自动检测和阻止写入操作、SQL 注入尝试
- 🚀 无状态设计: 每次查询独立执行,不维护连接状态
- 📊 完整的数据库访问: 支持表列表、表结构、数据查询
- 🎯 类型安全: 完整的 TypeScript 类型定义
- ⚡ 性能优化: 表结构缓存、预编译语句
- 🛠️ MCP 协议: 标准 MCP 工具接口,易于集成
安装
npm install @yidun/mysql-mcp-server快速开始
配置 Claude Desktop
在 Claude Desktop 配置文件中添加:
{
"mcpServers": {
"mysql": {
"command": "node",
"args": [
"/path/to/mysql-mcp-server/dist/index.js"
],
"env": {
"MYSQL_MAX_ROWS": "1000",
"MYSQL_QUERY_TIMEOUT": "30000",
"MYSQL_CACHE_TTL": "300"
}
}
}
}环境变量
MYSQL_MAX_ROWS: 单次查询返回的最大行数(默认: 1000)MYSQL_QUERY_TIMEOUT: 查询超时时间,单位毫秒(默认: 30000)MYSQL_CACHE_TTL: 表结构缓存过期时间,单位秒(默认: 300)
MCP 工具
1. list_tables
列出数据库中的所有表。
参数:
{
host: string; // 数据库主机地址
port: number; // 数据库端口
user: string; // 用户名
password: string; // 密码
database: string; // 数据库名
}返回:
{
tables: TableInfo[];
count: number;
}2. describe_table
查询指定表的结构信息。
参数:
{
host: string;
port: number;
user: string;
password: string;
database: string;
tableName: string; // 表名
}返回:
{
tableName: string;
columns: ColumnInfo[];
indexes: IndexInfo[];
constraints: ConstraintInfo[];
}3. query_table
查询指定表的数据。
参数:
{
host: string;
port: number;
user: string;
password: string;
database: string;
tableName: string;
where?: string; // WHERE 条件
orderBy?: string; // 排序字段
limit?: number; // 返回行数限制
offset?: number; // 偏移量
}返回:
{
columns: string[];
rows: Record<string, any>[];
rowCount: number;
executionTime: number;
}4. execute_query
执行自定义只读 SQL 查询。
参数:
{
host: string;
port: number;
user: string;
password: string;
database: string;
sql: string; // SQL 查询语句
}返回:
{
columns: string[];
rows: Record<string, any>[];
rowCount: number;
executionTime: number;
}安全特性
只读操作限制
系统会自动拒绝以下操作:
- 写入操作: INSERT, UPDATE, DELETE, REPLACE
- 结构修改: CREATE, ALTER, DROP, TRUNCATE
- 权限操作: GRANT, REVOKE
- 存储过程和函数调用
SQL 注入防护
- 使用预编译语句执行查询
- 验证所有用户输入
- 使用白名单验证表名和字段名
敏感信息保护
- 密码在日志中自动掩码
- 不在错误消息中暴露连接详情
开发
安装依赖
npm install开发模式
npm run dev构建
npm run build测试
# 运行所有测试
npm test
# 监视模式
npm run test:watch
# 生成覆盖率报告
npm run test:coverage代码检查
# 检查代码
npm run lint
# 自动修复
npm run lint:fix项目结构
mysql-mcp-server/
├── src/
│ ├── index.ts # 应用入口点
│ ├── types/ # TypeScript 类型定义
│ ├── server/ # MCP 服务器实现
│ ├── mysql/ # MySQL 客户端
│ ├── security/ # 安全验证
│ ├── error/ # 错误处理
│ ├── cache/ # 缓存管理
│ ├── integration/ # 集成测试
│ └── performance/ # 性能测试
├── dist/ # 构建输出
├── package.json
├── tsconfig.json
└── README.md技术栈
- 运行时: Node.js >= 18.0.0
- 语言: TypeScript 5.0+
- MCP SDK: @modelcontextprotocol/sdk ^0.5.0
- MySQL 驱动: mysql2 ^3.6.0
- 缓存: node-cache ^5.1.2
- 测试框架: Vitest 1.0+
- 属性测试: fast-check ^3.15.0
许可证
MIT
贡献
欢迎提交 Issue 和 Pull Request!
支持
如有问题,请访问 GitHub Issues
