MySQL MCP Server (Optimized)

MySQL MCP Server (Optimized)

An MCP server for MySQL that enables users to execute SQL queries, inspect table structures, and explore database schemas through a clean, SOLID-based architecture. It includes built-in security validations to protect against dangerous operations and ensure safe interaction with database resources.

Category
Visit Server

README

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

🏗️ 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

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
E2B

E2B

Using MCP to run code via e2b.

Official
Featured