Skip to main content
Glama
bpamiri

SQL Server MCP

by bpamiri

execute_query

Execute read-only SELECT queries on SQL Server databases to retrieve data with automatic row limiting for safety and performance.

Instructions

Execute a read-only SQL query and return results.

Only SELECT statements are allowed. The query will have a row limit applied
automatically if not specified.

Args:
    query: SQL SELECT statement to execute
    max_rows: Maximum rows to return (overrides default, capped by MSSQL_MAX_ROWS)

Returns:
    Dictionary with:
    - query: The original query
    - executed_query: The query that was actually executed (may include TOP)
    - columns: List of column names
    - rows: List of row dictionaries
    - row_count: Number of rows returned
    - max_rows: The effective row limit applied

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
max_rowsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Core handler function for the 'execute_query' MCP tool. Includes registration via @mcp.tool() decorator, input schema via type hints and docstring, validation logic, query execution, and result formatting.
    def execute_query(query: str, max_rows: int | None = None) -> dict[str, Any]:
        """Execute a read-only SQL query and return results.
    
        Only SELECT statements are allowed. The query will have a row limit applied
        automatically if not specified.
    
        Args:
            query: SQL SELECT statement to execute
            max_rows: Maximum rows to return (overrides default, capped by MSSQL_MAX_ROWS)
    
        Returns:
            Dictionary with:
            - query: The original query
            - executed_query: The query that was actually executed (may include TOP)
            - columns: List of column names
            - rows: List of row dictionaries
            - row_count: Number of rows returned
            - max_rows: The effective row limit applied
        """
        try:
            manager = get_connection_manager()
            config = manager.config
    
            # Create validator
            validator = SQLValidator(
                blocked_commands=config.blocked_commands,
                read_only=True,  # execute_query is always read-only
                allowed_schemas=config.allowed_schemas if config.allowed_schemas else None,
            )
    
            # Validate query is SELECT-only
            if not validator.is_select_only(query):
                return {
                    "error": "Only SELECT queries are allowed. Use other tools for data modification.",
                    "query": query,
                }
    
            # Check blocked commands
            is_valid, error = validator.validate(query)
            if not is_valid:
                return {"error": error, "query": query}
    
            # Determine effective row limit
            effective_max_rows = min(max_rows or config.max_rows, config.max_rows)
    
            # Inject row limit
            executed_query = validator.inject_row_limit(query, effective_max_rows)
    
            # Execute query
            rows = manager.execute_query(executed_query)
    
            # Extract column names from first row or return empty
            columns: list[str] = []
            if rows:
                columns = list(rows[0].keys())
    
            return {
                "query": query,
                "executed_query": executed_query,
                "columns": columns,
                "rows": rows,
                "row_count": len(rows),
                "max_rows": effective_max_rows,
            }
    
        except Exception as e:
            logger.error(f"Error executing query: {e}")
            return {"error": str(e), "query": query}
  • Input/output schema defined by function signature type hints and comprehensive docstring describing parameters and return structure.
    """Execute a read-only SQL query and return results.
    
    Only SELECT statements are allowed. The query will have a row limit applied
    automatically if not specified.
    
    Args:
        query: SQL SELECT statement to execute
        max_rows: Maximum rows to return (overrides default, capped by MSSQL_MAX_ROWS)
    
    Returns:
        Dictionary with:
        - query: The original query
        - executed_query: The query that was actually executed (may include TOP)
        - columns: List of column names
        - rows: List of row dictionaries
        - row_count: Number of rows returned
        - max_rows: The effective row limit applied
    """
  • Tool registration using the @mcp.tool() decorator from FastMCP.
    def execute_query(query: str, max_rows: int | None = None) -> dict[str, Any]:
Behavior4/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 effectively describes key behaviors: read-only nature, automatic row limiting, and the specific return format. However, it doesn't mention potential errors, performance implications, or authentication requirements, leaving some 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 well-structured and front-loaded with the core purpose. Every sentence adds value: the first states the action and constraint, the second explains row limiting, and the Args/Returns sections clearly document parameters and output without redundancy. No wasted words.

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 complexity of a SQL query tool with no annotations, the description is complete. It covers purpose, constraints, parameters, and detailed return values (with an output schema implied by the Returns section). This provides enough context for an agent to use the tool effectively without needing additional structured data.

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 meaningful context for both parameters: 'query' is explained as a 'SQL SELECT statement to execute', and 'max_rows' is described with its purpose ('overrides default, capped by MSSQL_MAX_ROWS'). This goes beyond the bare schema, though it could provide more detail on query syntax or constraints.

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 ('execute a read-only SQL query'), the resource ('SQL query'), and the scope ('only SELECT statements are allowed'). It distinguishes from siblings like 'call_stored_proc', 'delete_row', 'insert_row', and 'update_row' by explicitly limiting to read-only SELECT operations.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool ('only SELECT statements are allowed') and when not to use it (implying not for write operations like insert/update/delete, which are handled by sibling tools). It also mentions an alternative ('call_stored_proc') for stored procedures rather than direct queries.

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