logo
Free, unlimited AI code reviews that run on commit
git-lrc git-lrc GitHub Install Now We'd appreciate a star git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

mcp-data-accessor-mysql

Facilitates secure, read-only interaction with relational MySQL datastores, allowing introspection of table structures and execution of safe SQL retrieval operations.

Author

mcp-data-accessor-mysql logo

benborla

MIT License

Quick Info

GitHub GitHub Stars 840
NPM Weekly Downloads 0
Tools 1
Last Updated 2026-02-19

Tags

mysqldatabasedatabasesmysql providesaccess mysqlserver mysql

Model Context Protocol Adapter for MySQL (Claude Edition)

⭐ Enhanced fork focused on robust LLM integration and secure SSH tunneling. Source Attribution: Inspired by @benborla29's original work. Upstream Repository: https://github.com/benborla/mcp-server-mysql Licensing: MIT

NodeJS-based MySQL Interface for MCP

Quality Assurance Badge

Key Customizations & Enhancements:

  • 💡 LLM Optimization: Tailored for seamless deployment within Anthropic's Claude Code environment.
  • 🌐 Secure Tunnelling: Native support baked in for establishing secure SSH connections to remote database instances.
  • 🔄 Lifecycle Hooks: Automated management of SSH tunnels synchronized with Claude's start/stop events.
  • 🛠️ Schema Modification Control: Introduces MYSQL_DISABLE_READ_ONLY_TRANSACTIONS flag to conditionally permit CREATE TABLE or similar DDL commands.
  • 🏗️ Multi-Context Support: Simplified setup enabling configuration for numerous projects, each potentially pointing to distinct backing databases.

Quick Deployment Guide for Claude Code Users:

  1. Initial Setup: Consult PROJECT_SETUP_GUIDE.md for comprehensive prerequisites.
  2. Tunnel Configuration: Establish connection details for required remote database access points.
  3. Claude Integration: The server module integrates effortlessly with the Claude Code workflow.

A Model Context Protocol service providing programmatic access to MySQL backends, secured often via SSH connections. This module empowers AI agents to examine data structures and securely run non-mutating SQL queries.

Prerequisites

  • Node.js runtime, version 20 or later.
  • MySQL server instance, version 5.7 minimum (8.0+ highly suggested).
  • A dedicated MySQL credential set possessing necessary query execution privileges.
  • Credentials granting INSERT, UPDATE, and/or DELETE rights are mandatory only if write enablement is configured.

Installation

Via Smithery

The most straightforward setup path involves using the Smithery registry:

smithery configure @benborla29/mcp-server-mysql

Cursor IDE

To integrate with Cursor IDE:

  1. Navigate to the Smithery entry: https://smithery.ai/server/@benborla29/mcp-server-mysql
  2. Adhere to the instructions specifically outlined for Cursor deployment.

MCP Get acts as a central catalog, streamlining the onboarding of these server definitions.

Claude Code Integration

Method A: Import from Existing Claude Desktop Setup (Preferred)

If already cataloged in your Claude Desktop profile, import via:

claude mcp add-from-claude-desktop

This launches an interactive interface for selecting and importing the mcp_server_mysql configuration.

Method B: Manual Setup

Global Package Installation (NPM/PNPM):

Install the package globally on your system:

# Using npm
npm install -g @benborla29/mcp-server-mysql

# Using pnpm
pnpm add -g @benborla29/mcp-server-mysql

Then register the server with the Claude CLI, specifying required environmental parameters:

claude mcp add mcp_server_mysql \
  -e MYSQL_HOST="127.0.0.1" \
  -e MYSQL_PORT="3306" \
  -e MYSQL_USER="root" \
  -e MYSQL_PASS="your_password" \
  -e MYSQL_DB="your_database" \
  -e ALLOW_INSERT_OPERATION="false" \
  -e ALLOW_UPDATE_OPERATION="false" \
  -e ALLOW_DELETE_OPERATION="false" \
  -- npx @benborla29/mcp-server-mysql

