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
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | SQL query to execute | |
| parameters | No | Query parameters (optional) |
Implementation Reference
- src/tools/execute-query.ts:7-49 (handler)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, } } } - src/schemas.ts:3-9 (schema)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)'), }) - src/tools/index.ts:27-31 (registration)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), }, - src/services/SqlServerMCPService.ts:73-76 (registration)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 ?? {}) }) - src/tools/execute-query.ts:17-21 (helper)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) }