MCP MySQL Server
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., "@MCP MySQL ServerShow me the list of all tables"
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.
🔌 MCP MySQL Server
Servidor MCP (Model Context Protocol) para MySQL - Módulo reutilizável que permite integração nativa entre Cursor IDE e qualquer banco de dados MySQL.
📋 O que é isso?
Este é um servidor MCP que permite que o Cursor (e outras ferramentas que suportam MCP) executem queries SQL diretamente no seu banco MySQL local, facilitando:
✅ Análise de estrutura de tabelas
✅ Consultas de dados em tempo real
✅ Geração de código baseado no schema
✅ Debugging de queries
✅ Inspeção de relacionamentos
Related MCP server: MySQL MCP Server
🚀 Instalação Rápida
1. Instalar Dependências
cd mcp-mysql-server
npm install2. Configurar Credenciais
# Windows
copy env.example .env
# Linux/Mac
cp env.example .envEdite o arquivo .env com suas credenciais:
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWORD=sua_senha_aqui
MYSQL_DATABASE=food3. Testar Conexão
npm startSe aparecer [MCP MySQL] Servidor MCP iniciado com sucesso, está funcionando! ✅
⚙️ Configuração no Cursor
Windows
Edite o arquivo de configuração do Cursor:
Caminho: %APPDATA%\Cursor\User\globalStorage\rooveterinaryinc.roo-cline\settings\cline_mcp_settings.json
Ou acesse via Cursor: Settings → Extensions → MCP Servers
Adicione:
{
"mcpServers": {
"mysql-food": {
"command": "node",
"args": ["G:/IA/Estudos/mcp-mysql-server/src/index.js"],
"env": {
"MYSQL_HOST": "localhost",
"MYSQL_PORT": "3306",
"MYSQL_USER": "root",
"MYSQL_PASSWORD": "SuaSenhaAqui",
"MYSQL_DATABASE": "food"
}
}
}
}Linux/Mac
Caminho: ~/.config/Cursor/User/globalStorage/rooveterinaryinc.roo-cline/settings/cline_mcp_settings.json
{
"mcpServers": {
"mysql-food": {
"command": "node",
"args": ["/caminho/completo/mcp-mysql-server/src/index.js"],
"env": {
"MYSQL_HOST": "localhost",
"MYSQL_PORT": "3306",
"MYSQL_USER": "root",
"MYSQL_PASSWORD": "SuaSenhaAqui",
"MYSQL_DATABASE": "food"
}
}
}
}4. Reiniciar Cursor
Feche e abra o Cursor completamente para carregar o servidor MCP.
🛠️ Ferramentas Disponíveis
1. mysql_execute_query
Executa qualquer query SQL.
Exemplo:
SELECT * FROM combos WHERE COD = 9;Parâmetros:
query(string): Query SQLparams(array, opcional): Parâmetros para prepared statements
Uso com prepared statements:
SELECT * FROM users WHERE id = ? AND status = ?
Params: [1, "active"]2. mysql_list_tables
Lista todas as tabelas do banco de dados.
Retorna:
{
"success": true,
"database": "food",
"tableCount": 15,
"tables": ["combos", "detcombos", "produtos", ...]
}3. mysql_describe_table
Mostra a estrutura completa de uma tabela.
Parâmetros:
table_name(string): Nome da tabela
Exemplo:
table_name: "combos"Retorna:
{
"success": true,
"table": "combos",
"columns": [
{
"Field": "COD",
"Type": "int",
"Null": "NO",
"Key": "PRI",
"Default": null,
"Extra": "auto_increment"
},
...
]
}4. mysql_show_databases
Lista todos os databases disponíveis no servidor.
Retorna:
{
"success": true,
"databases": ["food", "mysql", "information_schema", ...]
}5. mysql_table_info
Retorna informações completas: colunas, índices e contagem de registros.
Parâmetros:
table_name(string): Nome da tabela
Retorna:
{
"success": true,
"table": "combos",
"rowCount": 25,
"columns": [...],
"indexes": [...]
}🎯 Exemplos de Uso
No Chat do Cursor
Depois de configurado, você pode pedir ao assistente:
"Liste todas as tabelas do banco food"
"Mostre a estrutura da tabela combos"
"Execute: SELECT * FROM detcombos WHERE CODCOMBO = 9"
"Quantos registros tem na tabela movimento?"O assistente vai usar automaticamente as ferramentas MCP!
🔒 Segurança
✅ Boas Práticas
Nunca commite o arquivo
.envEle está no
.gitignorepor segurança
Use usuário com permissões limitadas
CREATE USER 'cursor_readonly'@'localhost' IDENTIFIED BY 'senha_segura'; GRANT SELECT ON food.* TO 'cursor_readonly'@'localhost'; FLUSH PRIVILEGES;Conexão apenas local
O servidor só aceita conexões de
localhost
Prepared Statements
Use sempre parâmetros em vez de concatenar strings
🐛 Troubleshooting
Erro: "MYSQL_DATABASE não está configurado"
Solução: Crie o arquivo .env a partir do env.example
Erro: "Access denied for user"
Solução: Verifique usuário e senha no .env
Erro: "connect ECONNREFUSED"
Solução:
Verifique se o MySQL está rodando
Confirme a porta (padrão: 3306)
Cursor não encontra o servidor
Solução:
Verifique o caminho absoluto no
argsReinicie o Cursor completamente
Verifique logs em:
View→Output→MCP
Teste manual da conexão
# Testar se o MySQL está respondendo
mysql -u root -p -h localhost -P 3306
# Testar o servidor MCP
cd mcp-mysql-server
node src/index.js📂 Estrutura do Projeto
mcp-mysql-server/
├── src/
│ └── index.js # Servidor MCP principal
├── package.json # Dependências e scripts
├── env.example # Template de configuração
├── .gitignore # Arquivos ignorados pelo Git
└── README.md # Este arquivo🔄 Usar em Múltiplos Projetos
Opção 1: Instalar Globalmente
cd mcp-mysql-server
npm linkDepois em qualquer projeto:
npm link @local/mcp-mysql-serverOpção 2: Referenciar Diretamente
No Cursor, aponte para o caminho absoluto do index.js:
"args": ["G:/IA/Estudos/mcp-mysql-server/src/index.js"]Opção 3: Múltiplos Bancos
Crie múltiplas configurações no Cursor:
{
"mcpServers": {
"mysql-food": {
"command": "node",
"args": ["G:/IA/Estudos/mcp-mysql-server/src/index.js"],
"env": {
"MYSQL_DATABASE": "food",
...
}
},
"mysql-ecommerce": {
"command": "node",
"args": ["G:/IA/Estudos/mcp-mysql-server/src/index.js"],
"env": {
"MYSQL_DATABASE": "ecommerce",
...
}
}
}
}📦 Dependências
@modelcontextprotocol/sdk- SDK oficial do MCPmysql2- Driver MySQL para Node.js (com suporte a Promises)dotenv- Gerenciamento de variáveis de ambiente
🤝 Contribuindo
Sinta-se livre para melhorar este módulo:
Adicionar mais ferramentas
Melhorar tratamento de erros
Adicionar cache de queries
Implementar rate limiting
Adicionar logs estruturados
📝 Licença
MIT - Use livremente em seus projetos!
🎓 Recursos Adicionais
✨ Autor
Criado para facilitar o desenvolvimento com IA e bancos de dados MySQL.
Versão: 1.0.0
Node.js: >= 18.0.0
Testado em: Node v22.12.0
This server cannot be deployed
Maintenance
Related MCP Connectors
- mcpOAuthcom.gibsonai
GibsonAI MCP server: manage your databases with natural language
The Instant MCP server is a wrapper around the Instant Platform SDK that enables creating, managing, and updating InstantDB applications directly within an editor. It provides tools for fetching rules files for LLMs, retrieving and pushing app schemas, managing permission rules, and executing database queries. Key capabilities include schema management (get-schema, push-schema), permission management (get-perms, push-perms), query execution, and listing recent query history.
The Mercado Pago MCP Server implements the Model Context Protocol to provide AI agents and LLMs with access to Mercado Pago's APIs and tools within compatible development environments. It acts as an intermediary that translates Mercado Pago resources into executable functions (tools) that AI applications can invoke to perform actions and automate flows. The server simplifies integration, enables using documentation to implement or improve code, and optimizes operations through natural language interactions without manual implementations.
Draxlr's remote MCP server connects AI assistants to your SQL databases and dashboards. Explore schemas, run read-only queries, manage saved queries and dashboards, and export results, all with row-level security so each user sees only their own data.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceA specialized MySQL MCP server for Cursor that enables users to query table structures, execute SQL, and generate database documentation. It features multiple security modes to ensure safe interaction while providing tools for database overviews and query caching.5MIT
- AlicenseNot gradedqualityDmaintenanceA MySQL MCP server for secure database interaction, enabling schema inspection, query execution, and RBAC via AI coding assistants.618 npm5MIT
- AlicenseNot gradedqualityDmaintenanceMCP server that connects AI agents to MySQL databases for schema exploration, data querying, and SQL execution via natural language.2MIT
- AlicenseNot gradedqualityDmaintenanceA production-ready MCP server for MySQL database integration with AI agents, enabling database exploration, CRUD operations, schema management, and performance monitoring through natural language.492 npmMIT