Skip to main content
Glama
yuanoOo

OceanBase MCP Server

by yuanoOo

execute_sql

Execute SQL queries on OceanBase databases via the MCP Server, enabling AI assistants to securely interact with and manage data through a controlled interface.

Instructions

Execute an SQL query on the OceanBase server

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesThe SQL query to execute

Implementation Reference

  • The @app.call_tool() decorator defines the handler for the 'execute_sql' tool. It validates the tool name, extracts the SQL query from arguments, connects to the OceanBase database using mysql.connector, executes the query, handles special cases like SHOW TABLES, SHOW COLUMNS, DESCRIBE, SELECT queries by formatting results as CSV-like text, commits non-SELECT queries, and returns TextContent or error messages.
    @app.call_tool()
    async def call_tool(name: str, arguments: dict) -> list[TextContent]:
        """Execute SQL commands."""
        config = get_db_config()
        logger.info(f"Calling tool: {name} with arguments: {arguments}")
    
        if name != "execute_sql":
            raise ValueError(f"Unknown tool: {name}")
    
        query = arguments.get("query")
        if not query:
            raise ValueError("Query is required")
    
        try:
            with connect(**config) as conn:
                with conn.cursor() as cursor:
                    cursor.execute(query)
    
                    # Special handling for SHOW TABLES
                    if query.strip().upper().startswith("SHOW TABLES"):
                        tables = cursor.fetchall()
                        result = ["Tables_in_" + config["database"]]  # Header
                        result.extend([table[0] for table in tables])
                        return [TextContent(type="text", text="\n".join(result))]
    
                    elif query.strip().upper().startswith("SHOW COLUMNS"):
                        resp_header = "Columns info of this table: \n"
                        columns = [desc[0] for desc in cursor.description]
                        rows = cursor.fetchall()
                        result = [",".join(map(str, row)) for row in rows]
                        return [TextContent(type="text", text=resp_header + ("\n".join([",".join(columns)] + result)))]
    
                    elif query.strip().upper().startswith("DESCRIBE"):
                        resp_header = "Description of this table: \n"
                        columns = [desc[0] for desc in cursor.description]
                        rows = cursor.fetchall()
                        result = [",".join(map(str, row)) for row in rows]
                        return [TextContent(type="text", text=resp_header + ("\n".join([",".join(columns)] + result)))]
    
                    # Regular SELECT queries
                    elif query.strip().upper().startswith("SELECT"):
                        columns = [desc[0] for desc in cursor.description]
                        rows = cursor.fetchall()
                        result = [",".join(map(str, row)) for row in rows]
                        return [TextContent(type="text", text="\n".join([",".join(columns)] + result))]
    
                    # Non-SELECT queries
                    else:
                        conn.commit()
                        return [
                            TextContent(type="text", text=f"Query executed successfully. Rows affected: {cursor.rowcount}")]
    
        except Error as e:
            logger.error(f"Error executing SQL '{query}': {e}")
            return [TextContent(type="text", text=f"Error executing query: {str(e)}")]
  • The @app.list_tools() function registers the 'execute_sql' tool, providing its name, description, and input schema requiring a 'query' string.
    @app.list_tools()
    async def list_tools() -> list[Tool]:
        """List available OceanBase tools."""
        logger.info("Listing tools...")
        return [
            Tool(
                name="execute_sql",
                description="Execute an SQL query on the OceanBase server",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "query": {
                            "type": "string",
                            "description": "The SQL query to execute"
                        }
                    },
                    "required": ["query"]
                }
            )
        ]
  • The inputSchema defines the expected input for the 'execute_sql' tool: an object with a required 'query' string property.
    inputSchema={
        "type": "object",
        "properties": {
            "query": {
                "type": "string",
                "description": "The SQL query to execute"
            }
        },
        "required": ["query"]
    }
  • Helper function get_db_config() retrieves OceanBase connection details from environment variables (OB_HOST, OB_PORT, OB_USER, OB_PASSWORD, OB_DATABASE) and validates required fields, used by the handler.
    def get_db_config():
        """Get database configuration from environment variables."""
        config = {
            "host": os.getenv("OB_HOST", "localhost"),
            "port": int(os.getenv("OB_PORT", "2881")),
            "user": os.getenv("OB_USER"),
            "password": os.getenv("OB_PASSWORD"),
            "database": os.getenv("OB_DATABASE")
        }
    
        if not all([config["user"], config["password"], config["database"]]):
            logger.error("Missing required database configuration. Please check environment variables:")
            logger.error("OB_USER, OB_PASSWORD, and OB_DATABASE are required")
            raise ValueError("Missing required database configuration")
    
        return config
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions execution but fails to address critical aspects like required permissions, transaction handling, error behavior, or result format. This leaves significant gaps for a tool that performs database operations.

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, efficient sentence that directly states the tool's function without unnecessary elaboration. It's appropriately sized and front-loaded, with zero wasted words.

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?

For a database execution tool with no annotations and no output schema, the description is insufficient. It lacks information about return values, error handling, security requirements, and operational constraints, which are critical for proper tool invocation in this context.

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

Parameters3/5

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

Schema description coverage is 100%, with the single parameter 'query' documented in the schema. The description adds no additional parameter semantics beyond what the schema already provides, so it meets the baseline for adequate but unenhanced documentation.

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 ('execute') and resource ('SQL query on the OceanBase server'), providing a specific verb+resource combination. However, with no sibling tools mentioned, there's no opportunity to distinguish from alternatives, which prevents a perfect score.

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, prerequisites, or limitations. It merely states what the tool does without context for application, leaving the agent to infer usage scenarios independently.

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

Related 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/yuanoOo/oceanbase_mcp_server'

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