Running from Source Repository:

If running directly from a checked-out folder:

claude mcp add mcp_server_mysql \
  -e MYSQL_HOST="127.0.0.1" \
  -e MYSQL_PORT="3306" \
  -e MYSQL_USER="root" \
  -e MYSQL_PASS="your_password" \
  -e MYSQL_DB="your_database" \
  -e ALLOW_INSERT_OPERATION="false" \
  -e ALLOW_UPDATE_OPERATION="false" \
  -e ALLOW_DELETE_OPERATION="false" \
  -e PATH="/path/to/node/bin:/usr/bin:/bin" \
  -e NODE_PATH="/path/to/node/lib/node_modules" \
  -- /path/to/node /full/path/to/mcp-server-mysql/dist/index.js

Substitution Notes: Replace placeholders with actual paths (which node helps find the Node binary path).

Unix Socket Connection (For local MySQL):

claude mcp add mcp_server_mysql \
  -e MYSQL_SOCKET_PATH="/tmp/mysql.sock" \
  -e MYSQL_USER="root" \
  -e MYSQL_PASS="your_password" \
  -e MYSQL_DB="your_database" \
  -e ALLOW_INSERT_OPERATION="false" \
  -e ALLOW_UPDATE_OPERATION="false" \
  -e ALLOW_DELETE_OPERATION="false" \
  -- npx @benborla29/mcp-server-mysql

Scoping Selection

Determine the appropriate scope for registration:

# Local scope (Default): Limited to the current workspace context
claude mcp add mcp_server_mysql [options...]

# User scope: Accessible across all your projects
claude mcp add mcp_server_mysql -s user [options...]

# Project scope: Shared via configuration in .mcp.json for team use
claude mcp add mcp_server_mysql -s project [options...]

For credentialed database endpoints, local or user scope is strongly advised for credential isolation.

Validation Check

Confirm successful integration:

# List all registered servers
claude mcp list

# Retrieve specific server metadata
claude mcp get mcp_server_mysql

# Check operational status within the Claude Code environment
/mcp

Multi-Database Setup

To activate multi-database functionality, simply omit the -e MYSQL_DB parameter:

claude mcp add mcp_server_mysql_multi \
  -e MYSQL_HOST="127.0.0.1" \
  -e MYSQL_PORT="3306" \
  -e MYSQL_USER="root" \
  -e MYSQL_PASS="your_password" \
  -e MULTI_DB_WRITE_MODE="false" \
  -- npx @benborla29/mcp-server-mysql

Extensive Parameterization

Advanced behavioral tuning can be achieved using supplementary environment variables:

claude mcp add mcp_server_mysql \
  -e MYSQL_HOST="127.0.0.1" \
  -e MYSQL_PORT="3306" \
  -e MYSQL_USER="root" \
  -e MYSQL_PASS="your_password" \
  -e MYSQL_DB="your_database" \
  -e MYSQL_POOL_SIZE="10" \
  -e MYSQL_QUERY_TIMEOUT="30000" \
  -e MYSQL_CACHE_TTL="60000" \
  -e MYSQL_RATE_LIMIT="100" \
  -e MYSQL_SSL="true" \
  -e ALLOW_INSERT_OPERATION="false" \
  -e ALLOW_UPDATE_OPERATION="false" \
  -e ALLOW_DELETE_OPERATION="false" \
  -e MYSQL_ENABLE_LOGGING="true" \
  -- npx @benborla29/mcp-server-mysql

Debugging Claude Code Setup Issues

  1. Connectivity Failure: Use the /mcp command in Claude Code to confirm server reachability and authentication status.

  2. Path Resolution: When using a source checkout, verify the absolute paths for Node.js binaries are accurately supplied:

```bash # Locate Node binary which node

# Suggested PATH augmentation echo "$(which node)/../"

# Suggested NODE_PATH augmentation echo "$(which node)/../../lib/node_modules" ```

  1. Access Denied: Confirm the MySQL user possesses the minimum required database privileges for the intended actions.

  2. Startup Failure: Execute the server process standalone to isolate connection/configuration errors:

