Skip to main content
Glama
bpamiri

SQL Server MCP

by bpamiri

validate_query

Check SQL queries for safety before execution by validating statement types, blocked commands, read-only compliance, and potential issues like missing WHERE clauses.

Instructions

Check if a query is safe to execute without running it.

Validates the query against:
- Statement type (SELECT, INSERT, UPDATE, DELETE, DDL, EXEC)
- Blocked commands list
- Read-only mode compliance
- Potential issues (missing WHERE clause, unbounded SELECT)

Args:
    query: SQL statement to validate

Returns:
    Dictionary with:
    - query: The original query
    - valid: Whether the query is valid
    - statement_type: Type of SQL statement
    - warnings: List of warning messages
    - suggestions: List of suggested improvements
    - error: Error message if invalid

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The main handler function for the 'validate_query' MCP tool. It is decorated with @mcp.tool(), which registers it as a tool. The function validates SQL queries using SQLValidator, checks statement types, blocked commands, and provides warnings and suggestions.
    @mcp.tool()
    def validate_query(query: str) -> dict[str, Any]:
        """Check if a query is safe to execute without running it.
    
        Validates the query against:
        - Statement type (SELECT, INSERT, UPDATE, DELETE, DDL, EXEC)
        - Blocked commands list
        - Read-only mode compliance
        - Potential issues (missing WHERE clause, unbounded SELECT)
    
        Args:
            query: SQL statement to validate
    
        Returns:
            Dictionary with:
            - query: The original query
            - valid: Whether the query is valid
            - statement_type: Type of SQL statement
            - warnings: List of warning messages
            - suggestions: List of suggested improvements
            - error: Error message if invalid
        """
        try:
            manager = get_connection_manager()
            config = manager.config
    
            # Create validator
            validator = SQLValidator(
                blocked_commands=config.blocked_commands,
                read_only=config.read_only,
                allowed_schemas=config.allowed_schemas if config.allowed_schemas else None,
            )
    
            # Detect statement type
            stmt_type = validator.detect_statement_type(query)
    
            # Validate
            is_valid, error = validator.validate(query)
    
            # Get warnings
            warnings = validator.get_warnings(query)
    
            # Build suggestions
            suggestions: list[str] = []
            if stmt_type.value == "SELECT" and "TOP" not in query.upper():
                suggestions.append("Consider using TOP clause to limit results")
            if stmt_type.value in ("UPDATE", "DELETE") and "WHERE" not in query.upper():
                suggestions.append("Add WHERE clause to target specific rows")
    
            result: dict[str, Any] = {
                "query": query,
                "valid": is_valid,
                "statement_type": stmt_type.value,
                "warnings": warnings,
                "suggestions": suggestions,
            }
    
            if not is_valid:
                result["error"] = error
    
            return result
    
        except Exception as e:
            logger.error(f"Error validating query: {e}")
            return {"error": str(e), "query": query}
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 what the tool does (validates queries against specific criteria like statement types and blocked commands) and outlines the return structure. However, it doesn't mention potential limitations such as rate limits, authentication needs, or system-specific constraints, leaving some behavioral aspects uncovered.

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, starting with a clear purpose statement followed by bullet points for validation criteria and structured sections for args and returns. Every sentence adds value without redundancy, making it efficient and easy to parse for an AI agent.

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 (validation with multiple criteria), no annotations, and an output schema that details the return structure, the description is complete enough. It covers the purpose, usage, validation aspects, parameter semantics, and return values, providing all necessary context for effective tool selection and invocation.

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?

The description adds significant meaning beyond the input schema, which has 0% description coverage. It explains that the 'query' parameter is an 'SQL statement to validate', clarifying its purpose and format. This compensates fully for the schema's lack of documentation, providing essential context for the single parameter.

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 a specific verb ('check if a query is safe to execute') and resource ('a query'), distinguishing it from siblings like execute_query (which runs queries) and other database tools. It explicitly differentiates by stating 'without running it', making the distinction unambiguous.

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: to validate SQL queries for safety before execution. It implies an alternative (execute_query for actual execution) and specifies use cases like checking statement types, blocked commands, and compliance issues, making it clear this is for pre-execution validation rather than running 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