insert_data
Execute SQL INSERT INTO statements to add data into MySQL database tables using the MCP server for streamlined data management and JSON-formatted results.
Instructions
向 MySQL 数据库表插入数据
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | 要执行的 SQL INSERT INTO 语句 |
Input Schema (JSON Schema)
{
"properties": {
"query": {
"description": "要执行的 SQL INSERT INTO 语句",
"type": "string"
}
},
"required": [
"query"
],
"type": "object"
}
Implementation Reference
- src/index.ts:320-369 (handler)The main handler function for the 'insert_data' tool. Validates input, checks if query is INSERT INTO, executes the SQL query on the MySQL connection pool, and returns formatted success or error content.private async handleInsertData(request: any, transactionId: string) { if (!isValidSqlQueryArgs(request.params.arguments)) { throw new McpError( ErrorCode.InvalidParams, 'SQL 查询参数无效。' ); } const query = request.params.arguments.query; if (!isInsertQuery(query)) { throw new McpError( ErrorCode.InvalidParams, 'insert_data 工具仅允许 INSERT INTO 查询。' ); } console.error(`[${transactionId}] 执行 INSERT 查询: ${query}`); try { const [result] = await this.pool.query(query); console.error(`[${transactionId}] 数据插入成功`); return { content: [ { type: 'text', text: JSON.stringify({ success: true, message: '数据插入成功', result }, null, 2), }, ], }; } catch (error) { console.error(`[${transactionId}] 查询出错:`, error); if (error instanceof Error) { return { content: [ { type: 'text', text: `MySQL 错误: ${error.message}`, }, ], isError: true, }; } throw error; }
- src/index.ts:130-143 (schema)Tool schema definition including name, description, and input schema for the 'insert_data' tool, specifying an object with a required 'query' string property.{ name: 'insert_data', description: '向 MySQL 数据库表插入数据', inputSchema: { type: 'object', properties: { query: { type: 'string', description: '要执行的 SQL INSERT INTO 语句', }, }, required: ['query'], }, },
- src/index.ts:200-201 (registration)Registration of the 'insert_data' handler in the switch statement within the CallToolRequestSchema request handler.case 'insert_data': return this.handleInsertData(request, transactionId);
- src/index.ts:40-41 (helper)Helper function to validate if a SQL query is an INSERT INTO statement, used by the insert_data handler.const isInsertQuery = (query: string): boolean => query.trim().toLowerCase().startsWith('insert into');
- src/index.ts:26-29 (helper)Helper function to validate SQL query arguments, ensuring it has a 'query' string property, used by the insert_data handler.const isValidSqlQueryArgs = (args: any): args is SqlQueryArgs => typeof args === 'object' && args !== null && typeof args.query === 'string';