bash npx @benborla29/mcp-server-mysql

Manual Setup (NPM/PNPM)

For environments where direct CLI registration is inconvenient:

# Using npm
npm install -g @benborla29/mcp-server-mysql

# Using pnpm
pnpm add -g @benborla29/mcp-server-mysql

Post-installation, manual configuration within the LLM application's context is required (refer to the Configuration section).

Local Source Execution

To run and develop directly from a cloned source tree:

  1. Clone: Obtain the repository locally

bash git clone https://github.com/benborla/mcp-server-mysql.git cd mcp-server-mysql

  1. Dependencies: Install required modules

bash npm install # or pnpm install

  1. Compile: Build the project artifacts

bash npm run build # or pnpm run build

  1. Claude Desktop Registration: Update your Claude Desktop configuration file (claude_desktop_config.json):

json { "mcpServers": { "mcp_server_mysql": { "command": "/path/to/node", "args": [ "/full/path/to/mcp-server-mysql/dist/index.js" ], "env": { "MYSQL_HOST": "127.0.0.1", "MYSQL_PORT": "3306", "MYSQL_USER": "root", "MYSQL_PASS": "your_password", "MYSQL_DB": "your_database", "ALLOW_INSERT_OPERATION": "false", "ALLOW_UPDATE_OPERATION": "false", "ALLOW_DELETE_OPERATION": "false", "PATH": "/Users/atlasborla/Library/Application Support/Herd/config/nvm/versions/node/v22.9.0/bin:/usr/bin:/bin", "NODE_PATH": "/Users/atlasborla/Library/Application Support/Herd/config/nvm/versions/node/v22.9.0/lib/node_modules" } } } }

Crucial paths must be substituted with your system's absolute locations.

  1. Verification: Test direct execution:

bash node dist/index.js

Remote Access Mode

For deployment as a remotely accessible MCP endpoint, define necessary secrets via environment variables in a local .env file.

  1. Create Environment File

bash touch .env

  1. Populate Variables: Copy structure from the repository's example file. Configure MySQL details, ensure IS_REMOTE_MCP=true, and set a robust REMOTE_SECRET_KEY.
  2. Load Session Variables:

bash source .env

  1. Launch Server:

bash npx @benborla29/mcp-server-mysql

  1. Agent Configuration: Point the consuming agent to the remote endpoint using a structure similar to this:

json { "mcpServers": { "mysql": { "url": "http://your-host:3000/mcp", "type": "streamableHttp", "headers": { "Authorization": "Bearer <REMOTE_SECRET_KEY>" } } } }

Core Components

Exposed Tools

  • mysql_query
  • Action: Executes specified SQL queries against the linked data repository.
  • Input: sql (string): The SQL command or statement.
  • Default Security: Strictly read-only access.
  • Optional Write Capabilities (Requires configuration): INSERT, UPDATE, DELETE permissions can be conditionally enabled.
  • Reliability: Operations are wrapped in transaction boundaries with fail-safe commit/rollback logic.
  • Security: Utilizes parameterized queries to mitigate SQL injection risks.
  • Tuning: Configurable limits on execution time and result set size.

Available Information Resources

The service exposes deep insights into the database structure:

  • Table Schemas Endpoint
  • Detailed JSON representations of every table structure.
  • Includes column definitions, data types, indexing schemes, and constraint mapping.
  • Provides runtime table metrics and statistics.
  • Structure discovery is fully automated via introspection.

Security Framework

  • Defense against SQL injection via mandatory prepared statements.
  • Mechanisms for whitelisting/blacklisting permissible queries.
  • Throttling query submission frequency (Rate Limiting).
  • Heuristics for evaluating query complexity.
  • Optional encryption layer enforcement (SSL/TLS).
  • Default read-only enforcement on data manipulation.

Operational Performance Features

  • Efficient connection management via pooling.
  • Result set caching with Time-To-Live (TTL).
  • Streaming support for handling large result data payloads.
  • Query execution plan analysis integration.

