{
  "markdown": "# MySQL MCP Server\n\nA high-quality Model Context Protocol (MCP) server implementation for MySQL databases. This server enables AI assistants like Claude to interact with MySQL databases through a standardized protocol.\n\n**Version**: 0.2.0 | **Protocol**: MCP 2025-03-26 | **Rust**: 1.70+ | **Status**: Production Ready\n\n## Table of Contents\n\n- [Features](#features)\n- [Installation](#installation)\n- [Quick Start (5 Minutes)](#quick-start-5-minutes)\n- [Usage](#usage)\n- [Available Tools](#available-tools)\n- [Database Context Feature](#database-context-feature)\n- [Security Considerations](#security-considerations)\n- [Architecture](#architecture)\n- [Troubleshooting](#troubleshooting)\n- [Development](#development)\n- [Deployment Guide](#deployment-guide)\n- [Contributing](#contributing)\n- [License](#license)\n- [Support](#support)\n\n## Features\n\n- **Schema Inspection**: Retrieve table schemas and structure information\n- **Query Execution**: Execute SQL queries (read-only by default for safety)\n- **Data Manipulation**: Insert, update, and delete operations\n- **Database Context**: Specify which database to use per query\n- **Safety Controls**: Configurable query restrictions to prevent dangerous operations\n- **Connection Management**: Robust connection handling with retry logic and pooling\n- **Error Handling**: Comprehensive error reporting with detailed messages\n- **JSON-RPC 2.0 Protocol**: Standardized communication via stdio\n\n## Installation\n\n### Prerequisites\n\n- Rust 1.70+\n- MySQL 5.7+ or MariaDB 10.2+\n- Access to a MySQL database\n\n### Building from Source\n\n```bash\ngit clone <repository-url>\ncd mcp-server-mysql\ncargo build --release\n```\n\nThe compiled binary will be available at `target/release/mcp-server-mysql`.\n\n### From Release Package\n\n```bash\n# Extract the package\ntar -xzf mcp-server-mysql-v0.2.0-linux-x86_64.tar.gz\n\n# Move binary to system path (optional)\nsudo cp mcp-server-mysql /usr/local/bin/\n\n# Verify installation\nmcp-server-mysql --version\n```\n\n## Quick Start (5 Minutes)\n\n### Step 1: Build the Server\n\n```bash\ncargo build --release\n```\n\nThe binary will be at `target/release/mcp-server-mysql`\n\n### Step 2: Test the Connection\n\n```bash\n./target/release/mcp-server-mysql \\\n  --host localhost \\\n  --username root \\\n  --password yourpassword \\\n  --database testdb\n```\n\nYou should see: \"MCP MySQL Server started and ready to accept connections\"\n\n### Step 3: Configure Claude Desktop\n\nEdit your Claude Desktop configuration file:\n\n- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`\n- **Windows**: `%APPDATA%\\Claude\\claude_desktop_config.json`\n\nAdd this configuration:\n\n```json\n{\n  \"mcpServers\": {\n    \"mysql\": {\n      \"command\": \"/absolute/path/to/mcp-server-mysql\",\n      \"args\": [\n        \"--host\", \"localhost\",\n        \"--port\", \"3306\",\n        \"--username\", \"your_username\",\n        \"--password\", \"your_password\",\n        \"--database\", \"your_database\"\n      ]\n    }\n  }\n}\n```\n\n**Security Note**: For production use, consider using environment variables or a secure secrets management solution instead of hardcoding passwords in the configuration file.\n\n### Step 4: Restart Claude Desktop\n\nClose and reopen Claude Desktop completely. You should see a small hammer icon indicating the MCP server is connected.\n\n### Step 5: Try it Out!\n\nAsk Claude:\n- \"Can you show me the schema for the users table in my MySQL database?\"\n- \"Query the database and show me the first 10 rows from the products table\"\n- \"What tables are in my database?\"\n\n## Usage\n\n### Command Line Arguments\n\n```bash\nmcp-server-mysql \\\n  --host localhost \\\n  --port 3306 \\\n  --username your_username \\\n  --password your_password \\\n  --database your_database \\\n  --allow-dangerous-queries false\n```\n\n### Arguments Reference\n\n| Argument | Description | Default | Required |\n|----------|-------------|---------|----------|\n| `--host` | MySQL server hostname | `localhost` | No |\n| `--port` | MySQL server port | `3306` | No |\n| `--username` | MySQL username | - | Yes |\n| `--password` | MySQL password | ` ` (empty) | No |\n| `--database` | Database name to connect to | - | Yes |\n| `--allow-dangerous-queries` | Allow INSERT/UPDATE/DELETE queries | `false` | No |\n\n### Configuration with Claude Desktop\n\nAdd this configuration to your Claude Desktop config file:\n\n**macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`\n**Windows**: `%APPDATA%\\Claude\\claude_desktop_config.json`\n\n```json\n{\n  \"mcpServers\": {\n    \"mysql\": {\n      \"command\": \"/path/to/mcp-server-mysql\",\n      \"args\": [\n        \"--host\", \"localhost\",\n        \"--port\", \"3306\",\n        \"--username\", \"your_username\",\n        \"--password\", \"your_password\",\n        \"--database\", \"your_database\"\n      ]\n    }\n  }\n}\n```\n\n## Available Tools\n\n### 1. mysql (Schema Inspection)\n\nRetrieve database schema information for tables.\n\n**Parameters:**\n- `table_name` (string): Name of the table to inspect, or `\"all-tables\"` to get all table schemas\n\n**Example:**\n```json\n{\n  \"table_name\": \"users\"\n}\n```\n\n**Returns:**\n- Column information (name, type, nullable, defaults, keys)\n- Index information\n- Table constraints\n\n### 2. query (SQL Execution)\n\nExecute SQL queries on the database.\n\n**Parameters:**\n- `query` (string): SQL query to execute\n- `database` (string, optional): Database name to use for this specific query\n\n**Example:**\n```json\n{\n  \"query\": \"SELECT * FROM users WHERE active = 1 LIMIT 10\",\n  \"database\": \"my_database\"\n}\n```\n\n**Safety:**\n- By default, only SELECT queries are allowed\n- Use `--allow-dangerous-queries` flag to enable INSERT/UPDATE/DELETE\n- Dangerous keywords are blocked unless explicitly enabled\n\n### 3. insert (Insert Data)\n\nInsert data into a specified table.\n\n**Parameters:**\n- `table_name` (string): Name of the table\n- `data` (object): Key-value pairs of column names and values\n\n**Example:**\n```json\n{\n  \"table_name\": \"users\",\n  \"data\": {\n    \"username\": \"john_doe\",\n    \"email\": \"john@example.com\",\n    \"active\": true\n  }\n}\n```\n\n**Returns:** Last insert ID\n\n### 4. update (Update Data)\n\nUpdate data in a specified table based on conditions.\n\n**Parameters:**\n- `table_name` (string): Name of the table\n- `data` (object): Key-value pairs of columns to update\n- `conditions` (object): Key-value pairs for WHERE clause\n\n**Example:**\n```json\n{\n  \"table_name\": \"users\",\n  \"data\": {\n    \"email\": \"newemail@example.com\",\n    \"updated_at\": \"2024-01-15 10:30:00\"\n  },\n  \"conditions\": {\n    \"id\": 123\n  }\n}\n```\n\n**Returns:** Number of affected rows\n\n### 5. delete (Delete Data)\n\nDelete data from a specified table based on conditions.\n\n**Parameters:**\n- `table_name` (string): Name of the table\n- `conditions` (object): Key-value pairs for WHERE clause\n\n**Example:**\n```json\n{\n  \"table_name\": \"users\",\n  \"conditions\": {\n    \"id\": 123\n  }\n}\n```\n\n**Returns:** Number of affected rows\n\n**Warning:** Always specify conditions to avoid deleting all rows!\n\n## Database Context Feature\n\n### The Problem\n\nPreviously, database context was not maintained between queries:\n\n```sql\n-- Query 1\nUSE dev_database;  -- Succeeds\n\n-- Query 2 (new connection from pool)\nSELECT * FROM my_table;  -- ❌ Fails: context was lost\n```\n\n### The Solution\n\nUse the optional `database` parameter on each query:\n\n```json\n{\n  \"query\": \"SELECT * FROM my_table\",\n  \"database\": \"dev_database\"\n}\n```\n\n### Benefits\n\n1. **Explicit and Clear**: Know exactly which database each query uses\n2. **No Hidden State**: Each query is independent\n3. **Backward Compatible**: Existing queries without parameter still work\n4. **No Race Conditions**: Each query gets its own connection\n5. **Simple to Use**: Just add `\"database\": \"name\"` to query arguments\n\n### Usage Examples\n\n#### Basic Query with Database Parameter\n\n```json\n{\n  \"query\": \"SELECT * FROM crm_sites LIMIT 10\",\n  \"database\": \"dev_smartConnect_za\"\n}\n```\n\n#### Query Without Database Parameter (Uses Default)\n\n```json\n{\n  \"query\": \"SELECT * FROM users WHERE active = 1\"\n}\n```\n\nUses the database specified in `--database` startup argument.\n\n#### Multiple Databases in Same Session\n\n```json\n// Query database 1\n{\n  \"query\": \"SELECT COUNT(*) FROM customers\",\n  \"database\": \"production_db\"\n}\n\n// Query database 2\n{\n  \"query\": \"SELECT COUNT(*) FROM test_data\",\n  \"database\": \"test_db\"\n}\n```\n\n#### Before vs After\n\n**Before (Required fully qualified names):**\n```sql\nSELECT * FROM dev_smartConnect_za.crm_sites\n  JOIN dev_smartConnect_za.crm_orgs ON ...\nWHERE dev_smartConnect_za.crm_sites.active = 1;\n```\n\n**After (Clean and simple):**\n```json\n{\n  \"query\": \"SELECT * FROM crm_sites JOIN crm_orgs ON ... WHERE active = 1\",\n  \"database\": \"dev_smartConnect_za\"\n}\n```\n\n### Common Scenarios\n\n#### Scenario 1: Single Database Project\n\nSet default database and omit the parameter:\n\n```bash\n# Startup\n--database my_project_db\n\n# Query (no database parameter needed)\n{\n  \"query\": \"SELECT * FROM users\"\n}\n```\n\n#### Scenario 2: Multiple Database Project\n\nSpecify database for each query:\n\n```json\n// Customer database\n{ \"query\": \"...\", \"database\": \"customers_db\" }\n\n// Orders database\n{ \"query\": \"...\", \"database\": \"orders_db\" }\n\n// Analytics database\n{ \"query\": \"...\", \"database\": \"analytics_db\" }\n```\n\n### Error Handling\n\n**Error Code -32005: Connection Acquisition Failed**\n```\nCause: Connection pool exhausted\nSolution: Retry after a moment\n```\n\n**Error Code -32006: Database Context Switch Failed**\n```\nCause: Database doesn't exist or user lacks permissions\nSolution: Verify database exists and user has access\n```\n\n### Best Practices\n\n✅ **DO**\n- Specify database explicitly for production queries\n- Use descriptive database names in your queries\n- Test with `SELECT DATABASE()` to verify context\n- Group queries by database for clarity\n\n❌ **DON'T**\n- Mix qualified and unqualified names in the same query\n- Assume persistence - specify database for each query\n- Use special characters in database names if possible\n- Forget to verify user permissions for all databases\n\n## Security Considerations\n\n### Read-Only Mode (Default)\n\nBy default, the server operates in read-only mode, allowing only SELECT queries. This prevents accidental data modification or deletion.\n\n### Dangerous Queries Mode\n\nEnable write operations with `--allow-dangerous-queries`:\n\n```bash\nmcp-server-mysql --username user --password pass --database mydb --allow-dangerous-queries true\n```\n\n**Use with caution!** This enables:\n- INSERT statements\n- UPDATE statements\n- DELETE statements\n- Other potentially destructive operations\n\n### SQL Injection Protection\n\n- Table names are validated to contain only alphanumeric characters and underscores\n- All data values are parameterized using prepared statements\n- Database names are escaped by replacing backticks with double backticks\n- No raw SQL concatenation is performed\n\n### Connection Security\n\n- Supports standard MySQL SSL/TLS connections\n- Connection strings can be configured securely\n- Passwords can be provided via environment variables\n- Consider using dedicated database users with limited permissions\n\n### Production Deployment Security\n\n1. **Use dedicated database user**:\n   ```sql\n   CREATE USER 'mcp_user'@'localhost' IDENTIFIED BY 'secure_password';\n   GRANT SELECT ON your_database.* TO 'mcp_user'@'localhost';\n   FLUSH PRIVILEGES;\n   ```\n\n2. **Enable write access only when needed**:\n   ```bash\n   --allow-dangerous-queries true  # Use with caution!\n   ```\n\n3. **Use environment variables** (future enhancement):\n   Consider wrapping the binary in a shell script that reads from env vars.\n\n## Architecture\n\n### System Overview\n\n```\n┌─────────────────────────────────────────────────────┐\n│           MCP Client (e.g., Claude)                 │\n│  Sends: {query, database}                           │\n└────────────────────────┬────────────────────────────┘\n                         │ JSON-RPC 2.0 (stdio)\n                         ▼\n┌─────────────────────────────────────────────────────┐\n│      MCP MySQL Server (Rust)                        │\n│                                                      │\n│  execute_query(query, database, pool)               │\n│  ├─ If database param:                              │\n│  │  ├─ Acquire connection from pool                 │\n│  │  ├─ Execute: USE `database`                      │\n│  │  └─ Execute: [user's query]                      │\n│  └─ Else:                                           │\n│     └─ Execute query on pool (default database)     │\n└────────────────────────┬────────────────────────────┘\n                         │\n                         ▼\n┌─────────────────────────────────────────────────────┐\n│      MySQL Connection Pool (5 connections)          │\n└────────────────────────┬────────────────────────────┘\n                         │\n                         ▼\n┌─────────────────────────────────────────────────────┐\n│      MySQL/MariaDB Server                           │\n└─────────────────────────────────────────────────────┘\n```\n\n### Sequence: Query with Database Parameter\n\n```\nClient          MCP Server       Connection Pool      MySQL Server\n  │                 │                    │                  │\n  │  query +        │                    │                  │\n  │  database       │                    │                  │\n  ├────────────────>│                    │                  │\n  │                 │                    │                  │\n  │                 │ acquire()          │                  │\n  │                 ├───────────────────>│                  │\n  │                 │ <connection>       │                  │\n  │                 │<───────────────────┤                  │\n  │                 │                    │                  │\n  │                 │ USE database       │                  │\n  │                 ├────────────────────┼─────────────────>│\n  │                 │ OK                 │                  │\n  │                 │<────────────────────┼──────────────────┤\n  │                 │                    │                  │\n  │                 │ SELECT query       │                  │\n  │                 ├────────────────────┼─────────────────>│\n  │                 │ Results            │                  │\n  │                 │<────────────────────┼──────────────────┤\n  │                 │                    │                  │\n  │                 │ release()          │                  │\n  │                 ├───────────────────>│                  │\n  │  Results        │                    │                  │\n  │<────────────────┤                    │                  │\n```\n\n### Connection Pool Management\n\n```\nPool (5 connections)\n┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐\n│ C1 │ │ C2 │ │ C3 │ │ C4 │ │ C5 │\n└────┘ └────┘ └────┘ └────┘ └────┘\n\nKey Properties:\n• Each query gets its own connection instance\n• Database context is set per connection, per query\n• No state persists between queries\n• Fully thread-safe and concurrent\n```\n\n### Technical Details\n\n- **Protocol Version**: MCP 2025-03-26\n- **Transport**: stdio (JSON-RPC 2.0)\n- **Connection Pooling**: Max 5 connections\n- **Retry Logic**: Automatic reconnection on transient failures\n- **Performance Overhead**: ~50-200 microseconds per query with database parameter\n\n## Troubleshooting\n\n### Connection Failures\n\nIf you encounter connection errors:\n\n1. **Check MySQL is running:**\n   ```bash\n   mysql -h localhost -u your_username -p\n   ```\n\n2. **Verify credentials:**\n   - Ensure the username and password are correct\n   - Confirm the user has access to the specified database\n\n3. **Check network access:**\n   - Verify the host and port are correct\n   - Ensure no firewall is blocking the connection\n\n4. **Review server logs:**\n   - The server logs to stderr\n   - Check for detailed error messages\n\n### Common Errors\n\n#### \"Database connection failed\"\n\n- MySQL server may not be running\n- Incorrect host/port configuration\n- Network connectivity issues\n\n#### \"Only SELECT queries are allowed\"\n\n- You're trying to run a write query in read-only mode\n- Add `--allow-dangerous-queries true` if write access is needed\n\n#### \"No database selected\"\n\n- The specified database doesn't exist\n- The user doesn't have access to the database\n- Check `SHOW DATABASES;` to see available databases\n\n#### \"Table doesn't exist\"\n\n- Verify you're querying the correct database\n- Add the `database` parameter if using multiple databases\n- Use `SELECT DATABASE()` to check current context\n\n#### \"Failed to acquire connection\"\n\n- Connection pool is exhausted\n- Wait a moment and retry\n\n### Tool not appearing in Claude Desktop\n\n1. Verify the path to the binary is absolute (not relative)\n2. Check Claude Desktop logs for errors\n3. Restart Claude Desktop completely (not just reload)\n4. Ensure the server process starts without errors when run manually\n\n## Development\n\n### Project Structure\n\n```\nmcp-server-mysql/\n├── src/\n│   ├── main.rs          # Main server implementation\n│   ├── config.rs        # Configuration handling\n│   ├── db.rs            # Database operations\n│   ├── rpc.rs           # RPC protocol handling\n│   └── server.rs        # Server initialization\n├── tests/               # Test files\n├── Cargo.toml           # Rust dependencies\n├── Cargo.lock          # Locked dependency versions\n└── README.md           # This file\n```\n\n### Building for Development\n\n```bash\ncargo build\ncargo run -- --help\n```\n\n### Running Tests\n\n```bash\ncargo test\n```\n\n### Code Quality\n\n```bash\n# Format code\ncargo fmt\n\n# Run linter\ncargo clippy\n\n# Check for issues\ncargo check\n```\n\n### Development Conventions\n\nThe project follows standard Rust best practices:\n- Code formatting: `cargo fmt`\n- Linting: `cargo clippy`\n- Testing: `cargo test`\n\n## Deployment Guide\n\n### Quick Deployment\n\n#### 1. Test Connection\n\n```bash\n./mcp-server-mysql \\\n  --username your_user \\\n  --password your_pass \\\n  --database your_db\n```\n\nPress Ctrl+C to exit after seeing \"MCP MySQL Server started\".\n\n#### 2. Configure Claude Desktop\n\nEdit your Claude config file and add the server configuration (see Quick Start section).\n\n#### 3. Restart Claude Desktop\n\nClose and reopen Claude Desktop completely.\n\n### Production Deployment Tips\n\n#### Performance\n\n- The binary is optimized with `--release` flag\n- Connection pooling is configured (max 5 connections)\n- Automatic retry logic for transient failures\n\n#### Monitoring\n\nServer logs go to stderr. Capture them with:\n\n```bash\n./mcp-server-mysql --username user --password pass --database db 2>> server.log\n```\n\nLog levels:\n- `INFO`: Connection events, tool calls\n- `DEBUG`: Detailed query information\n- `WARN`: Non-fatal issues\n- `ERROR`: Failures and errors\n\n### Systemd Service (Optional)\n\nFor long-running deployments, create `/etc/systemd/system/mcp-mysql.service`:\n\n```ini\n[Unit]\nDescription=MySQL MCP Server\nAfter=network.target mysql.service\n\n[Service]\nType=simple\nUser=mcp-user\nExecStart=/usr/local/bin/mcp-server-mysql --username mcp_user --password secret --database production\nRestart=on-failure\nRestartSec=5s\nStandardOutput=journal\nStandardError=journal\n\n[Install]\nWantedBy=multi-user.target\n```\n\nEnable and start:\n```bash\nsudo systemctl enable mcp-mysql\nsudo systemctl start mcp-mysql\nsudo systemctl status mcp-mysql\n```\n\n### Upgrading\n\n```bash\n# Backup current version\ncp /usr/local/bin/mcp-server-mysql /usr/local/bin/mcp-server-mysql.backup\n\n# Replace with new version\ncp mcp-server-mysql /usr/local/bin/\n\n# Restart services\nsudo systemctl restart mcp-mysql  # If using systemd\n# Or restart Claude Desktop\n```\n\n### Rollback\n\n```bash\n# Restore previous version\ncp /usr/local/bin/mcp-server-mysql.backup /usr/local/bin/mcp-server-mysql\n\n# Or checkout previous git tag\ngit checkout v0.1.0\ncargo build --release\n```\n\n## Contributing\n\nContributions are welcome! Please ensure:\n- Code follows Rust best practices\n- All tests pass\n- Documentation is updated\n- Commit messages are clear and descriptive\n\n## License\n\nApache-2.0\n\n## Support\n\nFor issues, questions, or contributions, please open an issue on the project repository.\n\n---\n\n**Version**: 0.2.0 | **Release Date**: 2025-01-XX | **Protocol**: MCP 2025-03-26 | **Platform**: Linux x86_64 | **Status**: Production Ready ✅\n",
  "bytes": 20038,
  "sha": "e217b3faf19741f7c72d8d103372c6bf809f7676aefa7b774ca399405f9505f1",
  "repo_slug": "codechap/mcp-server-mysql",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_codechap_mysql_4a98ded8/readme"
}