Skip to main content
Glama
dhipskind253

mssql-mcp

by dhipskind253

run_select

Execute SELECT or WITH (CTE) queries on a read-only SQL Server database, rejecting modifications and capping results at a configurable limit (max 1000 rows).

Instructions

Run a single SELECT or WITH (CTE) statement. DML/DDL/EXEC are rejected before reaching the server. Results are capped at max_rows (default 100, hard max 1000).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesA single SELECT or WITH statement.
max_rowsNo

Implementation Reference

  • The actual handler for 'run_select' – executes the SQL query after calling assertReadOnly() for validation, caps results at maxRows, and returns rows with metadata.
    async runSelect(query: string, maxRows: number) {
      assertReadOnly(query);
      const cap = Math.min(Math.max(Math.floor(maxRows), 1), 1000);
      const r = await (await this.getPool()).request().query(query);
      const rows = r.recordset.slice(0, cap).map((row) => truncateRow(row));
      return {
        rows,
        row_count_returned: rows.length,
        row_count_total: r.recordset.length,
        truncated: r.recordset.length > rows.length,
      };
    }
  • src/index.ts:167-175 (registration)
    Registers the 'run_select' tool on the MCP server with its schema (query string, max_rows number) and the handler that delegates to db.runSelect().
    server.tool(
      'run_select',
      'Run a single SELECT or WITH (CTE) statement. DML/DDL/EXEC are rejected before reaching the server. Results are capped at max_rows (default 100, hard max 1000).',
      {
        query: z.string().describe('A single SELECT or WITH statement.'),
        max_rows: z.number().int().positive().max(1000).default(100),
      },
      async ({ query, max_rows }) => runTool(() => db.runSelect(query, max_rows))
    );
  • Input schema for 'run_select' – defines 'query' (string) and 'max_rows' (integer, default 100, max 1000) via Zod.
    server.tool(
      'run_select',
      'Run a single SELECT or WITH (CTE) statement. DML/DDL/EXEC are rejected before reaching the server. Results are capped at max_rows (default 100, hard max 1000).',
      {
        query: z.string().describe('A single SELECT or WITH statement.'),
        max_rows: z.number().int().positive().max(1000).default(100),
      },
  • Validation guardrail for run_select – assertReadOnly() strips comments/strings, checks for single SELECT/WITH statement, and rejects forbidden DDL/DML keywords before the query reaches the database.
    /**
     * Lexical guardrail for run_select. The actual security boundary is the
     * read-only database login; this just produces friendly errors before the
     * statement reaches the server.
     */
    const FORBIDDEN_KEYWORDS = [
      'INSERT',
      'UPDATE',
      'DELETE',
      'MERGE',
      'TRUNCATE',
      'DROP',
      'CREATE',
      'ALTER',
      'GRANT',
      'REVOKE',
      'DENY',
      'EXEC',
      'EXECUTE',
      'BACKUP',
      'RESTORE',
      'BULK',
      'OPENROWSET',
      'OPENDATASOURCE',
      'OPENQUERY',
      'DBCC',
      'KILL',
      'SHUTDOWN',
      'INTO', // SELECT INTO creates a new table
    ];
    
    export class InvalidQueryError extends Error {
      constructor(message: string) {
        super(`[INVALID_QUERY] ${message}`);
        this.name = 'InvalidQueryError';
      }
    }
    
    function stripCommentsAndStrings(sql: string): string {
      return sql
        .replace(/--[^\n]*/g, '')
        .replace(/\/\*[\s\S]*?\*\//g, '')
        .replace(/'(?:[^']|'')*'/g, "''")
        .replace(/"(?:[^"]|"")*"/g, '""');
    }
    
    export function assertReadOnly(sql: string): void {
      if (!sql || !sql.trim()) {
        throw new InvalidQueryError('Empty query.');
      }
    
      const cleaned = stripCommentsAndStrings(sql).trim();
    
      // Allow a single trailing semicolon, no others.
      const noTrailingSemi = cleaned.replace(/;\s*$/, '');
      if (noTrailingSemi.includes(';')) {
        throw new InvalidQueryError(
          'Multi-statement batches are not allowed. Submit a single SELECT or WITH (CTE).'
        );
      }
    
      const firstWord = noTrailingSemi.match(/^\s*([A-Za-z_]+)/)?.[1]?.toUpperCase();
      if (firstWord !== 'SELECT' && firstWord !== 'WITH') {
        throw new InvalidQueryError(
          `Only SELECT or WITH (CTE) statements are allowed; got "${firstWord ?? 'unknown'}".`
        );
      }
    
      for (const kw of FORBIDDEN_KEYWORDS) {
        const re = new RegExp(`\\b${kw}\\b`, 'i');
        if (re.test(noTrailingSemi)) {
          throw new InvalidQueryError(
            `Statement contains forbidden keyword "${kw}". This server is read-only.`
          );
        }
      }
    }
Behavior4/5

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

With no annotations, the description discloses key behaviors: result capping (default 100, hard max 1000) and rejection of non-SELECT/WITH statements. It does not mention auth or rate limits, but these are not critical for a read-only query.

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 main purpose, then constraints. No wasted words.

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?

The description covers key aspects for a query tool but does not mention the output format (e.g., row set, metadata). Given siblings are metadata tools, this is minor.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds value beyond the schema by clarifying max_rows default and limit. The query parameter is sufficiently explained in the schema, and the description reinforces it.

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 that the tool runs a SELECT or WITH statement, distinguishing it from sibling tools that query metadata (e.g., list_tables, describe_table).

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 explicitly states that DML/DDL/EXEC are rejected, guiding the agent away from invalid uses. However, it does not mention alternative tools for other query types.

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

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