Skip to main content
Glama
michaelyuwh

Enhanced MCP MSSQL Server

by michaelyuwh

mssql_query

Execute read-only SELECT queries on Microsoft SQL Server databases to retrieve data securely with connection parameters and row limits.

Instructions

Execute a read-only SELECT query

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
serverYesMSSQL Server hostname or IP address
portNoPort number (default: 1433)
userYesUsername for authentication
passwordYesPassword for authentication
databaseYesDatabase name
queryYesSQL SELECT query to execute
limitNoMaximum number of rows to return (default: 100)
encryptNoUse encrypted connection (default: true)
trustServerCertificateNoTrust server certificate (default: true)

Implementation Reference

  • The primary handler function for the 'mssql_query' tool. It validates the input query for security, establishes a connection to the MSSQL database, optionally adds a TOP limit clause, executes the query, and returns the results with metadata including row count and execution time.
    private async handleQuery(args: any) {
      const startTime = Date.now();
      this.metrics.totalQueries++;
    
      try {
        const config = ConnectionSchema.parse(args);
        const { query, limit = 1000 } = args;
        
        // Enhanced security validation
        const validation = this.securityValidator.validateQuery(query);
        if (!validation.isValid) {
          throw new MCPError(
            `Query validation failed: ${validation.errors.join(', ')}`,
            'QUERY_VALIDATION_ERROR',
            { errors: validation.errors }
          );
        }
    
        const sanitizedQuery = this.securityValidator.sanitizeQuery(query);
    
        const pool = await this.getConnection(config);
        const request = pool.request();
        
        // Add TOP clause if not already present and limit is specified
        let finalQuery = sanitizedQuery;
        const trimmedQuery = sanitizedQuery.trim().toLowerCase();
        
        if (limit && !trimmedQuery.includes(' top ') && trimmedQuery.startsWith('select')) {
          finalQuery = sanitizedQuery.replace(/^select\s+/i, `SELECT TOP ${Math.min(limit, this.config.security.maxRowsPerQuery)} `);
        }
    
        const result = await request.query(`USE [${config.database}]; ${finalQuery}`);
    
        // Update metrics
        this.metrics.avgExecutionTime = (this.metrics.avgExecutionTime + (Date.now() - startTime)) / this.metrics.totalQueries;
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                server: config.server,
                database: config.database,
                query: finalQuery,
                rowCount: result.recordset.length,
                executionTime: Date.now() - startTime,
                data: result.recordset,
              }, null, 2),
            },
          ],
        };
      } catch (error) {
        this.metrics.failedQueries++;
        throw error;
      }
    }
  • src/index.ts:323-341 (registration)
    Tool registration in the ListToolsRequestSchema handler, defining the name, description, and input schema for 'mssql_query'.
    {
      name: 'mssql_query',
      description: 'Execute a read-only SELECT query',
      inputSchema: {
        type: 'object',
        properties: {
          server: { type: 'string', description: 'MSSQL Server hostname or IP address' },
          port: { type: 'number', description: 'Port number (default: 1433)', default: 1433 },
          user: { type: 'string', description: 'Username for authentication' },
          password: { type: 'string', description: 'Password for authentication' },
          database: { type: 'string', description: 'Database name' },
          query: { type: 'string', description: 'SQL SELECT query to execute' },
          limit: { type: 'number', description: 'Maximum number of rows to return (default: 100)', default: 100 },
          encrypt: { type: 'boolean', description: 'Use encrypted connection (default: true)', default: true },
          trustServerCertificate: { type: 'boolean', description: 'Trust server certificate (default: true)', default: true },
        },
        required: ['server', 'user', 'password', 'database', 'query'],
      },
    },
  • Zod schema used to validate and parse connection parameters from the tool input arguments.
    const ConnectionSchema = z.object({
      server: z.string().describe('MSSQL Server hostname or IP address'),
      port: z.number().default(1433).describe('Port number (default: 1433)'),
      user: z.string().describe('Username for authentication'),
      password: z.string().describe('Password for authentication'),
      database: z.string().optional().describe('Database name (optional)'),
      encrypt: z.boolean().default(true).describe('Use encrypted connection'),
      trustServerCertificate: z.boolean().default(true).describe('Trust server certificate'),
    });
  • src/index.ts:443-444 (registration)
    Dispatch case in the CallToolRequestSchema switch statement that routes 'mssql_query' calls to the handleQuery method.
    case 'mssql_query':
      return await this.handleQuery(args);
  • SecurityValidator class providing query validation and sanitization used in the mssql_query handler to prevent SQL injection and enforce security policies.
    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();
      }
    }
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 'read-only SELECT query' which implies safety and query type, but lacks details on execution limits, error handling, result format, or performance implications. This is inadequate for a tool with 9 parameters and database operations.

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, clear sentence with zero wasted words. It's front-loaded with the core functionality ('Execute a read-only SELECT query'), making it immediately actionable without unnecessary elaboration.

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?

For a database query tool with 9 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain what the tool returns (e.g., result set format), error conditions, or important behavioral aspects like transaction handling or timeout settings, leaving significant gaps for agent understanding.

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 fully documents all 9 parameters. The description adds no parameter-specific information beyond implying the query must be SELECT-type. This meets the baseline for high schema coverage but doesn't enhance understanding of parameter interactions or constraints.

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') and resource ('a read-only SELECT query'), making the purpose immediately understandable. It doesn't explicitly differentiate from sibling tools like mssql_validate_query or mssql_sample_data, which prevents 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 like mssql_validate_query (for validation) or mssql_sample_data (for sampling). It mentions 'read-only SELECT query' but doesn't clarify exclusions (e.g., no DML operations) or prerequisites beyond what's in the schema.

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