Skip to main content
Glama
bpamiri

SQL Server MCP

by bpamiri

switch_database

Change the active database context in SQL Server using the USE statement to execute queries against different databases.

Instructions

Switch the active database context.

Changes the current database using the USE statement. The database must
exist, be online, and not be in the blocklist (MSSQL_BLOCKED_DATABASES).

Args:
    database_name: Name of the database to switch to

Returns:
    Dictionary with:
    - status: "switched" on success, "error" on failure
    - database: The new active database name
    - previous_database: The previously active database
    - error: Error message if switch failed

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
database_nameYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The main handler function for the 'switch_database' tool. It is decorated with @mcp.tool(), which registers it as an MCP tool. The function validates the database name, checks if it's blocked or exists and online, switches using 'USE [db]' statement, and returns status with previous and new database names.
    @mcp.tool()
    def switch_database(database_name: str) -> dict[str, Any]:
        """Switch the active database context.
    
        Changes the current database using the USE statement. The database must
        exist, be online, and not be in the blocklist (MSSQL_BLOCKED_DATABASES).
    
        Args:
            database_name: Name of the database to switch to
    
        Returns:
            Dictionary with:
            - status: "switched" on success, "error" on failure
            - database: The new active database name
            - previous_database: The previously active database
            - error: Error message if switch failed
        """
        try:
            manager = get_connection_manager()
            config = manager.config
            blocked_databases = config.blocked_databases
    
            # Check if database is blocked
            if database_name.lower() in blocked_databases:
                return {
                    "status": "error",
                    "error": f"Access to database '{database_name}' is not allowed",
                    "database": database_name,
                }
    
            # Get current database before switching
            current_db_query = "SELECT DB_NAME() AS current_database"
            current_db_result = manager.execute_query(current_db_query)
            previous_database = (
                current_db_result[0]["current_database"] if current_db_result else None
            )
    
            # Switch database using USE statement
            # Note: USE cannot be parameterized, but we validate the name exists first
            # by checking sys.databases
            check_query = "SELECT name FROM sys.databases WHERE name = %s AND state_desc = 'ONLINE'"
            check_result = manager.execute_query(check_query, (database_name,))
    
            if not check_result:
                return {
                    "status": "error",
                    "error": f"Database '{database_name}' does not exist or is not online",
                    "database": database_name,
                }
    
            # Execute USE statement (database name is validated, use bracket quoting for safety)
            use_query = f"USE [{database_name}]"
            manager.execute_query(use_query)
    
            # Verify the switch
            verify_result = manager.execute_query(current_db_query)
            new_database = verify_result[0]["current_database"] if verify_result else None
    
            return {
                "status": "switched",
                "database": new_database,
                "previous_database": previous_database,
            }
    
        except Exception as e:
            logger.error(f"Error switching database: {e}")
            return {"error": str(e), "database": database_name}
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by disclosing behavioral traits: it explains the action ('Changes the current database using the USE statement'), constraints (existence, online status, blocklist), and response structure. However, it lacks details on permissions, rate limits, or side effects on other tools.

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 appropriately sized and front-loaded: the first sentence states the purpose, followed by key constraints, then structured Args and Returns sections. Every sentence adds value without redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (1 parameter, no annotations, but with output schema), the description is complete: it covers purpose, usage, constraints, parameters, and return values. The output schema exists, so the description needn't explain return values beyond what's provided, and it adequately addresses the context.

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?

Schema description coverage is 0%, so the description must compensate. It adds meaning by explaining 'database_name' as 'Name of the database to switch to' and detailing constraints in the main text, though it could specify format (e.g., case sensitivity) or examples.

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 tool's purpose with specific verb ('switch') and resource ('active database context'), and distinguishes it from siblings like 'connect', 'disconnect', or 'list_databases' by focusing on context switching rather than connection management or listing.

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 provides clear context for when to use this tool ('switch the active database context') and includes prerequisites ('database must exist, be online, and not be in the blocklist'), but does not explicitly mention when not to use it or name specific alternatives among siblings.

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