Skip to main content
Glama
knight0zh

MSSQL MCP Server

by knight0zh

query

Execute SQL queries on Microsoft SQL Server databases to retrieve, modify, or analyze data using connection parameters or a connection string.

Instructions

Execute a SQL query on a MSSQL database

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
connectionStringNoFull connection string (alternative to individual parameters)
hostNoDatabase server hostname
portNoDatabase server port (default: 1433)
databaseNoDatabase name (default: master)
usernameNoDatabase username
passwordNoDatabase password
queryYesSQL query to execute
encryptNoEnable encryption (default: false)
trustServerCertificateNoTrust server certificate (default: true)

Implementation Reference

  • The core handler function that processes the query arguments, establishes a connection pool if needed, executes the SQL query using mssql, and returns the results as a formatted JSON string in the MCP content format.
    async handleQuery(args: QueryArgs): Promise<{ content: Array<{ type: string; text: string }> }> {
      try {
        const config = this.getConnectionConfig(args);
        const pool = await this.getPool(config);
        const result = await pool.request().query(args.query);
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(result.recordset, null, 2),
            },
          ],
        };
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        throw new McpError(ErrorCode.InternalError, `Database error: ${message}`);
      }
    }
  • The JSON input schema for the 'query' tool as returned in ListTools, defining properties for connection parameters and the required SQL query with validation rules via oneOf.
    inputSchema: {
      type: 'object',
      properties: {
        connectionString: {
          type: 'string',
          description: 'Full connection string (alternative to individual parameters)',
        },
        host: {
          type: 'string',
          description: 'Database server hostname',
        },
        port: {
          type: 'number',
          description: 'Database server port (default: 1433)',
        },
        database: {
          type: 'string',
          description: 'Database name (default: master)',
        },
        username: {
          type: 'string',
          description: 'Database username',
        },
        password: {
          type: 'string',
          description: 'Database password',
        },
        query: {
          type: 'string',
          description: 'SQL query to execute',
        },
        encrypt: {
          type: 'boolean',
          description: 'Enable encryption (default: false)',
        },
        trustServerCertificate: {
          type: 'boolean',
          description: 'Trust server certificate (default: true)',
        },
      },
      required: ['query'],
      oneOf: [
        { required: ['connectionString'] },
        { required: ['host', 'username', 'password'] },
      ],
    },
  • src/index.ts:171-226 (registration)
    Registers the 'query' tool in the MCP server's ListToolsRequest handler by returning it in the tools array with name, description, and input schema.
    this.server.setRequestHandler(ListToolsRequestSchema, (_request: ListToolsRequest) =>
      Promise.resolve({
        tools: [
          {
            name: 'query',
            description: 'Execute a SQL query on a MSSQL database',
            inputSchema: {
              type: 'object',
              properties: {
                connectionString: {
                  type: 'string',
                  description: 'Full connection string (alternative to individual parameters)',
                },
                host: {
                  type: 'string',
                  description: 'Database server hostname',
                },
                port: {
                  type: 'number',
                  description: 'Database server port (default: 1433)',
                },
                database: {
                  type: 'string',
                  description: 'Database name (default: master)',
                },
                username: {
                  type: 'string',
                  description: 'Database username',
                },
                password: {
                  type: 'string',
                  description: 'Database password',
                },
                query: {
                  type: 'string',
                  description: 'SQL query to execute',
                },
                encrypt: {
                  type: 'boolean',
                  description: 'Enable encryption (default: false)',
                },
                trustServerCertificate: {
                  type: 'boolean',
                  description: 'Trust server certificate (default: true)',
                },
              },
              required: ['query'],
              oneOf: [
                { required: ['connectionString'] },
                { required: ['host', 'username', 'password'] },
              ],
            },
          },
        ],
      })
    );
  • src/index.ts:228-245 (registration)
    Registers the handling of CallToolRequest for the 'query' tool by checking the name, validating arguments, and delegating to the handleQuery method.
    this.server.setRequestHandler(
      CallToolRequestSchema,
      async (
        request: CallToolRequest
      ): Promise<{ content: Array<{ type: string; text: string }> }> => {
        const params = request.params as { name: string; arguments: unknown };
    
        if (params.name !== 'query') {
          throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${params.name}`);
        }
    
        if (!isValidQueryArgs(params.arguments)) {
          throw new McpError(ErrorCode.InvalidRequest, 'Invalid query arguments');
        }
    
        return this.handleQuery(params.arguments);
      }
    );
  • Type guard function to validate that the tool arguments conform to the QueryArgs interface, used in the CallTool handler.
    const isValidQueryArgs = (args: unknown): args is QueryArgs => {
      const candidate = args as Record<string, unknown>;
    
      if (typeof candidate !== 'object' || candidate === null) {
        return false;
      }
    
      // Query is required
      if (typeof candidate.query !== 'string') {
        return false;
      }
    
      // Either connectionString OR (host + username + password) must be provided
      if (candidate.connectionString !== undefined) {
        if (typeof candidate.connectionString !== 'string') {
          return false;
        }
      } else {
        if (typeof candidate.host !== 'string') {
          return false;
        }
        if (typeof candidate.username !== 'string') {
          return false;
        }
        if (typeof candidate.password !== 'string') {
          return false;
        }
      }
    
      // Optional parameters
      if (candidate.port !== undefined && typeof candidate.port !== 'number') {
        return false;
      }
      if (candidate.database !== undefined && typeof candidate.database !== 'string') {
        return false;
      }
      if (candidate.encrypt !== undefined && typeof candidate.encrypt !== 'boolean') {
        return false;
      }
      if (
        candidate.trustServerCertificate !== undefined &&
        typeof candidate.trustServerCertificate !== 'boolean'
      ) {
        return false;
      }
    
      return true;
    };
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. While 'Execute a SQL query' implies both read and write operations, it doesn't specify permissions needed, potential side effects, rate limits, or what happens with complex queries. For a database tool with zero annotation coverage, this leaves significant behavioral gaps.

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 directly states the tool's purpose without any unnecessary words. It's appropriately sized and front-loaded with the essential information.

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 types of queries are supported, what the return format looks like, error handling, or security considerations. The tool has significant complexity that isn't addressed.

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%, meaning all parameters are documented in the schema itself. The description doesn't add any parameter-specific information beyond what's already in the schema, so it meets the baseline for high schema coverage but doesn't provide additional value.

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 a SQL query') and target resource ('on a MSSQL database'), providing specific verb+resource information. However, with no sibling tools mentioned, there's no opportunity to distinguish from alternatives, preventing 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, prerequisites, or context for usage. It simply states what the tool does without any usage instructions or constraints.

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

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