Skip to main content
Glama
NakiriYuuzu

MSSQL MCP Server

by NakiriYuuzu

connect-database

Connect to an MSSQL database server by providing server address, user credentials, and optional settings like encryption and database name to establish secure database interactions.

Instructions

連接到 MSSQL 資料庫伺服器

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseNo資料庫名稱 (可選)
encryptNo是否加密連接 (預設: true)
passwordYes密碼
portNo連接埠號 (預設: 1433)
serverYesMSSQL 伺服器位址
trustServerCertificateNo是否信任伺服器憑證 (預設: false)
userYes使用者名稱

Implementation Reference

  • The main handler function for the 'connect-database' tool. It validates the input configuration, sanitizes the database name, parses the config using Zod schema, establishes the connection via MSSQLManager, and returns success or error messages.
    async ({ server, port, database, user, password, encrypt, trustServerCertificate }) => {
      try {
        // 驗證連接配置
        const configValidation = validateConnectionConfig({ server, user, password, port })
        if (!configValidation.isValid) {
          return {
            content: [
              {
                type: 'text' as const,
                text: `連接配置錯誤:\n${configValidation.errors.join('\n')}`
              }
            ]
          }
        }
    
        const config = DatabaseConfigSchema.parse({
          server,
          port,
          database: database ? sanitizeDatabaseName(database) : undefined,
          user,
          password,
          options: {
            encrypt,
            trustServerCertificate,
          }
        })
    
        await mssqlManager.connect(config)
    
        return {
          content: [
            {
              type: 'text' as const,
              text: `成功連接到 MSSQL 伺服器: ${server}${database ? `\n目前資料庫: ${database}` : '\n未指定資料庫'}`
            }
          ]
        }
      } catch (error) {
        return {
          content: [
            {
              type: 'text' as const,
              text: `連接失敗: ${formatError(error)}`
            }
          ]
        }
      }
    }
  • Input schema definition for the connect-database tool, specifying parameters like server, port, database, credentials, and connection options using Zod.
    inputSchema: {
      server: z.string().describe('MSSQL 伺服器位址'),
      port: z.number().optional().default(1433).describe('連接埠號 (預設: 1433)'),
      database: z.string().optional().describe('資料庫名稱 (可選)'),
      user: z.string().describe('使用者名稱'),
      password: z.string().describe('密碼'),
      encrypt: z.boolean().optional().default(true).describe('是否加密連接 (預設: true)'),
      trustServerCertificate: z.boolean().optional().default(false).describe('是否信任伺服器憑證 (預設: false)'),
    }
  • src/index.ts:28-91 (registration)
    Registration of the 'connect-database' tool with the MCP server, including title, description, input schema, and handler function.
    server.registerTool(
      'connect-database',
      {
        title: '連接資料庫',
        description: '連接到 MSSQL 資料庫伺服器',
        inputSchema: {
          server: z.string().describe('MSSQL 伺服器位址'),
          port: z.number().optional().default(1433).describe('連接埠號 (預設: 1433)'),
          database: z.string().optional().describe('資料庫名稱 (可選)'),
          user: z.string().describe('使用者名稱'),
          password: z.string().describe('密碼'),
          encrypt: z.boolean().optional().default(true).describe('是否加密連接 (預設: true)'),
          trustServerCertificate: z.boolean().optional().default(false).describe('是否信任伺服器憑證 (預設: false)'),
        }
      },
      async ({ server, port, database, user, password, encrypt, trustServerCertificate }) => {
        try {
          // 驗證連接配置
          const configValidation = validateConnectionConfig({ server, user, password, port })
          if (!configValidation.isValid) {
            return {
              content: [
                {
                  type: 'text' as const,
                  text: `連接配置錯誤:\n${configValidation.errors.join('\n')}`
                }
              ]
            }
          }
    
          const config = DatabaseConfigSchema.parse({
            server,
            port,
            database: database ? sanitizeDatabaseName(database) : undefined,
            user,
            password,
            options: {
              encrypt,
              trustServerCertificate,
            }
          })
    
          await mssqlManager.connect(config)
    
          return {
            content: [
              {
                type: 'text' as const,
                text: `成功連接到 MSSQL 伺服器: ${server}${database ? `\n目前資料庫: ${database}` : '\n未指定資料庫'}`
              }
            ]
          }
        } catch (error) {
          return {
            content: [
              {
                type: 'text' as const,
                text: `連接失敗: ${formatError(error)}`
              }
            ]
          }
        }
      }
    )
  • Zod schema for DatabaseConfig used in the handler to parse and validate the connection configuration before passing to MSSQLManager.connect.
    export const DatabaseConfigSchema = z.object({
      server: z.string(),
      port: z.number().optional().default(1433),
      database: z.string().optional(),
      user: z.string(),
      password: z.string(),
      options: z.object({
        encrypt: z.boolean().optional().default(true),
        trustServerCertificate: z.boolean().optional().default(false),
        connectionTimeout: z.number().optional().default(30000),
        requestTimeout: z.number().optional().default(30000),
      }).optional()
    })
  • MSSQLManager.connect method called by the tool handler to establish the actual SQL Server connection pool using the 'mssql' library.
    async connect(config: DatabaseConfig): Promise<void> {
      try {
        // 如果已有連接,先關閉
        if (this.pool) {
          await this.disconnect()
        }
    
        this.config = config
        this.currentDatabase = config.database || null
    
        const poolConfig: sql.config = {
          server: config.server,
          port: config.port,
          database: config.database,
          user: config.user,
          password: config.password,
          options: config.options || {
            encrypt: true,
            trustServerCertificate: false,
            connectionTimeout: 30000,
            requestTimeout: 30000,
          }
        }
    
        this.pool = new sql.ConnectionPool(poolConfig)
        await this.pool.connect()
        
        console.log(`已連接到 MSSQL 伺服器: ${config.server}${config.database ? `, 資料庫: ${config.database}` : ''}`)
      } catch (error) {
        throw new Error(`連接資料庫失敗: ${error instanceof Error ? error.message : String(error)}`)
      }
    }
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 the action ('connect') but reveals nothing about what happens after connection: whether it establishes a persistent session, returns a connection object, handles authentication errors, or has rate limits. For a critical operation like database connection, this lack of behavioral context is a significant gap.

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 in Chinese that directly states the tool's function without any fluff or redundancy. It's appropriately sized for a straightforward connection tool and gets straight 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 connection tool with 7 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain what the connection enables (e.g., subsequent queries), what format the connection takes, or error handling. Given the complexity and lack of structured data, more context about the connection lifecycle and behavioral outcomes is needed.

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 schema has 100% description coverage, providing detailed documentation for all 7 parameters including defaults and requirements. The description adds no parameter-specific information beyond implying MSSQL as the database type, which is already evident from the schema. This meets the baseline of 3 for high 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 '連接到 MSSQL 資料庫伺服器' clearly states the verb ('連接' meaning 'connect') and resource ('MSSQL 資料庫伺服器'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'switch-database' or 'connection-status', which would require more specific language about establishing a new connection versus managing existing ones.

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. It doesn't mention prerequisites (e.g., needing server credentials), when not to use it (e.g., if already connected), or how it relates to siblings like 'disconnect' or 'switch-database'. This leaves the agent with minimal context for tool selection.

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

Related 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/NakiriYuuzu/Mssql-Mcp'

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