Skip to main content
Glama
bpamiri

SQL Server MCP

by bpamiri

connect

Establish a connection to Microsoft SQL Server databases using environment variables for configuration, enabling database interactions through the MCP server.

Instructions

Establish connection to the SQL Server database.

Uses configuration from environment variables:
- MSSQL_HOST: Server hostname or IP
- MSSQL_USER: Username
- MSSQL_PASSWORD: Password
- MSSQL_DATABASE: Database name
- MSSQL_PORT: Port (default: 1433)

Returns:
    Connection status and details including host, database, and timestamp.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The handler function for the 'connect' MCP tool. It calls get_connection_manager() to establish the database connection and returns status and details.
    @mcp.tool()
    def connect() -> dict[str, Any]:
        """Establish connection to the SQL Server database.
    
        Uses configuration from environment variables:
        - MSSQL_HOST: Server hostname or IP
        - MSSQL_USER: Username
        - MSSQL_PASSWORD: Password
        - MSSQL_DATABASE: Database name
        - MSSQL_PORT: Port (default: 1433)
    
        Returns:
            Connection status and details including host, database, and timestamp.
        """
        try:
            manager = get_connection_manager()
            info = manager.connect()
    
            return {
                "status": "connected",
                "host": info.host,
                "database": info.database,
                "connected_at": info.connected_at.isoformat(),
            }
        except ConnectionError as e:
            return {"status": "error", "error": str(e)}
        except Exception as e:
            logger.error(f"Unexpected error during connect: {e}")
            return {"status": "error", "error": f"Unexpected error: {e}"}
  • The @mcp.tool() decorator registers the 'connect' function as an MCP tool on the FastMCP instance.
    @mcp.tool()
    def connect() -> dict[str, Any]:
        """Establish connection to the SQL Server database.
    
        Uses configuration from environment variables:
        - MSSQL_HOST: Server hostname or IP
        - MSSQL_USER: Username
        - MSSQL_PASSWORD: Password
        - MSSQL_DATABASE: Database name
        - MSSQL_PORT: Port (default: 1433)
    
        Returns:
            Connection status and details including host, database, and timestamp.
        """
        try:
            manager = get_connection_manager()
            info = manager.connect()
    
            return {
                "status": "connected",
                "host": info.host,
                "database": info.database,
                "connected_at": info.connected_at.isoformat(),
            }
        except ConnectionError as e:
            return {"status": "error", "error": str(e)}
        except Exception as e:
            logger.error(f"Unexpected error during connect: {e}")
            return {"status": "error", "error": f"Unexpected error: {e}"}
  • Helper function that provides the global ConnectionManager instance, lazily initialized from MSSQLConfig.
    def get_connection_manager() -> ConnectionManager:
        """Get or create the global connection manager.
    
        Returns:
            ConnectionManager instance configured from environment variables
        """
        global _connection_manager
        if _connection_manager is None:
            config = MSSQLConfig()
            _connection_manager = ConnectionManager(config)
        return _connection_manager
  • Core helper method in ConnectionManager that performs the actual database connection using pymssql.connect.
    def connect(self, name: str = "default") -> ConnectionInfo:
        """Establish a connection to the SQL Server.
    
        Args:
            name: Connection name for reference
    
        Returns:
            ConnectionInfo with connection details
    
        Raises:
            ConnectionError: If connection fails
        """
        if name in self._connections and self._connections[name].is_active:
            logger.info(f"Reusing existing connection '{name}'")
            return self._connections[name]
    
        try:
            logger.info(f"Connecting to {self._config.host}/{self._config.database}")
    
            self._connection = pymssql.connect(
                server=self._config.host,
                user=self._config.user,
                password=self._config.password,
                database=self._config.database,
                port=self._config.port,
                login_timeout=self._config.timeout,
                timeout=self._config.query_timeout,
            )
    
            info = ConnectionInfo(
                name=name,
                host=self._config.host,
                database=self._config.database,
                connected_at=datetime.now(),
                is_active=True,
            )
            self._connections[name] = info
    
            logger.info(f"Connected successfully to {self._config.database}")
            return info
    
        except pymssql.Error as e:
            logger.error(f"Connection failed: {e}")
            raise ConnectionError(f"Failed to connect to {self._config.host}: {e}") from e
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 of behavioral disclosure. It describes the configuration method (environment variables) and return details (status, host, database, timestamp), but lacks information on error handling, authentication needs, or rate limits. It adequately covers basic behavior but misses advanced operational traits.

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 well-structured and front-loaded with the main purpose, followed by configuration details and return information. Each sentence adds essential information without redundancy, making it efficient and easy to parse.

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?

Given the tool's complexity (connection establishment with environment-based config) and the presence of an output schema, the description is mostly complete. It covers the purpose, configuration, and return overview, but could benefit from mentioning prerequisites or error scenarios to fully guide usage without relying on the output schema alone.

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 input schema has 0 parameters with 100% coverage, so no parameter documentation is needed. The description appropriately focuses on configuration and return values, adding value beyond the empty schema by explaining how connection details are sourced from environment variables.

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 ('Establish connection') and resource ('SQL Server database'), distinguishing it from siblings like disconnect, list_connections, and switch_database. It precisely defines what the tool does 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 implies usage context by specifying that it connects to the database using environment variables, but it does not explicitly state when to use this tool versus alternatives like list_connections or switch_database. It provides clear setup requirements without naming specific alternatives or exclusions.

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

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