Skip to main content
Glama
bpamiri

SQL Server MCP

by bpamiri

switch_database

Change the active database context in SQL Server to execute queries on different databases. Use this tool to switch between databases within a session.

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 `switch_database` tool handler: validates the database exists, is online, and not blocked, then executes `USE [database_name]` to switch context and returns status.
    @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}
  • Registers the `switch_database` function as an MCP tool using the `@mcp.tool()` decorator.
    @mcp.tool()
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 context, lists prerequisites (existence, online status, blocklist), and describes the return structure. It doesn't cover rate limits or authentication needs, but provides solid operational context.

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?

Perfectly structured with clear sections: purpose statement, prerequisites, Args, and Returns. Every sentence earns its place - the first sentence states the core action, subsequent sentences add necessary constraints, and the parameter/return sections are efficiently formatted.

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 (context switching with constraints), no annotations, and the presence of an output schema, the description is complete. It explains the action, constraints, parameter meaning, and return structure - covering everything needed for proper use without redundancy.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/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 fully. It does this excellently by explaining the single parameter's purpose ('Name of the database to switch to'), adding context about requirements (must exist, be online, not blocked) that goes beyond what the bare schema provides.

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 ('Switch the active database context') and resource ('database'), distinguishing it from siblings like list_databases or execute_query. It uses precise technical language ('USE statement') that clarifies the exact operation.

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 about when to use this tool ('Changes the current database') and mentions prerequisites ('database must exist, be online, and not be in the blocklist'). However, it doesn't explicitly state when NOT to use it or name specific alternatives among the sibling tools.

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/pymssql-mcp'

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