MySQL Database Server

MySQL Database Server

Enables secure MySQL database operations through natural language with built-in safety features. Supports SELECT queries by default while providing configurable restrictions for INSERT, UPDATE, and DELETE operations.

Category
访问服务器

README

MCP MySQL Server

A Model Context Protocol (MCP) server for MySQL database operations with built-in safety features and operation resistance. Perfect for use with Claude Code, Codex CLI, and other MCP-compatible AI assistants.

Features

  • Safe MySQL Operations: Execute SELECT queries freely while controlling destructive operations
  • Operation Resistance: Configurable INSERT, UPDATE, and DELETE restrictions
  • Schema Protection: DROP, TRUNCATE, and ALTER operations are always blocked
  • SQL Injection Prevention: Uses prepared statements with parameter binding
  • Multiple Tools: Query execution, table listing, schema inspection, and database info
  • Connection Pooling: Efficient connection management for better performance
  • Detailed Error Reporting: Clear error messages with SQL codes

Quick Start

Option 1: Automated Setup (Easiest)

# One command - does everything!
./setup.sh

The script will:

  • Auto-detect Bun or npm
  • Install dependencies
  • Create and optionally configure .env
  • Build the project
  • Test database connection

Option 2: Manual Setup

Using Bun (Faster):

bun install
cp .env.example .env && nano .env
bun run build

Using npm:

npm install
cp .env.example .env && nano .env
npm run build

Integration Guides

Configuration

Environment Variables

Create a .env file (use .env.example as a template):

# MySQL Connection
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=your_username
MYSQL_PASS=your_password
MYSQL_DB=your_database

# Operation Permissions (true/false)
ALLOW_INSERT_OPERATION=false
ALLOW_UPDATE_OPERATION=false
ALLOW_DELETE_OPERATION=false

MCP Client Configuration

For Claude Code, add to your ~/.config/claude-code/.mcp.json:

{
  "mcpServers": {
    "mysql": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-mysql-server/dist/index.js"],
      "env": {
        "MYSQL_HOST": "localhost",
        "MYSQL_PORT": "3306",
        "MYSQL_USER": "your_username",
        "MYSQL_PASS": "your_password",
        "MYSQL_DB": "your_database",
        "ALLOW_INSERT_OPERATION": "false",
        "ALLOW_UPDATE_OPERATION": "false",
        "ALLOW_DELETE_OPERATION": "false"
      }
    }
  }
}

Need more examples? See docs/mcp-config-examples.md for:

  • Multiple databases
  • Remote/Docker configurations
  • Development vs production setups
  • Platform-specific paths

See the integration guides for detailed setup instructions.

Safety Features

Always Blocked Operations

These operations are always blocked regardless of configuration:

  • DROP - Dropping tables/databases
  • TRUNCATE - Truncating tables
  • ALTER - Altering table structure

Configurable Operations

Control these operations via environment variables:

  • INSERT - Controlled by ALLOW_INSERT_OPERATION
  • UPDATE - Controlled by ALLOW_UPDATE_OPERATION
  • DELETE - Controlled by ALLOW_DELETE_OPERATION

Always Allowed Operations

  • SELECT - Reading data is always permitted

Available Tools

1. mysql_query

Execute SQL queries with safety restrictions.

Parameters:

  • query (string, required): The SQL query to execute
  • params (array, optional): Parameters for prepared statement

Example:

{
  "query": "SELECT * FROM users WHERE id = ?",
  "params": [123]
}

Response:

{
  "success": true,
  "rows": [...],
  "rowCount": 5,
  "fields": [...]
}

2. mysql_list_tables

List all tables in the current database.

Example Response:

{
  "success": true,
  "tables": [
    { "Tables_in_db": "users" },
    { "Tables_in_db": "products" }
  ]
}

3. mysql_describe_table

Get the structure/schema of a specific table.

Parameters:

  • table (string, required): Table name

Example Response:

{
  "success": true,
  "table": "users",
  "columns": [
    {
      "Field": "id",
      "Type": "int",
      "Null": "NO",
      "Key": "PRI",
      "Default": null,
      "Extra": "auto_increment"
    }
  ]
}

4. mysql_get_database_info

