Skip to main content
Glama
MySQL MCP Server (Optimized)

MySQL MCP Server (Optimized)

by fabiovige

Servidor MCP MySQL Otimizado

Servidor MCP (Model Context Protocol) para MySQL com arquitetura limpa e princípios SOLID.

🆕 Melhorias na v1.1.0

✨ Arquitetura Otimizada

  • Separação de Responsabilidades: Classes especializadas para cada função

  • SOLID Principles: Código mais maintível e extensível

  • Clean Architecture: Estrutura modular e testável

🔒 Segurança Aprimorada

  • Validação de Queries: Proteção contra operações perigosas

  • Sanitização: Nomes de tabelas validados

  • SQL Injection Protection: Parâmetros seguros

🚀 Performance e Confiabilidade

  • Conexão Reutilizada: Gerenciamento eficiente de recursos

  • Tratamento de Erros: Mensagens consistentes e informativas

  • Shutdown Gracioso: Encerramento controlado de conexões

Related MCP server: MySQL MCP Server

🏗️ Arquitetura

MySQLMCPServer
├── DatabaseConfig (Configurações)
├── DatabaseConnection (Conexão MySQL)
├── QueryValidator (Validação e Segurança)
├── ResponseFormatter (Formatação)
├── ToolsHandler (Ferramentas)
├── ResourcesHandler (Recursos)
└── PromptsHandler (Templates)

🎯 Conceitos MCP Implementados

1. Tools (Ferramentas)

  • execute_query: Executa queries SQL com validação

  • describe_table: Descreve estrutura de tabelas

2. Resources (Recursos)

  • mysql://databases: Lista de bancos disponíveis

  • mysql://tables: Tabelas do banco atual

  • mysql://schema: Schema completo

3. Prompts (Templates)

  • analyze_table: Análise detalhada de tabela

  • find_large_tables: Tabelas com mais registros

  • database_overview: Visão geral do banco

🚀 Instalação e Uso

1. Instalar Dependências

npm install

2. Configurar MySQL

Crie um arquivo .env:

MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWORD=sua_senha
MYSQL_DATABASE=seu_banco

3. Compilar e Executar

# Compilar
npm run build

# Executar
npm start

# Desenvolvimento
npm run dev

4. Testar Conexão

npm run test:connection

🔧 Configuração Claude Desktop

Adicione ao claude_desktop_config.json:

{
  "mcpServers": {
    "mysql-optimized": {
      "command": "node",
      "args": ["/caminho/para/dist/index.js"],
      "env": {
        "MYSQL_HOST": "localhost",
        "MYSQL_PORT": "3306",
        "MYSQL_USER": "root",
        "MYSQL_PASSWORD": "sua_senha",
        "MYSQL_DATABASE": "seu_banco"
      }
    }
  }
}

🛡️ Segurança

Validações Implementadas:

  • ✅ Bloqueio de DROP DATABASE/TABLE

  • ✅ Proteção contra DELETE ... WHERE 1=1

  • ✅ Sanitização de nomes de tabelas

  • ✅ Validação de queries vazias

  • ✅ Tratamento seguro de parâmetros

Práticas de Segurança:

  • 🔒 Conexões controladas

  • 🔒 Logs de erro seguros

  • 🔒 Isolamento de responsabilidades

  • 🔒 Validação de entrada

📊 Exemplo de Uso

// Executar query segura
{
  "name": "execute_query",
  "arguments": {
    "query": "SELECT * FROM usuarios LIMIT 5",
    "database": "meu_banco"
  }
}

// Analisar tabela
{
  "name": "describe_table",
  "arguments": {
    "table_name": "usuarios"
  }
}

🔍 Debug e Logs

O servidor fornece logs informativos:

  • ✅ Conexão estabelecida

  • 🔄 Queries executadas

  • ❌ Erros com detalhes

  • 🔚 Shutdown gracioso

📈 Roadmap

  • Cache de resultados

  • Métricas de performance

  • Pool de conexões

  • Suporte a transações

  • Interface web de monitoramento

🤝 Contribuição

  1. Fork o projeto

  2. Crie uma branch (git checkout -b feature/nova-funcionalidade)

  3. Commit suas mudanças (git commit -m 'Adiciona nova funcionalidade')

  4. Push para a branch (git push origin feature/nova-funcionalidade)

  5. Abra um Pull Request

📝 Changelog

v1.1.0 (2025-01-XX)

  • ✨ Arquitetura otimizada com SOLID

  • 🔒 Validação e segurança aprimoradas

  • 🚀 Performance melhorada

  • 📚 Documentação expandida

v1.0.0 (2025-01-XX)

  • 🎉 Versão inicial

  • 🔧 Implementação básica MCP

  • 🗄️ Suporte MySQL completo

📄 Licença

MIT License - veja o arquivo LICENSE para detalhes.


Criado com ❤️ para demonstrar o protocolo MCP da Anthropic

Available Tools

2 tools
describe_tableC

Descreve a estrutura de uma tabela

Inputs: table_name (required), database.

execute_queryC

Executa uma query SQL no banco MySQL

Inputs: query (required), database.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3/5.0

    Scored across 2 tools

    Disambiguation5/5

    The two tools have completely distinct purposes: describe_table is for metadata inspection of a table's structure, while execute_query is for running arbitrary SQL queries. There is no overlap or ambiguity between these functions, making it easy for an agent to choose the correct tool based on the task.

    Naming Consistency5/5

    Both tools follow a consistent verb_noun pattern with snake_case naming: describe_table and execute_query. The naming is clear, predictable, and adheres to a uniform style throughout the tool set.

    Tool Count2/5

    With only 2 tools, this server is severely under-equipped for a MySQL database management domain. Core operations like creating/dropping tables, inserting/updating/deleting data, managing users, or handling transactions are missing, making it inadequate for typical database workflows.

    Completeness1/5

    The tool surface is extremely incomplete for a MySQL server. It lacks basic CRUD operations (create, read, update, delete), schema modification tools, user management, and other essential database functions. Agents will frequently encounter dead ends when trying to perform common MySQL tasks.

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      A high-performance MCP server that enables AI assistants to safely interact with MySQL databases through secure CRUD operations, schema inspection, and parameterized queries with built-in SQL injection prevention.
      1
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      A MySQL MCP server for secure database interaction, enabling schema inspection, query execution, and RBAC via AI coding assistants.
      524 npm
      7
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      A production-ready MCP server for MySQL database operations, providing secure HTTP endpoints for read-only queries, performance analysis, and server monitoring.
      81 npm
      22
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      A secure and efficient MCP server for MySQL database operations, enabling LLMs to execute SQL queries with read-only access by default and optional write permissions.
      3
      MIT