Skip to main content
Glama
smith-nathanh

Oracle MCP Server

execute_query

Execute SQL queries against Oracle databases using SELECT, DESCRIBE, or EXPLAIN PLAN statements for data retrieval and analysis.

Instructions

Execute a SQL query against the Oracle database. Only SELECT, DESCRIBE, and EXPLAIN PLAN statements are allowed for safety.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYesSQL query to execute (SELECT, DESCRIBE, or EXPLAIN PLAN only)
paramsNoOptional parameters for parameterized queries

Implementation Reference

  • Core handler that executes the SQL query: performs safety checks (blocks DML/DDL), adds automatic ROWNUM row limits for SELECTs, executes via oracledb.Connection, handles Oracle-specific types (LOBs, dates), and returns structured JSON results.
    async def execute_query(
        self, sql: str, params: Optional[List] = None
    ) -> Dict[str, Any]:
        """Execute a SQL query with safety controls"""
    
        # Basic SQL injection prevention
        sql_upper = sql.upper().strip()
    
        # Check for potentially dangerous operations
        dangerous_keywords = [
            "DROP",
            "DELETE",
            "TRUNCATE",
            "ALTER",
            "CREATE",
            "INSERT",
            "UPDATE",
        ]
    
        # Allow SELECT, DESCRIBE, EXPLAIN PLAN
        if not any(
            sql_upper.startswith(keyword)
            for keyword in ["SELECT", "WITH", "DESCRIBE", "DESC", "EXPLAIN"]
        ):
            if any(keyword in sql_upper for keyword in dangerous_keywords):
                raise ValueError(
                    "Only SELECT, DESCRIBE, and EXPLAIN PLAN statements are allowed"
                )
    
        conn = await self.connection_manager.get_connection()
        try:
            cursor = conn.cursor()
    
            # Set row limit
            if (
                "SELECT" in sql_upper
                and "ROWNUM" not in sql_upper
                and "LIMIT" not in sql_upper
            ):
                # Add ROWNUM limitation for SELECT queries
                if "ORDER BY" in sql_upper:
                    # More complex query, wrap it
                    sql = f"SELECT * FROM ({sql}) WHERE ROWNUM <= {QUERY_LIMIT_SIZE}"
                else:
                    # Simple query, add WHERE clause
                    if "WHERE" in sql_upper:
                        sql += f" AND ROWNUM <= {QUERY_LIMIT_SIZE}"
                    else:
                        sql += f" WHERE ROWNUM <= {QUERY_LIMIT_SIZE}"
    
            start_time = datetime.now()
    
            if params:
                cursor.execute(sql, params)
            else:
                cursor.execute(sql)
    
            execution_time = (datetime.now() - start_time).total_seconds()
    
            # Fetch results
            if cursor.description:
                columns = [desc[0] for desc in cursor.description]
                rows = cursor.fetchall()
    
                # Convert Oracle types to JSON-serializable types
                serializable_rows = []
                for row in rows:
                    serializable_row = []
                    for value in row:
                        if hasattr(value, "read"):  # LOB object
                            serializable_row.append(str(value.read()))
                        elif isinstance(value, datetime):
                            serializable_row.append(value.isoformat())
                        else:
                            serializable_row.append(value)
                    serializable_rows.append(serializable_row)
    
                return {
                    "columns": columns,
                    "rows": serializable_rows,
                    "row_count": len(rows),
                    "execution_time_seconds": execution_time,
                    "query": sql,
                }
            else:
                return {
                    "message": "Query executed successfully",
                    "execution_time_seconds": execution_time,
                    "query": sql,
                }
    
        finally:
            conn.close()
  • Registers the execute_query tool in the MCP server's list_tools() handler, defining its metadata and input schema.
    Tool(
        name="execute_query",
        description="Execute a SQL query against the Oracle database. Only SELECT, DESCRIBE, and EXPLAIN PLAN statements are allowed for safety.",
        inputSchema={
            "type": "object",
            "properties": {
                "sql": {
                    "type": "string",
                    "description": "SQL query to execute (SELECT, DESCRIBE, or EXPLAIN PLAN only)",
                },
                "params": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Optional parameters for parameterized queries",
                    "default": [],
                },
            },
            "required": ["sql"],
        },
    ),
  • JSON schema defining inputs for execute_query: required 'sql' string, optional 'params' array of strings.
    inputSchema={
        "type": "object",
        "properties": {
            "sql": {
                "type": "string",
                "description": "SQL query to execute (SELECT, DESCRIBE, or EXPLAIN PLAN only)",
            },
            "params": {
                "type": "array",
                "items": {"type": "string"},
                "description": "Optional parameters for parameterized queries",
                "default": [],
            },
        },
        "required": ["sql"],
    },
  • Dispatch handler in MCP call_tool(): extracts 'sql' and 'params' from arguments, invokes QueryExecutor.execute_query, serializes result as TextContent.
    if name == "execute_query":
        sql = arguments.get("sql")
        params = arguments.get("params", [])
    
        result = await self.executor.execute_query(sql, params)
    
        return [
            TextContent(
                type="text", text=json.dumps(result, indent=2, default=str)
            )
        ]
Behavior3/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 communicates safety constraints by limiting allowed SQL types, implying read-only behavior, but lacks details on permissions, rate limits, error handling, or result format. This provides basic transparency but misses deeper 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?

The description is two sentences with zero waste: the first states the core purpose, and the second adds critical safety constraints. It is front-loaded and appropriately sized, with every sentence earning its place by providing essential information without redundancy.

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

Completeness3/5

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

Given the tool's complexity (executing SQL queries), lack of annotations, and no output schema, the description is moderately complete. It covers safety and basic usage but omits details on result format, error conditions, or performance implications, which are important for an agent to use it effectively in varied contexts.

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%, so the schema already documents both parameters (sql and params) thoroughly. The description adds no additional parameter semantics beyond what's in the schema, such as syntax examples or usage nuances. Baseline 3 is appropriate as the schema handles the heavy lifting.

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 SQL query') and target resource ('against the Oracle database'), distinguishing it from siblings like list_tables or describe_table by focusing on query execution rather than metadata retrieval. It explicitly mentions the allowed SQL statement types (SELECT, DESCRIBE, EXPLAIN PLAN), which further clarifies its scope.

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 by specifying 'Only SELECT, DESCRIBE, and EXPLAIN PLAN statements are allowed for safety,' which implicitly guides when to use this tool (for read-only/safe queries) versus when not to (for DML/DDL operations). However, it does not explicitly name alternatives or detail when to choose siblings like export_query_results for output handling.

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/smith-nathanh/oracle-mcp-server'

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