Get information about the database connection and permissions.

Example Response:

{
  "success": true,
  "connection": {
    "host": "localhost",
    "port": 3306,
    "user": "tommygun",
    "database": "db"
  },
  "permissions": {
    "INSERT": false,
    "UPDATE": false,
    "DELETE": false,
    "SELECT": true,
    "DROP": false,
    "TRUNCATE": false,
    "ALTER": false
  }
}

Usage Examples

For comprehensive examples, see examples/usage-examples.md.

Quick Examples

Safe SELECT Query:

Get the first 10 users from the database

Parameterized Query (Prevents SQL Injection):

Find products where category is 'electronics' and price is less than 1000

Data Analysis:

Show me monthly revenue for the last 6 months

Schema Exploration:

What tables are in my database?
Show me the structure of the users table

Blocked Operations

When operations are disabled, you'll receive clear error messages:

{
  "error": "INSERT operations are disabled. Set ALLOW_INSERT_OPERATION=true to enable.",
  "blocked": true
}

Enabling Write Operations

To enable write operations, update your .env:

# Enable INSERT operations
ALLOW_INSERT_OPERATION=true

# Enable UPDATE operations
ALLOW_UPDATE_OPERATION=true

# Enable DELETE operations (use with caution!)
ALLOW_DELETE_OPERATION=true

After changing permissions, restart the MCP server.

Security Best Practices

  1. Default to Read-Only: Keep write operations disabled unless specifically needed
  2. Use Prepared Statements: Always use the params array for user input
  3. Validate Table Names: The server validates table names in describe operations
  4. Schema Protection: DROP/TRUNCATE/ALTER are permanently blocked
  5. Connection Pooling: Uses connection pooling for better performance and resource management

Error Handling

The server provides detailed error responses:

{
  "error": "Table 'db.nonexistent' doesn't exist",
  "code": "ER_NO_SUCH_TABLE",
  "sqlState": "42S02"
}

Testing and Verification

Quick Tests

Once connected to your MCP client, try these commands:

  1. Check Connection:

    Show me the MySQL database information
    
  2. List Tables:

    What tables are in my database?
    
  3. Test Safety Features:

    Try to insert a test record into any table
    

    (Should be blocked with a clear error message)

  4. Query Data:

    Show me sample data from the users table
    

Verification Checklist

  • [ ] Server shows as connected in MCP client
  • [ ] Database connection info displays correctly
  • [ ] Table listing works
  • [ ] SELECT queries execute successfully
  • [ ] INSERT/UPDATE/DELETE are blocked (default)
  • [ ] Clear error messages for blocked operations

For detailed testing examples, see examples/usage-examples.md.

Development

# Build the project
npm run build

# Run the server directly (for testing)
npm start

# Build and run
npm run dev

# Watch mode (if needed)
npm run build -- --watch

Project Structure

mcp-mysql-server/
├── src/
│   └── index.ts          # Main server implementation
├── dist/                 # Compiled JavaScript output
├── examples/             # Integration guides and examples
│   ├── claude-code-setup.md
│   ├── codex-cli-setup.md
│   └── usage-examples.md
├── .env.example          # Environment template
├── package.json
├── tsconfig.json
└── README.md

Contributing

See CONTRIBUTING.md for development guidelines.

Troubleshooting

Connection Issues

  • Verify MySQL is running: mysql -u username -p
  • Check host/port configuration
  • Verify user credentials
  • Ensure database exists

Permission Errors

  • Check MySQL user has required permissions
  • Verify ALLOW_*_OPERATION settings match your needs

Tool Not Found

  • Ensure the server is properly configured in .mcp.json
  • Verify the build succeeded: ls -la dist/index.js
  • Check MCP client can find the server

Resources

Support

  • Issues: Report bugs or request features via GitHub issues
  • Questions: Check the examples directory for common use cases
  • Security: For security concerns, please email the maintainers

Changelog

Version 1.0.0

  • Initial release
  • Basic MySQL operations (SELECT, INSERT, UPDATE, DELETE)
  • Safety features and operation resistance
  • Prepared statements for SQL injection prevention
  • Connection pooling
  • Comprehensive documentation

License

MIT - see LICENSE file for details

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选