Skip to main content
Glama
ydb-platform

YDB MCP

Official
by ydb-platform

ydb_explain_query_with_params

Analyze parametrized SQL queries with JSON parameters to understand execution plans and optimize database performance.

Instructions

Explain a parametrized SQL query with JSON parameters

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYes
paramsYes

Implementation Reference

  • The handler function for the 'ydb_explain_query_with_params' tool. It parses the JSON params string, converts to YDB parameters, and delegates to the explain_query method to get the execution plan.
    async def explain_query_with_params(self, sql: str, params: str) -> List[TextContent]:
        """Explain a SQL query against YDB
    
        Args:
            sql: SQL query to execute
            params: Optional query parameters
    
        Returns:
            Execution plan of the query as TextContent object with JSON-formatted execution plan
        """
        """Run a parameterized SQL query with JSON parameters.
    
        Args:
            sql: SQL query to execute
            params: Parameters as a JSON string
    
        Returns:
            Query results as a list of TextContent objects or a dictionary
        """
        # Handle authentication errors
        if self.auth_error:
            logger.error(f"Authentication error: {self.auth_error}")
            safe_error = self._stringify_dict_keys({"error": f"Authentication error: {self.auth_error}"})
            return [TextContent(type="text", text=json.dumps(safe_error, indent=2))]
    
        try:
            ydb_params = self._parse_str_to_ydb_params(params)
        except json.JSONDecodeError as e:
            logger.error(f"Error parsing JSON parameters: {str(e)}")
            safe_error = self._stringify_dict_keys({"error": f"Error parsing JSON parameters: {str(e)}"})
            return [TextContent(type="text", text=json.dumps(safe_error, indent=2))]
    
        return await self.explain_query(sql, ydb_params)
  • The registration loop in register_tools() that registers the ydb_explain_query_with_params tool (along with others) using FastMCP.add_tool and ToolManager.register_tool, linking the name to the handler function.
    for spec in tool_specs:
        self.add_tool(
            spec["handler"],
            name=spec["name"],
            description=spec["description"],
    
            # Structured output is temporarily disabled until proper schema definitions are implemented.
            # See https://github.com/ydb-platform/ydb-mcp/issues/12 for details.
            structured_output=False,
        )
    
        # Also register with our tool manager
        self.tool_manager.register_tool(
            name=spec["name"],
            handler=spec["handler"],
            description=spec["description"],
            parameters=spec.get("parameters"),
        )
  • The tool specification dictionary defining the schema (input parameters: sql string, params string) and description for ydb_explain_query_with_params.
    {
        "name": "ydb_explain_query_with_params",
        "description": "Explain a parametrized SQL query with JSON parameters",
        "handler": self.explain_query_with_params,  # Use real handler
        "parameters": {
            "properties": {
                "sql": {"type": "string", "title": "Sql"},
                "params": {"type": "string", "title": "Params"},
            },
            "required": ["sql", "params"],
            "type": "object",
        },
  • The core explain_query helper method called by the tool handler, which performs the actual YDB explain operation using the session pool.
    async def explain_query(self, sql: str, params: Optional[Dict[str, Any]] = None) -> List[TextContent]:
        """Explain a SQL query against YDB
    
        Args:
            sql: SQL query to execute
            params: Optional query parameters
    
        Returns:
            Execution plan of the query as TextContent object with JSON-formatted execution plan
        """
        # Check if there's an authentication error
        if self.auth_error:
            return [TextContent(type="text", text=json.dumps({"error": self.auth_error}, indent=2))]
    
        try:
            pool = await self.get_pool()
            ydb_params = None
            if params:
                ydb_params = {}
                for key, value in params.items():
                    param_key = key if key.startswith("$") else f"${key}"
                    ydb_params[param_key] = value
    
            structured_plan = await pool.explain_with_retries(
                query=sql,
                parameters=ydb_params,
                result_format=ydb.QueryExplainResultFormat.DICT,
            )
    
            safe_plan = self._stringify_dict_keys(structured_plan)
            formatted_plan = json.dumps(safe_plan, indent=2, cls=CustomJSONEncoder)
            logger.info(f"Query plan: {formatted_plan}")
            return [TextContent(type="text", text=formatted_plan)]
        except Exception as e:
            error_message = str(e)
            safe_error = self._stringify_dict_keys({"error": error_message})
            return [TextContent(type="text", text=json.dumps(safe_error, indent=2))]
  • Helper function to parse the JSON string parameters into YDB-compatible parameter dictionary, used by the tool handler.
    def _parse_str_to_ydb_params(self, params: str) -> Dict:
        parsed_params = {}
        if params and params.strip():
            parsed_params = json.loads(params)
    
        # Convert [value, type] to YDB type if needed
        ydb_params = {}
        for key, value in parsed_params.items():
            param_key = key if key.startswith("$") else f"${key}"
            if isinstance(value, (list, tuple)) and len(value) == 2:
                param_value, type_name = value
                if isinstance(type_name, str) and hasattr(ydb.PrimitiveType, type_name):
                    ydb_type = getattr(ydb.PrimitiveType, type_name)
                    ydb_params[param_key] = (param_value, ydb_type)
                else:
                    ydb_params[param_key] = param_value
            else:
                ydb_params[param_key] = value
    
        return ydb_params
Behavior2/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 states the tool explains queries but doesn't specify what the explanation includes (e.g., execution plan, cost estimates), whether it's read-only or has side effects, or any constraints like rate limits or authentication needs. This leaves significant gaps in understanding the tool's behavior.

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 a single, clear sentence with no wasted words, making it highly concise and front-loaded. It efficiently communicates the core purpose without unnecessary elaboration, earning a top score for brevity and structure.

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

Completeness2/5

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

Given the complexity of explaining parameterized SQL queries, the lack of annotations, no output schema, and low schema description coverage, the description is incomplete. It doesn't address what the explanation output entails, potential errors, or usage nuances, making it inadequate 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.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 0%, meaning the input schema provides no descriptions for the 'sql' and 'params' parameters. The description adds minimal value by implying 'sql' is a SQL query and 'params' are JSON parameters, but it doesn't clarify the format, syntax, or examples (e.g., how JSON parameters should be structured), which is insufficient given the low coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Explain') and the resource ('a parametrized SQL query with JSON parameters'), which is specific and informative. However, it doesn't explicitly distinguish this tool from its sibling 'ydb_explain_query', which likely explains non-parameterized queries, leaving some ambiguity about when to choose one over the other.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. Given the sibling tools include 'ydb_explain_query' and 'ydb_query_with_params', there's no indication of whether this is for debugging, optimization, or other contexts, nor any prerequisites or exclusions mentioned.

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/ydb-platform/ydb-mcp'

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