Skip to main content
Glama
burakdirin

mysqldb-mcp-server

execute_query

Execute MySQL queries directly on the 'mysqldb-mcp-server' to retrieve, manage, or manipulate database data using structured SQL statements.

Instructions

Execute MySQL queries

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes

Implementation Reference

  • The primary handler function for the 'execute_query' tool. Decorated with @mcp.tool() for registration in FastMCP. It orchestrates query execution via QueryExecutor and formats results as JSON.
    @mcp.tool()
    def execute_query(query: str, ctx: Context) -> str:
        """Execute MySQL queries"""
        try:
            executor = _get_executor(ctx)
            results = executor.execute_multiple_queries(query)
    
            if len(results) == 1:
                return json.dumps(results[0], indent=2)
            return json.dumps(results, indent=2)
        except (ConnectionError, QueryError) as e:
            return str(e)
  • Core helper class QueryExecutor that handles the actual MySQL query execution, connection management, result processing, and error handling used by the execute_query tool.
    class QueryExecutor:
        """Handles MySQL query execution and result processing"""
    
        def __init__(self, context: MySQLContext):
            self.context = context
    
        def _format_datetime(self, value: Any) -> Any:
            """Format datetime values to string"""
            return value.strftime('%Y-%m-%d %H:%M:%S') if hasattr(value, 'strftime') else value
    
        def _process_row(self, row: Dict[str, Any]) -> Dict[str, Any]:
            """Process a single row of results"""
            return {key: self._format_datetime(value) for key, value in row.items()}
    
        def _process_results(self, cursor: MySQLCursor) -> Union[List[Dict[str, Any]], Dict[str, int]]:
            """Process query results"""
            if cursor.with_rows:
                results = cursor.fetchall()
                return [self._process_row(row) for row in results]
            return {"affected_rows": cursor.rowcount}
    
        def execute_single_query(self, query: str) -> Dict[str, Any]:
            """Execute a single query and return results"""
            self.context.ensure_connected()
            cursor = None
    
            try:
                cursor = self.context.connection.cursor(dictionary=True)
                query_type = QueryType(query.strip().upper().split()[0])
    
                # Handle readonly mode
                if self.context.readonly and QueryType.is_write_operation(query_type.value):
                    raise QueryError(
                        "Server is in read-only mode. Write operations are not allowed.")
    
                # Handle USE statements
                if query_type == QueryType.USE:
                    db_name = query.strip().split()[-1].strip('`').strip()
                    self.context.database = db_name
                    cursor.execute(query)
                    return {"message": f"Switched to database: {db_name}"}
    
                # Execute query
                cursor.execute(query)
                results = self._process_results(cursor)
    
                if not self.context.readonly:
                    self.context.connection.commit()
    
                return results
    
            except MySQLError as e:
                raise QueryError(f"Error executing query: {str(e)}")
            finally:
                if cursor:
                    cursor.close()
    
        def execute_multiple_queries(self, query: str) -> List[Dict[str, Any]]:
            """Execute multiple queries and return results"""
            queries = [q.strip() for q in query.split(';') if q.strip()]
            results = []
    
            for single_query in queries:
                try:
                    result = self.execute_single_query(single_query)
                    results.append(result)
                except QueryError as e:
                    results.append({"error": str(e)})
    
            return results
  • Helper function to retrieve the QueryExecutor instance from the MCP context, used within the execute_query handler.
    def _get_executor(ctx: Context) -> QueryExecutor:
        """Helper function to get QueryExecutor from context"""
        mysql_ctx = ctx.request_context.lifespan_context
        return QueryExecutor(mysql_ctx)
Behavior1/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure but fails to do so. It doesn't mention whether this is a read-only or destructive operation, authentication requirements, error handling, rate limits, or what the response looks like. For a database query tool with zero annotation coverage, this is a critical gap in transparency.

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 extremely concise with just three words, front-loaded and free of unnecessary information. Every word ('Execute MySQL queries') directly contributes to the core purpose, making it efficient in structure, though this brevity contributes to gaps in other dimensions.

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

Completeness1/5

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

Given the complexity of a database query tool, lack of annotations, no output schema, and 0% schema description coverage, the description is completely inadequate. It fails to address key aspects like behavioral traits, parameter details, return values, or usage context, making it insufficient for effective agent tool invocation.

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

Parameters1/5

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

The schema description coverage is 0%, meaning the input schema provides no descriptions for the 'query' parameter. The description 'Execute MySQL queries' adds no meaningful semantics beyond the parameter name—it doesn't explain the expected format, syntax, constraints, or examples for the query. This leaves the parameter entirely undocumented.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Execute MySQL queries' clearly states the verb ('execute') and resource ('MySQL queries'), making the purpose understandable. However, it lacks specificity about what types of queries are supported (e.g., SELECT, INSERT, UPDATE) and doesn't distinguish from the sibling tool 'connect_database', which appears to be a different operation. This makes it vague but not tautological.

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 the sibling 'connect_database' or other alternatives. It doesn't mention prerequisites (e.g., whether a database connection must be established first), use cases, or exclusions. This leaves the agent with no contextual direction for tool selection.

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

Related 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/burakdirin/mysqldb-mcp-server'

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