Skip to main content
Glama
vini-cius

SQL Server MCP Service

by vini-cius

execute_query

Run SQL queries on SQL Server with optional parameters. Provides built-in protection against SQL injection and destructive operations for secure database interaction.

Instructions

Executes a SQL query in SQL Server

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSQL query to execute
parametersNoQuery parameters (optional)

Implementation Reference

  • The core handler function that executes a SQL query. It takes a database connection, query string, and optional parameters, sanitizes parameters, validates the query, and returns the result as JSON or an error.
    export async function executeQuery(
      db: DatabaseConnection,
      query: string,
      parameters?: Record<string, unknown>
    ): Promise<CallToolResult> {
      try {
        const pool = db.getPool()
        const request = pool.request()
    
        if (parameters) {
          const sanitizedParams = sanitizeParameters(parameters)
    
          for (const [key, value] of Object.entries(sanitizedParams)) {
            request.input(key, value)
          }
        }
    
        if (!validateQuery(query)) {
          throw new Error('Potentially destructive command blocked.')
        }
    
        const result = await request.query(query)
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(result.recordset, null, 2),
            },
          ],
        }
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: `Erro: ${error instanceof Error ? error.message : 'Erro desconhecido'}`,
            },
          ],
          isError: true,
        }
      }
    }
  • Zod schema for execute_query input validation: requires a 'query' string, and accepts optional 'parameters' as a record of string/number/boolean values.
    export const executeQueryInput = z.object({
      query: z.string().describe('SQL query to execute'),
      parameters: z
        .record(z.string(), z.union([z.string(), z.number(), z.boolean()]))
        .optional()
        .describe('Query parameters (optional)'),
    })
  • Registers the tool with name 'execute_query', description, and JSON schema converted from the Zod schema.
    {
      name: 'execute_query',
      description: 'Executes a SQL query in SQL Server',
      inputSchema: zodToJsonSchema(executeQueryInput),
    },
  • Maps the 'execute_query' tool name to a handler that extracts query and parameters from args and calls the executeQuery function.
    handlers.set('execute_query', async (database, args) => {
      const { query, parameters } = args as ExecuteQueryInput
      return await executeQuery(database, query, parameters ?? {})
    })
  • Uses sanitizeParameters to sanitize user-provided parameters before passing them to the SQL request.
    const sanitizedParams = sanitizeParameters(parameters)
    
    for (const [key, value] of Object.entries(sanitizedParams)) {
      request.input(key, value)
    }
Behavior2/5

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

With no annotations, the description must disclose behavioral traits but only states it 'executes a SQL query'. It fails to mention important aspects such as potential destructiveness, required permissions, or side effects of arbitrary SQL execution.

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

Conciseness3/5

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

The description is very concise (one sentence) with no fluff, but it is too minimal for a tool that can execute arbitrary SQL. It does not earn its place by providing sufficient information.

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 (potential for data modification, error handling, return format), the description is incomplete. It does not explain what the tool returns or any limitations, especially with no output schema.

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 schema already documents both parameters. The description adds no additional meaning beyond what the schema provides, so it meets the baseline without adding value.

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 ('executes') and the resource ('SQL query in SQL Server'), making the purpose understandable. However, it does not differentiate from the sibling tool 'execute_procedure', which is a similar operation.

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 like 'execute_procedure'. The description lacks context about use cases, prerequisites, or conditions.

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/vini-cius/mcp-sqlserver'

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