Skip to main content
Glama

read_data

Execute SELECT queries on MSSQL databases to retrieve data from tables while maintaining security by preventing destructive SQL operations.

Instructions

Executes a SELECT query on an MSSQL Database table. The query must start with SELECT and cannot contain any destructive SQL operations for security reasons.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSQL SELECT query to execute (must start with SELECT and cannot contain destructive operations). Example: SELECT * FROM movies WHERE genre = 'comedy'

Implementation Reference

  • The `run` method of ReadDataTool class that implements the core logic for executing SELECT queries on MSSQL database after validation and sanitization.
    async run(params: any) {
      try {
        const { query } = params;
        
        // Validate the query for security issues
        const validation = this.validateQuery(query);
        if (!validation.isValid) {
          console.warn(`Security validation failed for query: ${query.substring(0, 100)}...`);
          return {
            success: false,
            message: `Security validation failed: ${validation.error}`,
            error: 'SECURITY_VALIDATION_FAILED'
          };
        }
    
        // Log the query for audit purposes (in production, consider more secure logging)
        console.log(`Executing validated SELECT query: ${query.substring(0, 200)}${query.length > 200 ? '...' : ''}`);
    
        // Execute the query
        const request = new sql.Request();
        const result = await request.query(query);
        
        // Sanitize the result
        const sanitizedData = this.sanitizeResult(result.recordset);
        
        return {
          success: true,
          message: `Query executed successfully. Retrieved ${sanitizedData.length} record(s)${
            result.recordset.length !== sanitizedData.length 
              ? ` (limited from ${result.recordset.length} total records)` 
              : ''
          }`,
          data: sanitizedData,
          recordCount: sanitizedData.length,
          totalRecords: result.recordset.length
        };
        
      } catch (error) {
        console.error("Error executing query:", error);
        
        // Don't expose internal error details to prevent information leakage
        const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
        const safeErrorMessage = errorMessage.includes('Invalid object name') 
          ? errorMessage 
          : 'Database query execution failed';
        
        return {
          success: false,
          message: `Failed to execute query: ${safeErrorMessage}`,
          error: 'QUERY_EXECUTION_FAILED'
        };
      }
    }
  • Input schema definition for the read_data tool, specifying the required 'query' parameter.
    inputSchema = {
      type: "object",
      properties: {
        query: { 
          type: "string", 
          description: "SQL SELECT query to execute (must start with SELECT and cannot contain destructive operations). Example: SELECT * FROM movies WHERE genre = 'comedy'" 
        },
      },
      required: ["query"],
    } as any;
  • src/index.ts:129-130 (registration)
    Registration in the tool dispatch switch statement in CallToolRequestSchema handler, where readDataTool is invoked based on name.
    case readDataTool.name:
      result = await readDataTool.run(args);
  • src/index.ts:117-118 (registration)
    Inclusion of readDataTool in the list of available tools returned by ListToolsRequestSchema handler.
    ? [listTableTool, readDataTool, describeTableTool] // todo: add searchDataTool to the list of tools available in readonly mode once implemented
    : [insertDataTool, readDataTool, describeTableTool, updateDataTool, createTableTool, createIndexTool, dropTableTool, listTableTool], // add all new tools here
  • Helper method `validateQuery` used by the handler to check for dangerous SQL keywords and patterns before execution.
    private validateQuery(query: string): { isValid: boolean; error?: string } {
      if (!query || typeof query !== 'string') {
        return { 
          isValid: false, 
          error: 'Query must be a non-empty string' 
        };
      }
    
      // Remove comments and normalize whitespace for analysis
      const cleanQuery = query
        .replace(/--.*$/gm, '') // Remove line comments
        .replace(/\/\*[\s\S]*?\*\//g, '') // Remove block comments
        .replace(/\s+/g, ' ') // Normalize whitespace
        .trim();
    
      if (!cleanQuery) {
        return { 
          isValid: false, 
          error: 'Query cannot be empty after removing comments' 
        };
      }
    
      const upperQuery = cleanQuery.toUpperCase();
    
      // Must start with SELECT
      if (!upperQuery.startsWith('SELECT')) {
        return { 
          isValid: false, 
          error: 'Query must start with SELECT for security reasons' 
        };
      }
    
      // Check for dangerous keywords in the cleaned query using word boundaries
      for (const keyword of ReadDataTool.DANGEROUS_KEYWORDS) {
        // Use word boundary regex to match only complete keywords, not parts of words
        const keywordRegex = new RegExp(`(^|\\s|[^A-Za-z0-9_])${keyword}($|\\s|[^A-Za-z0-9_])`, 'i');
        if (keywordRegex.test(upperQuery)) {
          return { 
            isValid: false, 
            error: `Dangerous keyword '${keyword}' detected in query. Only SELECT operations are allowed.` 
          };
        }
      }
    
      // Check for dangerous patterns using regex
      for (const pattern of ReadDataTool.DANGEROUS_PATTERNS) {
        if (pattern.test(query)) {
          return { 
            isValid: false, 
            error: 'Potentially malicious SQL pattern detected. Only simple SELECT queries are allowed.' 
          };
        }
      }
    
      // Additional validation: Check for multiple statements
      const statements = cleanQuery.split(';').filter(stmt => stmt.trim().length > 0);
      if (statements.length > 1) {
        return { 
          isValid: false, 
          error: 'Multiple SQL statements are not allowed. Use only a single SELECT statement.' 
        };
      }
    
      // Check for suspicious string patterns that might indicate obfuscation
      if (query.includes('CHAR(') || query.includes('NCHAR(') || query.includes('ASCII(')) {
        return { 
          isValid: false, 
          error: 'Character conversion functions are not allowed as they may be used for obfuscation.' 
        };
      }
    
      // Limit query length to prevent potential DoS
      if (query.length > 10000) {
        return { 
          isValid: false, 
          error: 'Query is too long. Maximum allowed length is 10,000 characters.' 
        };
      }
    
      return { isValid: true };
    }
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. It discloses key behavioral traits: it's a read-only operation (implied by SELECT-only), has security constraints (no destructive SQL), and targets MSSQL Database. However, it lacks details on permissions, error handling, result format, or rate limits, leaving gaps for a tool with no annotation support.

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 two sentences, front-loaded with the core purpose and followed by a security constraint. Every word earns its place with no redundancy or fluff, making it highly efficient and easy to parse.

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 no annotations and no output schema, the description is moderately complete for a simple query tool. It covers the purpose and basic constraints but lacks details on return values, error cases, or advanced usage, which could be critical for an AI agent to handle effectively in a database context.

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 the 'query' parameter thoroughly. The description adds minimal value beyond the schema by reiterating the SELECT and non-destructive constraints, but does not provide additional syntax, format, or usage nuances. This meets the baseline for high schema coverage.

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 ('Executes a SELECT query') and target resource ('on an MSSQL Database table'), distinguishing it from siblings like create_table or insert_data. It precisely defines the tool's function without being vague or tautological.

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 (for SELECT queries only) and implicitly excludes destructive operations, but it does not explicitly name alternatives like list_table for metadata queries or when not to use it versus other read operations. It offers solid guidance but lacks explicit sibling comparisons.

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

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