Skip to main content
Glama
alittleyellowkevin

MySQL MCP Server

run_sql_query

Execute SQL SELECT queries to retrieve data from a MySQL database. This tool performs read-only operations, returning query results in JSON format for analysis and reporting.

Instructions

执行只读 SQL 查询(仅限 SELECT 语句)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes要执行的 SQL SELECT 查询语句

Implementation Reference

  • Main handler function that validates the SQL query arguments, ensures it's a SELECT query, executes it using the MySQL connection pool, and returns the results as JSON or an error message.
    private async handleReadQuery(request: any, transactionId: string) {
      if (!isValidSqlQueryArgs(request.params.arguments)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'SQL 查询参数无效。'
        );
      }
    
      const query = request.params.arguments.query;
    
      if (!isReadOnlyQuery(query)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'run_sql_query 工具仅允许 SELECT 查询。'
        );
      }
    
      console.error(`[${transactionId}] 执行 SELECT 查询: ${query}`);
    
      try {
        const [rows] = await this.pool.query(query);
        console.error(`[${transactionId}] 查询执行成功`);
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(rows, null, 2),
            },
          ],
        };
      } catch (error) {
        console.error(`[${transactionId}] 查询出错:`, error);
        if (error instanceof Error) {
          return {
            content: [
              {
                type: 'text',
                text: `MySQL 错误: ${error.message}`,
              },
            ],
            isError: true,
          };
        }
        throw error;
      }
    }
  • Tool schema definition including input schema for 'query' parameter, provided in the ListTools response.
    {
      name: 'run_sql_query',
      description: '执行只读 SQL 查询(仅限 SELECT 语句)',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description: '要执行的 SQL SELECT 查询语句',
          },
        },
        required: ['query'],
      },
    },
  • src/index.ts:190-214 (registration)
    Tool call request handler that dispatches to handleReadQuery based on tool name 'run_sql_query'.
    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      const transactionId = generateTransactionId();
      console.error(`[${transactionId}] 正在处理请求: ${request.params.name}`);
    
      // 根据工具类型分发处理
      switch (request.params.name) {
        case 'run_sql_query':
          return this.handleReadQuery(request, transactionId);
        case 'create_table':
          return this.handleCreateTable(request, transactionId);
        case 'insert_data':
          return this.handleInsertData(request, transactionId);
        case 'update_data':
          return this.handleUpdateData(request, transactionId);
        case 'delete_data':
          return this.handleDeleteData(request, transactionId);
        case 'execute_sql':
          return this.handleExecuteSql(request, transactionId);
        default:
          throw new McpError(
            ErrorCode.MethodNotFound,
            `未知工具: ${request.params.name}`
          );
      }
    });
  • Helper functions and interface for validating SQL query arguments and checking if it's a read-only SELECT query.
    interface SqlQueryArgs {
      query: string;
    }
    
    // 校验 SQL 查询参数是否合法
    const isValidSqlQueryArgs = (args: any): args is SqlQueryArgs =>
      typeof args === 'object' &&
      args !== null &&
      typeof args.query === 'string';
    
    // 判断是否为只读查询(SELECT)
    const isReadOnlyQuery = (query: string): boolean =>
      query.trim().toLowerCase().startsWith('select');
Behavior3/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It clearly states the tool is read-only and limited to SELECT statements, which is helpful context. However, it lacks details on potential behavioral traits like error handling, result formatting, timeouts, or authentication requirements, leaving gaps for an AI agent.

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 and front-loaded with a single sentence in Chinese that directly states the tool's function and limitations. There is no wasted text, and every word earns its place by clarifying the scope (read-only, SELECT-only).

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?

Given the tool's complexity (SQL execution), lack of annotations, and no output schema, the description is minimally adequate. It covers the basic purpose and restrictions but misses details like return format, error cases, or performance considerations. For a tool with no structured output documentation, more context would be beneficial.

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?

The input schema has 100% description coverage, with the 'query' parameter documented as '要执行的 SQL SELECT 查询语句' (SQL SELECT query statement to execute). The description doesn't add any additional meaning beyond what the schema provides, such as syntax examples or constraints. Given the high schema coverage, a baseline score of 3 is appropriate.

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 tool's purpose as '执行只读 SQL 查询(仅限 SELECT 语句)', which translates to 'execute read-only SQL queries (only SELECT statements)'. This specifies both the verb ('execute') and resource ('SQL queries') with a clear restriction to SELECT statements. However, it doesn't explicitly differentiate from sibling tools like 'execute_sql', which might handle other SQL operations.

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

Usage Guidelines4/5

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

The description provides clear context for when to use this tool by specifying '只读' (read-only) and '仅限 SELECT 语句' (only SELECT statements). This implicitly guides usage for read operations versus siblings like 'insert_data' or 'update_data' for writes. However, it doesn't explicitly name alternatives or state when not to use it, such as for non-SELECT queries.

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/alittleyellowkevin/Mysql-MCP'

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