Observability and Diagnostics

  • Extensive logging of query activity.
  • Collection of key operational performance indicators.
  • Integrated error tracking and reporting pipeline.
  • Server health check endpoint availability.

Configuration Details

Smithery Automated Setup

Installation via Smithery automatically handles initial configuration. Adjustments can be made using:

smithery configure @benborla29/mcp-server-mysql

When reconfiguring, you manage core connection parameters (Host, Port, Credentials, DB name) and granular write access controls:

  • Connection Parameters:
  • MySQL Host, Port, User, Pass, Database Name.
  • SSL/TLS negotiation settings.

  • Write Permissions Toggle:

  • Allow INSERT Operations: Enable data appendage.
  • Allow UPDATE Operations: Enable modification of existing records.
  • Allow DELETE Operations: Enable record removal.

Security Posture: Write operations are OFF by default. Activate only when the LLM's need to modify data is necessary and trusted.

Extended Parameterization

For granular control over server behavior, modify the client configuration object:

{
  "mcpServers": {
    "mcp_server_mysql": {
      "command": "/path/to/npx/binary/npx",
      "args": [
        "-y",
        "@benborla29/mcp-server-mysql"
      ],
      "env": {
        // Basic Credentials
        "MYSQL_HOST": "127.0.0.1",
        "MYSQL_PORT": "3306",
        "MYSQL_USER": "root",
        "MYSQL_PASS": "",
        "MYSQL_DB": "db_name",
        "PATH": "/path/to/node/bin:/usr/bin:/bin",

        // Performance tuning
        "MYSQL_POOL_SIZE": "10",
        "MYSQL_QUERY_TIMEOUT": "30000",
        "MYSQL_CACHE_TTL": "60000",

        // Security tuning
        "MYSQL_RATE_LIMIT": "100",
        "MYSQL_MAX_QUERY_COMPLEXITY": "1000",
        "MYSQL_SSL": "true",

        // Logging/Monitoring
        "ENABLE_LOGGING": "true",
        "MYSQL_LOG_LEVEL": "info",
        "MYSQL_METRICS_ENABLED": "true",

        // Write flags
        "ALLOW_INSERT_OPERATION": "false",
        "ALLOW_UPDATE_OPERATION": "false",
        "ALLOW_DELETE_OPERATION": "false"
      }
    }
  }
}

Runtime Environment Variables

Core Connection Settings

  • MYSQL_SOCKET_PATH: Absolute path for a Unix domain socket connection (overrides Host/Port).
  • MYSQL_HOST: Network address for the MySQL server (Default: "127.0.0.1").
  • MYSQL_PORT: TCP port (Default: "3306").
  • MYSQL_USER: Access username (Default: "root").
  • MYSQL_PASS: Authentication secret.
  • MYSQL_DB: The specific database catalog to default to (Empty string activates Multi-DB Mode).

Performance Tuning Controls

  • MYSQL_POOL_SIZE: Maximum concurrent connections (Default: "10").
  • MYSQL_QUERY_TIMEOUT: Maximum query execution time in milliseconds (Default: "30000").
  • MYSQL_CACHE_TTL: Duration results are cached (ms) (Default: "60000").

Security Controls

  • MYSQL_RATE_LIMIT: Maximum queries permitted per sixty seconds (Default: "100").
  • MYSQL_MAX_QUERY_COMPLEXITY: Threshold for blocking overly complex operations (Default: "1000").
  • MYSQL_SSL: Boolean flag to enforce TLS/SSL connectivity (Default: "false").
  • Write Operation Flags: ALLOW_INSERT_OPERATION, ALLOW_UPDATE_OPERATION, ALLOW_DELETE_OPERATION (All default to "false").
  • MYSQL_DISABLE_READ_ONLY_TRANSACTIONS: [CRITICAL] Bypasses read-only transaction locking, potentially enabling DDL/Write operations if other flags are set (Default: "false"). ⚠️ Caution: Use only when total trust is established.
  • Schema-Specific Override Variables: SCHEMA_INSERT_PERMISSIONS, SCHEMA_UPDATE_PERMISSIONS, etc., for per-database access definitions.
  • MULTI_DB_WRITE_MODE: Activates write permissions across all accessible DBs in Multi-DB mode (Default: "false").

