Skip to main content
Glama
michaelyuwh

Enhanced MCP MSSQL Server

by michaelyuwh

mssql_validate_query

Validate SQL queries for security vulnerabilities and syntax errors before execution. Includes optional optimization suggestions to improve query performance.

Instructions

Validate a SQL query for security and syntax without executing it

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSQL query to validate
includeOptimizationsNoInclude optimization suggestions (default: false)

Implementation Reference

  • Main handler function for mssql_validate_query tool. Performs security validation via SecurityValidator, adds performance warnings and optimization suggestions without executing the query or requiring a database connection.
    private async handleValidateQuery(args: any) {
      const { query, includeOptimizations = false } = args;
    
      try {
        const validation = this.securityValidator.validateQuery(query);
        const sanitizedQuery = this.securityValidator.sanitizeQuery(query);
        
        const result: any = {
          isValid: validation.isValid,
          originalQuery: query,
          sanitizedQuery: sanitizedQuery,
          errors: validation.errors,
          warnings: [],
          suggestions: []
        };
    
        // Basic query analysis
        const trimmedQuery = query.trim().toLowerCase();
        
        // Check for potential performance issues
        if (trimmedQuery.includes('select *')) {
          result.warnings.push('Using SELECT * may impact performance - consider specifying specific columns');
        }
        
        if (trimmedQuery.includes('like \'%') || trimmedQuery.includes('like "%')) {
          result.warnings.push('Leading wildcard in LIKE clause may cause full table scan');
        }
    
        if (!trimmedQuery.includes('where') && (trimmedQuery.includes('update') || trimmedQuery.includes('delete'))) {
          result.errors.push('UPDATE/DELETE statements without WHERE clause are dangerous');
          result.isValid = false;
        }
    
        if (includeOptimizations) {
          // Basic optimization suggestions
          if (trimmedQuery.includes('order by') && !trimmedQuery.includes('top')) {
            result.suggestions.push('Consider adding TOP clause when using ORDER BY for better performance');
          }
        }
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(result, null, 2),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                isValid: false,
                error: error instanceof Error ? error.message : String(error)
              }, null, 2),
            },
          ],
          isError: true,
        };
      }
    }
  • Input schema definition for the mssql_validate_query tool, specifying query string (required) and optional optimizations flag.
    inputSchema: {
      type: 'object',
      properties: {
        query: { type: 'string', description: 'SQL query to validate' },
        includeOptimizations: { type: 'boolean', description: 'Include optimization suggestions (default: false)', default: false },
      },
      required: ['query'],
    },
  • src/index.ts:396-407 (registration)
    Tool registration in the ListToolsRequestSchema handler's tools array.
    {
      name: 'mssql_validate_query',
      description: 'Validate a SQL query for security and syntax without executing it',
      inputSchema: {
        type: 'object',
        properties: {
          query: { type: 'string', description: 'SQL query to validate' },
          includeOptimizations: { type: 'boolean', description: 'Include optimization suggestions (default: false)', default: false },
        },
        required: ['query'],
      },
    },
  • src/index.ts:451-452 (registration)
    Dispatcher switch case in CallToolRequestSchema handler that routes to the tool handler.
    case 'mssql_validate_query':
      return await this.handleValidateQuery(args);
  • SecurityValidator class providing validateQuery and sanitizeQuery methods used by the handler for security checks.
    class SecurityValidator {
      private config: SecurityConfig;
    
      constructor(config: SecurityConfig) {
        this.config = config;
      }
    
      validateQuery(query: string): { isValid: boolean; errors: string[] } {
        const errors: string[] = [];
    
        if (!this.config.enableQueryValidation) {
          return { isValid: true, errors: [] };
        }
    
        // Check query length
        if (query.length > this.config.maxQueryLength) {
          errors.push(`Query exceeds maximum length of ${this.config.maxQueryLength} characters`);
        }
    
        // Check for blocked keywords
        const lowercaseQuery = query.toLowerCase();
        for (const keyword of this.config.blockedKeywords) {
          if (lowercaseQuery.includes(keyword.toLowerCase())) {
            errors.push(`Query contains blocked keyword: ${keyword}`);
          }
        }
    
        // Check for dangerous patterns
        const dangerousPatterns = [
          /;\s*(drop|truncate|alter)\s+/i,
          /union\s+.*select/i,
          /\/\*.*\*\//g, // Block comments (potential SQL injection)
          /--.*$/gm,     // Line comments in suspicious contexts
          /xp_[\w]+/i,
          /sp_[\w]+/i,
        ];
    
        for (const pattern of dangerousPatterns) {
          if (pattern.test(query)) {
            errors.push(`Query contains potentially dangerous pattern: ${pattern.source}`);
          }
        }
    
        // Validate allowed operations
        if (this.config.allowedOperations.length > 0) {
          const firstWord = query.trim().split(/\s+/)[0]?.toUpperCase();
          if (firstWord && !this.config.allowedOperations.includes(firstWord)) {
            errors.push(`Operation '${firstWord}' is not allowed. Allowed operations: ${this.config.allowedOperations.join(', ')}`);
          }
        }
    
        return { isValid: errors.length === 0, errors };
      }
    
      sanitizeQuery(query: string): string {
        // Basic sanitization
        return query
          .replace(/--.*$/gm, '') // Remove line comments
          .replace(/\/\*.*?\*\//g, '') // Remove block comments
          .trim();
      }
    }
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It discloses that validation is for 'security and syntax' and occurs 'without executing it', which is useful behavioral context. However, it doesn't mention error handling, response format, or performance implications (e.g., timeouts), leaving some gaps for a tool with no annotation coverage.

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 front-loads the core purpose ('Validate a SQL query') and adds key qualifiers ('for security and syntax without executing it'). Every word earns its place with zero waste, making it highly concise and well-structured.

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

Completeness4/5

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

Given the tool's moderate complexity (validation without execution), no annotations, and no output schema, the description is mostly complete. It covers the purpose and key behavioral trait (non-execution) but lacks details on output format or error handling. It's adequate but could be more comprehensive for full agent guidance.

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 fully. The description doesn't add any meaning beyond what the schema provides (e.g., it doesn't explain what 'security' validation entails or give examples). Baseline 3 is appropriate as the schema does the heavy lifting.

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 the specific action ('validate a SQL query') and the resource ('SQL query'), distinguishing it from siblings like mssql_query (which executes) and mssql_describe_table (which inspects structure). It explicitly notes the validation is for 'security and syntax without executing it', making the purpose unambiguous.

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?

The description explicitly states when to use this tool: to validate queries 'without executing it', which directly contrasts with mssql_query (which executes). This provides clear guidance on choosing this tool over its sibling for pre-execution checks, with no misleading or missing exclusions.

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/michaelyuwh/mcp-mssql-connector'

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