Skip to main content
Glama
yawlhead91

MariaDB MCP Server

by yawlhead91

execute_sql

Execute read-only SQL queries on MariaDB databases to retrieve data, explore schemas, and inspect database structures securely.

Instructions

Execute a read-only SQL query and return results.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
databaseNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The primary handler for the 'execute_sql' tool, registered via @mcp.tool() decorator. Performs security validation for read-only queries, executes the SQL using MariaDBConnection, and returns formatted results as a markdown table.
    @mcp.tool()
    async def execute_sql(query: str, database: Optional[str] = None) -> str:
        """Execute a read-only SQL query and return results."""
        try:
            # Security check: only allow SELECT, SHOW, DESCRIBE, EXPLAIN queries
            query_upper = query.strip().upper()
            allowed_keywords = ['SELECT', 'SHOW', 'DESCRIBE', 'DESC', 'EXPLAIN', 'WITH']
            
            if not any(query_upper.startswith(keyword) for keyword in allowed_keywords):
                return "Error: Only read-only queries (SELECT, SHOW, DESCRIBE, EXPLAIN) are allowed"
            
            # Switch database if specified
            if database:
                await db_connection.execute_query(f"USE `{database}`")
            
            results = await db_connection.execute_query(query)
            
            if not results:
                return "Query executed successfully. No results returned."
            
            # Format results as a table
            if len(results) == 0:
                return "No rows returned"
            
            # Get column names
            columns = list(results[0].keys())
            
            # Create table header
            output = "Query Results:\n\n"
            header = " | ".join(columns)
            separator = " | ".join(["-" * len(col) for col in columns])
            output += header + "\n" + separator + "\n"
            
            # Add data rows (limit to 100 rows for readability)
            for i, row in enumerate(results[:100]):
                row_data = " | ".join([str(row.get(col, '')) for col in columns])
                output += row_data + "\n"
            
            if len(results) > 100:
                output += f"\n... and {len(results) - 100} more rows (truncated for display)"
            
            output += f"\nTotal rows: {len(results)}"
            
            return output
        
        except Exception as e:
            logger.error(f"Error executing SQL: {e}")
            return f"Error executing SQL: {str(e)}"
  • Helper method in MariaDBConnection class that actually executes SQL queries using aiomysql pool, used by the execute_sql tool.
    async def execute_query(self, query: str, params: Optional[tuple] = None) -> List[Dict[str, Any]]:
        """Execute a SQL query and return results."""
        logger.debug(f"Executing query: {query[:100]}{'...' if len(query) > 100 else ''}")
        await self.connect()
        
        async with self.pool.acquire() as conn:
            async with conn.cursor(aiomysql.DictCursor) as cursor:
                await cursor.execute(query, params)
                if cursor.description:
                    results = await cursor.fetchall()
                    logger.debug(f"Query returned {len(results)} rows")
                    return [dict(row) for row in results]
                logger.debug("Query executed successfully, no results returned")
                return []
  • The @mcp.tool() decorator registers the execute_sql function as an MCP tool in the FastMCP server.
    @mcp.tool()
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. It discloses that the query is read-only, which is a key behavioral trait, but doesn't cover other aspects like permissions needed, rate limits, error handling, or what 'return results' entails (e.g., format, pagination). For a tool with no annotations, this leaves significant gaps in understanding its behavior.

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 that front-loads key information (execute, read-only, return results) with zero waste. Every word earns its place, making it highly concise and well-structured for quick understanding.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (SQL execution with 2 parameters), no annotations, and an output schema present, the description is minimally adequate. It covers the basic purpose and read-only nature, but lacks details on parameter usage, behavioral constraints, or integration with siblings. The output schema reduces the need to explain return values, but more context would be helpful for safe and effective use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It mentions 'SQL query' which relates to the 'query' parameter, but doesn't explain the 'database' parameter or provide any additional semantic context beyond what's inferred from parameter names. With 2 parameters and no schema descriptions, the description adds minimal value over the bare schema.

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 verb ('execute') and resource ('SQL query'), specifying it's read-only and returns results. It distinguishes from potential siblings like 'get_table_schema' or 'list_tables' by focusing on query execution rather than metadata retrieval. However, it doesn't explicitly differentiate from all siblings (e.g., 'reload_config' is unrelated).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for executing SQL queries, particularly read-only ones, but doesn't provide explicit guidance on when to use this versus alternatives like 'list_tables' for metadata or specify prerequisites. It mentions 'read-only' which hints at when not to use it for write operations, but lacks detailed alternatives or exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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/yawlhead91/mariadb-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server