Skip to main content
Glama
Liu-creators

MySQL MCP

by Liu-creators

insert_data

Insert records into a MySQL table by providing a table name and a dictionary of field-value pairs. Optionally specify database connection configuration for custom setups.

Instructions

向表中插入数据

Args:
    table_name: 表名
    data: 要插入的数据,字段名和值的字典
    db_config: 数据库连接配置参数,如果为None则使用默认配置
    
Returns:
    包含插入结果的字典

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
table_nameYes
dataYes
db_configNo

Implementation Reference

  • The async function `insert_data` that executes the tool logic. It is decorated with @mcp.tool(), connects to MySQL, builds an INSERT SQL statement from the provided data dict, executes it, commits, and returns the result with inserted_id. Includes error handling for common MySQL errors.
    @mcp.tool()
    async def insert_data(table_name: str, data: Dict[str, Any], db_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """向表中插入数据
        
        Args:
            table_name: 表名
            data: 要插入的数据,字段名和值的字典
            db_config: 数据库连接配置参数,如果为None则使用默认配置
            
        Returns:
            包含插入结果的字典
        """
        if not table_name or not data:
            return {"error": "表名和数据不能为空"}
            
        try:
            conn = get_connection(db_config)
            cursor = conn.cursor()
            
            columns = ", ".join(data.keys())
            placeholders = ", ".join(["%s"] * len(data))
            values = list(data.values())
            
            insert_sql = f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})"
            cursor.execute(insert_sql, values)
            conn.commit()
            
            return {
                "success": True,
                "inserted_id": cursor.lastrowid,
                "message": f"数据成功插入到表 {table_name}"
            }
        except Error as e:
            error_message = f"插入数据失败: {str(e)}"
            if "doesn't exist" in str(e):
                error_message += f"\n原因:表 {table_name} 不存在"
            elif "Unknown column" in str(e):
                error_message += "\n原因:插入数据中包含表中不存在的列"
            elif "cannot be null" in str(e):
                error_message += "\n原因:某个NOT NULL字段被设置为NULL值"
            elif "Duplicate entry" in str(e):
                error_message += "\n原因:插入的数据违反了唯一键约束"
            elif "Data too long" in str(e):
                error_message += "\n原因:插入的数据超出了字段的长度限制"
            return {"error": error_message}
        except Exception as e:
            return {"error": f"插入数据时发生未知错误: {str(e)}"}
        finally:
            if 'conn' in locals() and conn.is_connected():
                cursor.close()
                conn.close()
  • mysql-mcp.py:299-299 (registration)
    The @mcp.tool() decorator on line 299 registers `insert_data` as an MCP tool with the FastMCP server instance named 'mcp'.
    @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 states that the tool inserts data (implying mutation) but does not disclose side effects, permissions, error handling, or result format beyond a generic dictionary. For a mutation tool, more transparency is needed.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise with a front-loaded purpose line followed by structured Args/Returns sections. However, the docstring format is slightly verbose; still, it effectively conveys the necessary information without waste.

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?

The description covers parameter semantics but lacks details on return values (vague 'dict containing insert results'), error conditions, and prerequisites (e.g., table must exist). For a 3-parameter tool with no output schema, it is minimally adequate but not comprehensive.

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

Parameters4/5

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

With 0% schema description coverage, the tool description adds significant meaning to each parameter: table_name is the table name, data is a dictionary of field names and values, and db_config is an optional database connection config. This goes beyond the schema's type-only information.

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

Purpose5/5

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

The description clearly states '向表中插入数据' (insert data into table), which is a specific verb+resource combination. This distinguishes it from sibling tools like create_table, update_data, and delete_data.

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?

No guidance is provided on when to use this tool versus alternatives. There is no mention of context, prerequisites, or scenarios where other tools would be more appropriate.

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/Liu-creators/mysql-mcp'

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