Skip to main content
Glama
wenb1n-dev

mysql_mcp_server

execute_sql

Execute SQL queries on MySQL5.6 databases using a supported MCP server. Supports multiple SQL executions, table and field queries, execution plan analysis, and Chinese-to-pinyin conversion.

Instructions

在MySQL5.6s数据库上执行SQL

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes要执行的SQL语句

Implementation Reference

  • The `run_tool` method of ExecuteSQL class: core handler logic for 'execute_sql' tool. Validates input, executes SQL using ExecuteSqlUtil, formats and returns results as TextContent.
    async def run_tool(self, arguments: Dict[str, Any]) -> Sequence[TextContent]:
        """执行SQL工具
        
        Args:
            arguments: 包含SQL查询的参数字典
            
        Returns:
            执行结果文本序列
        """
        if "query" not in arguments:
            return [TextContent(type="text", text="错误: 缺少查询语句")]
    
        query = arguments["query"]
        
        try:
            exe = ExecuteSqlUtil()
            sql_results = exe.execute_multiple_statements(query)
            
            # 格式化结果
            results = []
            for result in sql_results:
                formatted_result = exe.format_result(result)
                results.append(formatted_result)
            
            return [TextContent(type="text", text="\n---\n".join(results))]
            
        except SQLExecutionError as e:
  • The `get_tool_description` method defines the input schema for 'execute_sql' tool: object with required 'query' string property.
    def get_tool_description(self) -> Tool:
        """获取工具描述"""
        return Tool(
            name=self.name,
            description=self.description,
            inputSchema={
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "要执行的SQL语句"
                    }
                },
                "required": ["query"]
            }
        )
  • BaseHandler.__init_subclass__ automatically registers subclasses like ExecuteSQL to ToolRegistry when they have a defined 'name'.
    def __init_subclass__(cls, **kwargs):
        """子类初始化时自动注册到工具注册表"""
        super().__init_subclass__(**kwargs)
        if cls.name:  # 只注册有名称的工具
            ToolRegistry.register(cls)
  • ExecuteSqlUtil.execute_multiple_statements: splits query by ';', executes each statement via execute_single_statement (with permissions, pooling), collects results. Called by handler.
    def execute_multiple_statements(self, query: str) -> List[SQLResult]:
        """执行多条SQL语句
        
        Args:
            query: 包含多条SQL语句的查询字符串,以分号分隔
            
        Returns:
            SQL执行结果列表
        """
        statements = [stmt.strip() for stmt in query.split(';') if stmt.strip()]
        results = []
        
        for statement in statements:
            try:
                result = self.execute_single_statement(statement)
                results.append(result)
            except Exception as e:
                logger.warning(f"SQL执行警告: {e}, SQL: {statement}")
                results.append(SQLResult(
                    success=False,
                    message=f"执行失败: {str(e)}"
                ))
                
        return results
  • ToolRegistry.register: instantiates the handler class and stores it in the registry by name, called automatically during subclass init.
    @classmethod
    def register(cls, tool_class: Type['BaseHandler']) -> Type['BaseHandler']:
        """注册工具类
        
        Args:
            tool_class: 要注册的工具类
            
        Returns:
            返回注册的工具类,方便作为装饰器使用
        """
        tool = tool_class()
        cls._tools[tool.name] = tool
        return tool_class
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. It states the tool executes SQL on MySQL5.6, but doesn't disclose critical behavioral traits: whether it's read-only or can modify data, authentication requirements, transaction handling, error behavior, result format, or any rate limits. '执行SQL' implies both read and write operations are possible, but this isn't clarified.

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 - a single sentence that directly states the tool's purpose without any wasted words. It's front-loaded with the core functionality and includes the database specification. Every word earns its place.

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 SQL execution tool with no annotations and no output schema, the description is incomplete. It doesn't address critical context: what types of SQL are supported, whether it's for read-only queries or data modification, what the return format looks like, error handling, or security implications. The agent lacks sufficient information to use this tool safely and 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%, with the single parameter 'query' documented as '要执行的SQL语句' (SQL statement to execute). The description adds no additional parameter semantics beyond what the schema provides. The baseline score of 3 is appropriate when the schema already fully documents parameters.

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 ('执行SQL' - execute SQL) and specifies the target resource ('在MySQL5.6s数据库上' - on MySQL5.6 database). It distinguishes from sibling tools that focus on metadata retrieval (get_table_name, get_table_desc, etc.) rather than SQL execution. However, it doesn't explicitly differentiate from potential non-sibling SQL execution tools.

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. It doesn't mention when this tool is appropriate, what types of SQL statements it supports (SELECT, INSERT, UPDATE, DDL, etc.), or any prerequisites or limitations. The agent must infer usage from the purpose alone.

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/wenb1n-dev/mysql_mcp_server_pro'

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