Skip to main content
Glama
egarcia74

Warp SQL Server MCP

by egarcia74

execute_query

Execute SQL queries on SQL Server databases to retrieve, analyze, or modify data through a secure connection with configurable access levels.

Instructions

Execute a SQL query on the connected SQL Server database

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesThe SQL query to execute
databaseNoOptional: Database name to use for this query

Implementation Reference

  • Core handler function for the 'execute_query' tool. Validates the SQL query against safety policies, executes it using the connection manager, logs performance metrics, handles errors, and formats results as a text table.
    async executeQuery(query, database = null) {
      // Validate query first
      const validation = this.validateQuery(query);
      if (!validation.allowed) {
        this.logger.security('QUERY_BLOCKED', 'Query blocked by safety policy', {
          query: query.substring(0, 200),
          reason: validation.reason,
          queryType: validation.queryType
        });
        throw new Error(`Query blocked by safety policy: ${validation.reason}`);
      }
    
      const startTime = Date.now();
    
      this.logger.debug('Executing query', {
        tool: 'execute_query',
        database,
        queryLength: query.length,
        queryType: validation.queryType
      });
    
      try {
        const pool = await this.connectionManager.connect();
        const request = pool.request();
    
        // Switch database if specified
        if (database) {
          await request.query(`USE [${database}]`);
        }
    
        const result = await request.query(query);
        const executionTime = Date.now() - startTime;
    
        // Log successful query execution
        this.logger.logQueryExecution(
          'execute_query',
          query,
          { database, securityLevel: validation.queryType },
          { success: true, duration: executionTime, rowsAffected: result.rowsAffected }
        );
    
        // Track performance (don't let performance monitoring failures break query execution)
        try {
          this.performanceMonitor.recordQuery({
            tool: 'execute_query',
            query,
            executionTime,
            success: true,
            database,
            timestamp: new Date(startTime)
          });
        } catch (perfError) {
          this.logger.warn('Performance monitoring failed', { error: perfError.message });
        }
    
        // Format results
        if (!result.recordset || result.recordset.length === 0) {
          return {
            content: [
              {
                type: 'text',
                text: `Query executed successfully. ${result.rowsAffected} rows affected.`
              }
            ]
          };
        }
    
        return this.formatQueryResults(result.recordset);
      } catch (error) {
        const executionTime = Date.now() - startTime;
    
        // Log failed query execution
        this.logger.logQueryExecution(
          'execute_query',
          query,
          { database, securityLevel: validation.queryType },
          { success: false, duration: executionTime, error }
        );
    
        // Track failed query (don't let performance monitoring failures break error handling)
        try {
          this.performanceMonitor.recordQuery({
            tool: 'execute_query',
            query,
            executionTime,
            success: false,
            error: error.message,
            database,
            timestamp: new Date(startTime)
          });
        } catch (perfError) {
          this.logger.warn('Performance monitoring failed during error handling', {
            error: perfError.message
          });
        }
    
        throw new McpError(ErrorCode.InternalError, `Query execution failed: ${error.message}`);
      }
    }
  • index.js:280-285 (registration)
    Tool dispatch/registration in the main CallToolRequest handler switch statement. Routes 'execute_query' calls to the executeQuery method.
    case 'execute_query': {
      const queryResult = await this.executeQuery(args.query, args.database);
      return {
        content: queryResult.content
      };
    }
  • Tool schema definition including name, description, and input schema for validation.
    name: 'execute_query',
    description: 'Execute a SQL query on the connected SQL Server database',
    inputSchema: {
      type: 'object',
      properties: {
        query: { type: 'string', description: 'The SQL query to execute' },
        database: { type: 'string', description: 'Optional: Database name to use for this query' }
      },
      required: ['query']
    }
  • index.js:241-243 (registration)
    Registration of ListTools handler which returns all tools including 'execute_query' from the tool registry.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: getAllTools()
    }));
  • Helper function used by executeQuery to format query results into a readable text table.
    formatQueryResults(data) {
      if (data.length === 0) {
        return { content: [{ type: 'text', text: 'No data returned' }] };
      }
    
      const headers = Object.keys(data[0]);
      const rows = data.map(row => headers.map(header => String(row[header] || '')));
    
      return {
        content: [
          {
            type: 'text',
            text: this.createTextTable(headers, rows)
          }
        ]
      };
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. While 'Execute a SQL query' implies a write operation could occur, it doesn't specify whether this tool supports read-only queries, what permissions are required, whether transactions are managed, what happens with errors, or any rate limits. For a database execution tool with zero annotation coverage, this leaves significant behavioral questions unanswered.

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 communicates the core purpose without any wasted words. It's appropriately sized for a straightforward execution tool and gets directly to the point.

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 execution tool with no annotations and no output schema, the description is insufficiently complete. It doesn't address critical context like what types of queries are supported (SELECT, INSERT, etc.), whether results are returned, error handling, transaction behavior, or security implications. Given the complexity of database operations and the lack of structured metadata, the description should provide more operational 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?

The description mentions executing 'a SQL query' which aligns with the 'query' parameter, but adds no additional semantic context beyond what the 100% covered schema already provides. The schema descriptions clearly document both parameters, so the description doesn't compensate but doesn't need to given the comprehensive schema coverage.

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 ('SQL query on the connected SQL Server database'), providing a specific verb+resource combination. However, it doesn't distinguish this tool from potential alternatives like 'explain_query' or 'analyze_query_performance' which might also involve query execution with different purposes.

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. With 15 sibling tools including 'explain_query', 'analyze_query_performance', and 'get_table_data', there's no indication of when this general execution tool is preferred over more specialized alternatives or what types of queries it's designed for.

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/egarcia74/warp-sql-server-mcp'

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