Skip to main content
Glama
fabiovige

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

ParametersJSON Schema
NameRequiredDescriptionDefault
table_nameYesNome da tabela para descrever
databaseNoNome do banco de dados

TDQS

C2.9/5.0
Behavior2/5

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.

Conciseness5/5

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.

Completeness2/5

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.

Parameters3/5

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.

Purpose4/5

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.

Usage Guidelines2/5

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

ParametersJSON Schema
NameRequiredDescriptionDefault
queryYesA query SQL para executar
databaseNoBanco de dados opcional

TDQS

C2.9/5.0
Behavior2/5

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.

Conciseness5/5

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.

Completeness2/5

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.

Parameters3/5

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.

Purpose4/5

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.

Usage Guidelines2/5

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

B3/5.0
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.

Maintenance

ActivityStale
ResponsivenessNo issues

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

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.
    1,081
    5
    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.
    121
    16
    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

Latest Blog Posts

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