Skip to main content
Glama
ImRieul

MySQL MCP Server

by ImRieul

execute

Execute data modification SQL statements (INSERT, UPDATE, DELETE, DDL). Validate without executing by setting dryRun=true; confirm destructive operations like DROP or TRUNCATE before execution.

Instructions

Execute a data modification SQL statement (INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, etc.). Set dryRun=true to validate without executing — uses EXPLAIN for DML, or previews the SQL for DDL. Always confirm destructive operations (DROP, TRUNCATE, DELETE without WHERE) with the user before executing. Not available in read-only mode.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYesThe SQL statement to execute. SELECT statements are not allowed here; use the "query" tool instead.
dryRunNoIf true, validates the statement via EXPLAIN without executing it. Defaults to false.

Implementation Reference

  • The main handler function for the 'execute' tool. It checks read-only mode, validates SQL input, rejects SELECT/WITH statements, supports dry-run (EXPLAIN for DML, preview for DDL), and runs the actual SQL returning affectedRows/changedRows.
    export function createExecuteHandler(runner: QueryRunner, isReadonly: boolean) {
      return async ({ sql, dryRun }: { sql: string; dryRun?: boolean }) => {
        if (isReadonly) {
          return {
            isError: true as const,
            content: [
              {
                type: 'text' as const,
                text: 'Error: Server is in read-only mode. Data modification is not allowed.',
              },
            ],
          };
        }
    
        const validation = validateSql(sql);
        if (!validation.valid) {
          return {
            isError: true as const,
            content: [{ type: 'text' as const, text: validation.message! }],
          };
        }
    
        const normalized = sql.trim().toUpperCase();
        if (normalized.startsWith('SELECT') || normalized.startsWith('WITH')) {
          return {
            isError: true as const,
            content: [
              {
                type: 'text' as const,
                text: 'Error: Use the "query" tool for SELECT statements.',
              },
            ],
          };
        }
    
        if (dryRun) {
          const DDL_PREFIXES = ['CREATE', 'DROP', 'ALTER', 'TRUNCATE', 'RENAME'];
          const isDdl = DDL_PREFIXES.some((p) => normalized.startsWith(p));
    
          if (isDdl) {
            return {
              content: [
                {
                  type: 'text' as const,
                  text: `[dry-run] SQL preview (DDL cannot be validated via EXPLAIN):\n${sql}`,
                },
              ],
            };
          }
    
          try {
            const [rows] = await runner.query(`EXPLAIN ${sql}`);
            return {
              content: [
                {
                  type: 'text' as const,
                  text: `[dry-run] Statement validated via EXPLAIN:\n${JSON.stringify(rows, null, 2)}`,
                },
              ],
            };
          } catch (error) {
            return {
              isError: true as const,
              content: [{ type: 'text' as const, text: `[dry-run] Validation failed: ${formatError(error)}` }],
            };
          }
        }
    
        try {
          const [result] = await runner.query(sql);
          const r = result as unknown as Record<string, unknown>;
          return {
            content: [
              { type: 'text' as const, text: `affectedRows: ${r.affectedRows}, changedRows: ${r.changedRows ?? 0}` },
            ],
          };
        } catch (error) {
          return {
            isError: true as const,
            content: [{ type: 'text' as const, text: formatError(error) }],
          };
        }
      };
    }
  • Tool name ('execute'), description, and Zod-based input schema (sql string, dryRun optional boolean).
    export const executeToolName = 'execute';
    
    export const executeToolConfig = {
      title: 'Execute',
      description:
        'Execute a data modification SQL statement (INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, etc.). ' +
        'Set dryRun=true to validate without executing — uses EXPLAIN for DML, or previews the SQL for DDL. ' +
        'Always confirm destructive operations (DROP, TRUNCATE, DELETE without WHERE) with the user before executing. ' +
        'Not available in read-only mode.',
      inputSchema: {
        sql: z
          .string()
          .describe('The SQL statement to execute. SELECT statements are not allowed here; use the "query" tool instead.'),
        dryRun: z
          .boolean()
          .optional()
          .describe('If true, validates the statement via EXPLAIN without executing it. Defaults to false.'),
      },
    };
  • Registers the 'execute' tool on the MCP server with its name, description, input schema, and handler.
    server.tool(
      executeToolName,
      executeToolConfig.description,
      executeToolConfig.inputSchema,
      createExecuteHandler(runner, readonly),
    );
  • Validates SQL input for control characters before execution.
    export function validateSql(sql: string): ValidationResult {
      if (hasControlChars(sql)) {
        return {
          valid: false,
          message: 'Error: SQL contains control characters. Remove non-printable characters (tab and newline are allowed).',
        };
      }
      return { valid: true };
    }
  • Formats error messages with contextual hints for common MySQL errors.
    export function formatError(error: unknown): string {
      const message = error instanceof Error ? error.message : String(error);
      const hint = HINTS.find(([pattern]) => pattern.test(message));
      return hint ? `Error: ${message}\n${hint[1]}` : `Error: ${message}`;
    }
Behavior5/5

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

With no annotations, the description fully discloses behavioral traits: it executes modifications, dryRun uses EXPLAIN for DML/previews for DDL, requires user confirmation for destructive ops, and is restricted in read-only mode.

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?

Three concise sentences, front-loaded with purpose. Each sentence adds necessary context without redundancy.

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

Completeness5/5

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

Given the tool's complexity and safety implications, the description covers purpose, usage, validation, and restrictions. While no output schema exists, the behavior is adequately described for an agent.

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?

Schema coverage is 100% (baseline 3). The description adds value by explaining dryRun's behavior (EXPLAIN for DML, preview for DDL) and reinforcing that sql is for modification statements, not SELECT.

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 it executes data modification SQL statements (INSERT, UPDATE, DELETE, etc.) and explicitly distinguishes from the 'query' tool by excluding SELECT. It names specific SQL verbs, providing a precise scope.

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

Usage Guidelines5/5

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

It provides when to use (data modification SQL), when not to use (SELECT, use query instead), and includes safety guidelines: dryRun for validation, confirmation for destructive operations, and unavailability in read-only mode.

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/ImRieul/mysql-mcp-server'

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