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 "Install 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
| Name | Required | Description | Default |
|---|---|---|---|
| table_name | Yes | Nome da tabela para descrever | |
| database | No | Nome do banco de dados |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool describes table structure but doesn't cover aspects like read-only nature, potential errors, output format, or performance implications, which are important for a tool with no annotations.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, efficient sentence in Portuguese that directly states the tool's function without unnecessary words. It's appropriately sized and front-loaded, making it easy to parse.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the lack of annotations and output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., column details, types) or handle potential complexities, which is insufficient for a tool with no structured output information.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The input schema has 100% description coverage, clearly documenting both parameters. The description doesn't add any additional meaning or context beyond what the schema provides, such as examples or constraints, so it meets the baseline score of 3.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description 'Descreve a estrutura de uma tabela' clearly states the tool's purpose with a specific verb ('Descreve') and resource ('estrutura de uma tabela'), making it understandable. However, it doesn't explicitly differentiate from its sibling tool 'execute_query', which might also involve table operations, so it doesn't reach the highest score of 5.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides no guidance on when to use this tool versus alternatives. There's no mention of prerequisites, context, or comparison with the sibling tool 'execute_query', leaving the agent without usage instructions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
execute_queryC
Executa uma query SQL no banco MySQL
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | A query SQL para executar | |
| database | No | Banco de dados opcional |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries full burden for behavioral disclosure. While 'Executa uma query SQL' implies write capability for non-SELECT queries, it doesn't specify permissions required, whether transactions are supported, potential side effects, or error handling. For a database mutation tool with zero annotation coverage, this is a significant gap.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, efficient sentence with zero waste. It's appropriately sized for a straightforward tool and gets directly to the point without unnecessary elaboration.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a database query execution tool with no annotations and no output schema, the description is insufficient. It doesn't address critical context like what types of queries are supported (SELECT/INSERT/UPDATE), result format, error conditions, or security considerations. The agent would have significant gaps in understanding how to use this tool effectively.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so the schema already documents both parameters fully. The description doesn't add any meaningful parameter semantics beyond what's in the schema - it doesn't explain query syntax requirements, database connection behavior, or parameter interactions. Baseline 3 is appropriate when schema does the heavy lifting.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the action ('Executa uma query SQL') and target resource ('no banco MySQL'), providing specific verb+resource information. However, it doesn't differentiate from the sibling tool 'describe_table' or explain how this general query execution differs from more specific operations.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides no guidance about when to use this tool versus alternatives, prerequisites, or limitations. There's no mention of the sibling tool 'describe_table' or any context about appropriate use cases for general SQL execution versus table inspection.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
TDQS
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.
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
An MCP server that provides read access to your cloud storage providers, bank accounts and more.
A MCP server built for developers enabling Git based project management with project and personal…
MCP server for querying and analyzing data from ad platforms, analytics tools, and spreadsheets
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.1,0815MIT
- AlicenseNot gradedqualityDmaintenanceA production-ready MCP server for MySQL database operations, providing secure HTTP endpoints for read-only queries, performance analysis, and server monitoring.12116MIT
- 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
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/fabiovige/mcp-mysql-simple'
If you have feedback or need assistance with the MCP directory API, please join our Discord server