Telemetry Settings

  • MYSQL_ENABLE_LOGGING: Activates query recording (Default: "false").
  • MYSQL_LOG_LEVEL: Verbosity level for system output (e.g., "debug", "info").
  • MYSQL_METRICS_ENABLED: Toggles internal performance counter emission (Default: "false").

Remote Access Configuration

  • IS_REMOTE_MCP: Activates the remote serving mode (Default: "false").
  • REMOTE_SECRET_KEY: Required token for external agents to authenticate (If absent, remote mode fails securely).
  • PORT: The network port the remote server listens on (Default: 3000).

Multi-DB Mode Operation

This mode allows the service to interact with any database accessible by the underlying MySQL credentials when MYSQL_DB is unset.

Activation Protocol

Set MYSQL_DB to an empty string ("") to engage federated database access.

In this mode, all queries must explicitly name the target schema:

-- Full qualification required
SELECT * FROM catalog_schema.data_table;

-- Or switch context dynamically
USE secondary_catalog;
SELECT * FROM local_table;

Documentation for advanced multi-DB scenarios is available at README-MULTI-DB.md.

Granular Security Policies

To impose precise access restrictions per catalog, utilize schema-level permission environment variables. This overrides global write flags for specific targets.

Policy Definition Format

Permissions are defined as a comma-separated list mapping schema names to boolean flags:

SCHEMA_INSERT_PERMISSIONS=dev_db:true,staging_db:true,prod_db:false
SCHEMA_UPDATE_PERMISSIONS=dev_db:true,staging_db:true,prod_db:false
SCHEMA_DELETE_PERMISSIONS=dev_db:false,staging_db:true,prod_db:false
SCHEMA_DDL_PERMISSIONS=dev_db:false,staging_db:true,prod_db:false

Consult README-MULTI-DB.md for security best practices regarding this feature.

Validation Routines

Test Environment Seeding

Ensure the testing environment is prepared with structures and data:

  1. Establish Test Database & User

```sql -- Setup executed as root user CREATE DATABASE IF NOT EXISTS mcp_test;

-- Create dedicated, secure test credentials CREATE USER IF NOT EXISTS 'mcp_test'@'localhost' IDENTIFIED BY 'mcp_test_password'; GRANT ALL PRIVILEGES ON mcp_test.* TO 'mcp_test'@'localhost'; FLUSH PRIVILEGES; ```

  1. Execute Seeding Script

bash # Runs the database initialization script pnpm run setup:test:db

  1. Configure Test Parameters Create a .env.test file in the root directory if missing:

env MYSQL_HOST=127.0.0.1 MYSQL_PORT=3306 MYSQL_USER=mcp_test MYSQL_PASS=mcp_test_password MYSQL_DB=mcp_test

  1. Update package.json Scripts Ensure testing lifecycle hooks are defined:

json { "scripts": { "setup:test:db": "ts-node scripts/setup-test-db.ts", "pretest": "pnpm run setup:test:db", "test": "vitest run", "test:watch": "vitest", "test:coverage": "vitest run --coverage" } }

Running Tests

Execute the automated reliability checks:

# Initial setup required
pnpm run setup:test:db

# Execute full test suite
pnpm test

Running Evals

The integrated evaluation framework loads an MCP client, removing the need for manual recompilation between runs. Environment variables are passed via shell prefixing. Detailed instructions are available at MCP Evals.

OPENAI_API_KEY=your-key  npx mcp-eval evals.ts index.ts

Issue Resolution

