npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

mysql-optimizer-mcp-server

v1.0.1

Published

MCP server for MySQL database analysis and query optimization

Downloads

6

Readme

MySQL Optimizer MCP Server

A Model Context Protocol (MCP) server that provides MySQL database analysis and query optimization tools with read-only access.

Features

  • Table Analysis: Get detailed information about tables including columns, indexes, primary keys, and foreign keys
  • Query Optimization: Analyze SELECT queries and get optimization suggestions
  • Index Suggestions: Get recommendations for creating indexes based on query patterns
  • Data Retrieval: Safely retrieve sample or latest data from tables
  • Security: Read-only access with strict validation against dangerous operations

Installation

From npm (Recommended)

npm install -g mysql-optimizer-mcp-server

From source

git clone https://github.com/yourusername/mysql-optimizer-mcp-server.git
cd mysql-optimizer-mcp-server
npm install

Environment Variables

Set these environment variables for database connection:

DB_HOST=localhost          # Database host (default: localhost)
DB_PORT=3306              # Database port (default: 3306)
DB_USER=your_username     # Database username
DB_PASSWORD=your_password # Database password
DB_NAME=your_database     # Database name

Usage

Running the Server

npm start

Available Tools

1. show_table_details

Get comprehensive information about a table.

Parameters:

  • table_name (string): Name of the table to analyze

Returns:

  • Table structure with columns, data types, constraints
  • All indexes with their columns and properties
  • Primary keys and foreign key relationships

2. analyze_query

Intelligently analyze SQL queries with three-tier safety handling.

Parameters:

  • query (string): SQL query to analyze
  • limit (number): Maximum rows to return for executed queries (default: 100, max: 1000)

Three-Tier Safety Model:

  • Safe queries (SELECT, SHOW, DESCRIBE, EXPLAIN): ✅ Executed with results and optimization suggestions
  • Analyzable queries (INSERT, UPDATE): ⚠️ Analyzed for structure and optimization but NOT executed
  • Blocked queries (DROP, DELETE, TRUNCATE, ALTER, etc.): ❌ Completely rejected

Returns:

  • For safe queries: Execution results, optimization suggestions, execution plan
  • For analyzable queries: Structure analysis, optimization suggestions, safe alternatives
  • For blocked queries: Rejection message with security explanation

3. suggest_indexes

Get index suggestions for a table based on query patterns.

Parameters:

  • table_name (string): Name of the table
  • where_columns (array): Columns frequently used in WHERE conditions

Returns:

  • Existing indexes on the table
  • Suggested single-column indexes
  • Suggested composite indexes
  • SQL statements to create the indexes

4. get_table_data

Retrieve sample or latest data from a table.

Parameters:

  • table_name (string): Name of the table
  • limit (number): Number of rows to return (default: 10, max: 100)
  • order_by (string): Column to order by
  • order_direction (string): ASC or DESC (default: DESC)

Returns:

  • Sample data from the table
  • Total row count
  • Query parameters used

5. list_tables

List all tables in the database with metadata.

Returns:

  • All tables with row counts, sizes, and timestamps

Security Features

  • Three-Tier Security Model: Smart categorization of queries based on risk level
  • Safe Execution: SELECT, SHOW, DESCRIBE, EXPLAIN queries are executed with optimization
  • Analysis-Only Mode: INSERT, UPDATE queries are analyzed for structure but never executed
  • Complete Blocking: DROP, DELETE, TRUNCATE, ALTER operations are completely rejected
  • Comprehensive Validation: Detects dangerous keywords, SQL injection patterns, and nested unsafe operations
  • Flexible Limits: Configurable row limits (max 1000 for safe queries, max 100 for table data)
  • Read-Only Guarantee: No data modifications can occur - only safe reads and analysis

Example Usage in MCP Client

// Get table details
await callTool('show_table_details', { table_name: 'users' });

// Analyze any query - automatically handles safety
await callTool('analyze_query', { 
  query: 'SELECT * FROM users WHERE email = ? AND status = ?',
  limit: 50
});

// Safe queries are executed with optimization suggestions
await callTool('analyze_query', { 
  query: 'SHOW TABLES' 
});

await callTool('analyze_query', { 
  query: 'DESCRIBE users' 
});

await callTool('analyze_query', { 
  query: 'EXPLAIN SELECT * FROM users WHERE email = "[email protected]"' 
});

// Analyzable queries (INSERT/UPDATE) - analyzed but not executed
await callTool('analyze_query', { 
  query: 'INSERT INTO users (name, email) VALUES ("John", "[email protected]")' 
});
// Returns: Structure analysis, optimization suggestions, safe alternatives

