MySQL MCP Server (Optimized)
Provides tools to interact with a MySQL database, allowing users to execute SQL queries, inspect table structures, list databases and tables, and perform schema analysis.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@MySQL MCP Server (Optimized) show me the schema for the users table"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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çãodescribe_table: Descreve estrutura de tabelas
2. Resources (Recursos)
mysql://databases: Lista de bancos disponíveismysql://tables: Tabelas do banco atualmysql://schema: Schema completo
3. Prompts (Templates)
analyze_table: Análise detalhada de tabelafind_large_tables: Tabelas com mais registrosdatabase_overview: Visão geral do banco
🚀 Instalação e Uso
1. Instalar Dependências
npm install2. Configurar MySQL
Crie um arquivo .env:
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWORD=sua_senha
MYSQL_DATABASE=seu_banco3. Compilar e Executar
# Compilar
npm run build
# Executar
npm start
# Desenvolvimento
npm run dev4. 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
Fork o projeto
Crie uma branch (
git checkout -b feature/nova-funcionalidade)Commit suas mudanças (
git commit -m 'Adiciona nova funcionalidade')Push para a branch (
git push origin feature/nova-funcionalidade)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 toolsdescribe_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
Scored across 2 tools
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.
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.
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.
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
Hosted SQL Server MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Hosted MySQL MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
An MCP server that provides read access to your cloud storage providers, bank accounts and more.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA 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-
- AlicenseNot gradedqualityDmaintenanceA MySQL MCP server for secure database interaction, enabling schema inspection, query execution, and RBAC via AI coding assistants.524 npm7MIT
- AlicenseNot gradedqualityDmaintenanceA production-ready MCP server for MySQL database operations, providing secure HTTP endpoints for read-only queries, performance analysis, and server monitoring.81 npm22MIT
- AlicenseNot gradedqualityDmaintenanceA 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.3MIT