Pervasive Problems

  1. Connection Failures
  2. Confirm MySQL service daemon responsiveness.
  3. Double-check all authentication parameters and associated user privileges.
  4. Verify SSL settings align with server requirements.
  5. Sanity check connectivity using a native MySQL client utility.

  6. Degraded Performance

  7. Fine-tune the connection pool size.
  8. Adjust query timeout thresholds.
  9. Activate result caching for frequently accessed data.
  10. Review query complexity limits.

  11. Security Enforcement Triggers

  12. Inspect rate limiting statistics.
  13. Review query whitelist/blacklist definitions.
  14. Confirm SSL/TLS configuration validity.
  15. Verify MySQL user rights match enabled features.

  16. Binary Path Resolution Errors If connection fails due to binary location ambiguity, explicitly define the execution paths:

json { "env": { "PATH": "/path/to/node/bin:/usr/bin:/bin" } }

Locating system binaries:

For PATH augmentation:

bash echo "$(which node)/../"

For NODE_PATH augmentation:

bash echo "$(which node)/../../lib/node_modules"

  1. Claude Desktop Specific Pitfalls
  2. If logs show "Server disconnected," examine the local log file: ~/Library/Logs/Claude/mcp-server-mcp_server_mysql.log
  3. Guarantee absolute file system paths are used for both the Node interpreter and the server script.
  4. Confirm environmental variables, especially secrets, are correctly loaded; override with direct settings if necessary.
  5. Enabling Writes: If modification is required, ensure configuration reflects this:

    json "env": { "ALLOW_INSERT_OPERATION": "true", "ALLOW_UPDATE_OPERATION": "true", "ALLOW_DELETE_OPERATION": "true" }

  6. Use the direct execution configuration structure for precise control:

    json { "mcpServers": { "mcp_server_mysql": { "command": "/full/path/to/node", "args": [ "/full/path/to/mcp-server-mysql/dist/index.js" ], "env": { // ... credentials ... } } } }

  7. Authentication Mismatch (MySQL 8.0+)

  8. The server must support the caching_sha2_password mechanism.
  9. If issues persist, consider migrating the user to the legacy authentication method:

    sql CREATE USER 'user'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

    Credit to @lizhuangs for this insight.

  10. Dependency Resolution Error: Encountering Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'dotenv'? Use this execution wrapper to force dependency loading:

bash npx -y -p @benborla29/mcp-server-mysql -p dotenv mcp-server-mysql

Credit to @lizhuangs.

Community Contributions

We encourage feature submissions via Pull Requests to the primary source repository: https://github.com/benborla/mcp-server-mysql

Acknowledged Contributors

Contributors

Development Workflow

  1. Checkout the source code.
  2. Install dependencies using pnpm: pnpm install.
  3. Compile: pnpm run build.
  4. Test: pnpm test.

Future Roadmap

Our development trajectory focuses on iterative improvements, detailed in CHANGELOG.md. Key areas include:

  • Advanced parameterized query handling.
  • Strengthening security protocols.
  • Ongoing performance enhancements.
  • Comprehensive telemetry reporting.
  • Expansion of discoverable schema metadata.

We welcome community input on roadmap items; raise an issue on GitHub to discuss potential contributions.

Submission Protocol

  1. Fork the repository.
  2. Branch out for your change: git checkout -b enhancement/my-new-feature.
  3. Commit changes clearly: git commit -am 'Feature: Implemented X optimization'.
  4. Push your branch: git push origin enhancement/my-new-feature.
  5. Open a formal Pull Request.

Licensing

This server software is distributed under the permissive MIT License. Consult the LICENSE file for full legal text.

WIKIPEDIA NOTE: XMLHttpRequest (XHR) is a fundamental interface within web development, permitting asynchronous HTTP communication between a client-side script (like JavaScript) and a remote server, forming the backbone of AJAX techniques. Before XHR, interactivity often required full page reloads via standard form submissions or hyperlinks. XHR was pioneered by Microsoft Outlook developers around 2000 and subsequently standardized by the W3C, evolving through Level 2 specifications to include features like progress monitoring and binary data handling.

See Also

`