await callTool('analyze_query', { 
  query: 'UPDATE products SET price = price * 1.1 WHERE category = "electronics"' 
});
// Returns: Structure analysis, affected columns, optimization suggestions

// Dangerous queries are completely rejected
await callTool('analyze_query', { 
  query: 'DELETE FROM users WHERE last_login < "2023-01-01"' 
});
// Returns: {"status": "REJECTED", "reason": "Dangerous operations are completely blocked"}

// Get index suggestions
await callTool('suggest_indexes', { 
  table_name: 'users', 
  where_columns: ['email', 'status'] 
});

// Get latest reports
await callTool('get_table_data', { 
  table_name: 'reports', 
  limit: 20, 
  order_by: 'created_at',
  order_direction: 'DESC'
});

Security Examples

The server uses a three-tier security model with different handling for each category:

Safe Query Execution (SELECT, SHOW, DESCRIBE, EXPLAIN)

// Input: SELECT COUNT(*) FROM users WHERE status = 'inactive'
// Output:
{
  "query": "SELECT COUNT(*) FROM users WHERE status = 'inactive'",
  "safety_status": "SAFE - EXECUTED",
  "query_type": "SELECT",
  "result": [{"COUNT(*)": 42}],
  "row_count": 1,
  "optimization_suggestions": [...]
}

Analyzable Query Analysis (INSERT, UPDATE)

// Input: UPDATE products SET price = price * 1.1 WHERE category = 'electronics'
// Output:
{
  "query": "UPDATE products SET price = price * 1.1 WHERE category = 'electronics'",
  "safety_status": "ANALYZABLE - NOT EXECUTED",
  "structure_analysis": {
    "type": "UPDATE",
    "tables": ["products"],
    "columns": ["price"],
    "conditions": ["category = 'electronics'"]
  },
  "analysis_recommendations": [
    {
      "type": "analysis",
      "message": "UPDATE operations modify existing data",
      "alternatives": [
        "To preview affected rows: SELECT * FROM products WHERE category = 'electronics' LIMIT 10",
        "To count affected rows: SELECT COUNT(*) FROM products WHERE category = 'electronics'"
      ]
    }
  ],
  "note": "This query was analyzed for structure and optimization but was NOT executed."
}

Blocked Query Rejection (DROP, DELETE, TRUNCATE, etc.)

// Input: DELETE FROM users WHERE status = 'inactive'
// Output: 
{
  "query": "DELETE FROM users WHERE status = 'inactive'",
  "status": "REJECTED",
  "reason": "Dangerous operations are completely blocked",
  "violations": ["DELETE: DELETE operations remove data from tables"],
  "message": "Operations like DROP, DELETE, TRUNCATE, ALTER, CREATE, etc. are completely blocked for security.",
  "allowed_operations": ["SELECT", "SHOW", "DESCRIBE", "DESC", "EXPLAIN", "HELP"],
  "analyzable_operations": ["INSERT", "UPDATE"]
}

MCP Configuration

Using npm package (Recommended)

Add to your MCP client configuration:

{
  "mcpServers": {
    "mysql-optimizer": {
      "command": "npx",
      "args": ["mysql-optimizer-mcp-server"],
      "env": {
        "DB_HOST": "localhost",
        "DB_PORT": "3306",
        "DB_USER": "your_username",
        "DB_PASSWORD": "your_password",
        "DB_NAME": "your_database"
      }
    }
  }
}

Using uvx (Alternative)

If you have uv installed, you can also use:

{
  "mcpServers": {
    "mysql-optimizer": {
      "command": "uvx",
      "args": ["mysql-optimizer-mcp-server"],
      "env": {
        "DB_HOST": "localhost",
        "DB_PORT": "3306",
        "DB_USER": "your_username",
        "DB_PASSWORD": "your_password",
        "DB_NAME": "your_database"
      }
    }
  }
}

Using local installation

For local development or custom installations:

{
  "mcpServers": {
    "mysql-optimizer": {
      "command": "node",
      "args": ["/path/to/mysql-optimizer-mcp-server/index.js"],
      "env": {
        "DB_HOST": "localhost",
        "DB_PORT": "3306",
        "DB_USER": "your_username",
        "DB_PASSWORD": "your_password",
        "DB_NAME": "your_database"
      }
    }
  }
}

Query Optimization Tips

The server provides suggestions for:

  1. Missing Indexes: When full table scans are detected
  2. Single Column Indexes: For frequently filtered columns
  3. Composite Indexes: For multi-column WHERE conditions
  4. Query Structure: Based on execution plan analysis

All suggestions are provided as SQL statements that you can review and execute manually.# mcp-db

mcp-db

mcp-db