Skip to main content
Glama
elgentos

Magento 2 Development MCP Server

by elgentos

Database Query

db-query

Execute SQL queries directly on Magento 2 database to retrieve, analyze, or modify data with output in table, JSON, or CSV format.

Instructions

Execute SQL queries directly on Magento 2 database

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
formatNoOutput formattable
queryYesSQL query to execute

Implementation Reference

  • The handler function that implements the core logic of the 'db-query' tool by executing a magerun2 db:query command with the provided SQL query and format.
    async ({ query, format = "table" }) => {
      const command = `magerun2 db:query --format=${format} "${query}"`;
      const result = await executeMagerun2Command(command, format === "json");
    
      if (!result.success) {
        return {
          content: [{
            type: "text",
            text: result.error
          }],
          isError: true
        };
      }
    
      const responseText = format === "json"
        ? `Query results (${format} format):\n\n${JSON.stringify(result.data, null, 2)}`
        : `Query results (${format} format):\n\n${result.data}`;
    
      return {
        content: [{
          type: "text",
          text: responseText
        }]
      };
    }
  • The input schema defining the parameters for the 'db-query' tool: 'query' (SQL string) and 'format' (table/json/csv with default 'table').
      query: z.string()
        .describe("SQL query to execute"),
      format: z.enum(["table", "json", "csv"])
        .default("table")
        .describe("Output format")
    }
  • src/index.ts:937-975 (registration)
    The registration of the 'db-query' tool using server.registerTool, including title, description, input schema, and handler reference.
    server.registerTool(
      "db-query",
      {
        title: "Database Query",
        description: "Execute SQL queries directly on Magento 2 database",
        inputSchema: {
          query: z.string()
            .describe("SQL query to execute"),
          format: z.enum(["table", "json", "csv"])
            .default("table")
            .describe("Output format")
        }
      },
      async ({ query, format = "table" }) => {
        const command = `magerun2 db:query --format=${format} "${query}"`;
        const result = await executeMagerun2Command(command, format === "json");
    
        if (!result.success) {
          return {
            content: [{
              type: "text",
              text: result.error
            }],
            isError: true
          };
        }
    
        const responseText = format === "json"
          ? `Query results (${format} format):\n\n${JSON.stringify(result.data, null, 2)}`
          : `Query results (${format} format):\n\n${result.data}`;
    
        return {
          content: [{
            type: "text",
            text: responseText
          }]
        };
      }
    );
  • The helper function 'executeMagerun2Command' used by the db-query handler (and other tools) to run magerun2 CLI commands safely with JSON parsing, timeouts, and Magento-specific error handling.
    /**
     * Helper function to execute magerun2 commands with consistent error handling
     */
    async function executeMagerun2Command(command: string, parseJson: boolean = false): Promise<{
      success: true;
      data: any;
      rawOutput: string;
    } | {
      success: false;
      error: string;
      isError: true;
    }> {
      try {
        const { stdout, stderr } = await execAsync(command, {
          cwd: process.cwd(),
          timeout: 30000 // 30 second timeout
        });
    
        if (stderr && stderr.trim()) {
          console.error("magerun2 stderr:", stderr);
        }
    
        if (parseJson) {
          try {
            return { success: true, data: JSON.parse(stdout), rawOutput: stdout };
          } catch (parseError) {
            return {
              success: false,
              error: `Error parsing magerun2 JSON output: ${parseError}\n\nRaw output:\n${stdout}`,
              isError: true
            };
          }
        }
    
        return { success: true, data: stdout.trim(), rawOutput: stdout };
    
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
    
        // Check if magerun2 is not found
        if (errorMessage.includes("command not found") || errorMessage.includes("not recognized")) {
          return {
            success: false,
            error: "Error: magerun2 command not found. Please ensure n98-magerun2 is installed and available in your PATH.\n\nInstallation instructions: https://github.com/netz98/n98-magerun2",
            isError: true
          };
        }
    
        // Check if not in Magento directory
        if (errorMessage.includes("not a Magento installation") || errorMessage.includes("app/etc/env.php")) {
          return {
            success: false,
            error: "Error: Current directory does not appear to be a Magento 2 installation. Please run this command from your Magento 2 root directory.",
            isError: true
          };
        }
    
        return {
          success: false,
          error: `Error executing magerun2 command: ${errorMessage}`,
          isError: true
        };
      }
    }
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 queries but doesn't mention critical aspects like required permissions, whether it's read-only or can modify data, potential risks of direct database access, or any rate limits. This leaves significant gaps for safe and effective use.

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 a single, efficient sentence that directly states the tool's function without unnecessary words. It's appropriately sized and front-loaded, making it easy to understand immediately.

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?

Given the complexity of executing SQL queries on a production database, the description is insufficient. With no annotations, no output schema, and no guidance on usage or behavior, it fails to provide the completeness needed for safe operation. The agent lacks information about return values, error handling, and operational constraints.

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%, so the input schema fully documents both parameters (query and format). The description doesn't add any meaningful parameter semantics beyond what's already in the schema, such as SQL dialect specifics or format implications. The baseline score of 3 reflects adequate but not enhanced parameter understanding.

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 ('Execute SQL queries') and target resource ('Magento 2 database'), making the purpose unambiguous. However, it doesn't differentiate from sibling tools like 'setup-db-status' or other database-related operations, which would require explicit comparison to achieve a perfect score.

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. With many sibling tools available (e.g., 'setup-db-status', 'config-store-get'), there's no indication of appropriate contexts, prerequisites, or exclusions for this direct SQL execution tool.

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/elgentos/magento2-dev-mcp'

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