Skip to main content
Glama
git-scarrow

Oracle MCP Server

by git-scarrow

execute_query

Execute SQL queries on Oracle databases to retrieve or manipulate data, supporting parameters and row limits for efficient database operations.

Instructions

Execute a SQL query on the Oracle database

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSQL query to execute
paramsNoQuery parameters (optional)
maxRowsNoMaximum number of rows to return (default: 1000)

Implementation Reference

  • The handleExecuteQuery method is the primary handler for the 'execute_query' tool. It validates the input arguments, calls the executeQuery helper, and returns the result in the MCP content format.
    async handleExecuteQuery(args) {
      // Input validation
      if (!args.query || typeof args.query !== 'string') {
        throw new Error('Query parameter is required and must be a string');
      }
      
      if (args.query.length > 10000) {
        throw new Error('Query too long (max 10000 characters)');
      }
      
      const result = await this.executeQuery(args.query, args.params || [], {
        maxRows: args.maxRows || 1000
      });
    
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify({
              query: args.query,
              rowCount: result.rowCount,
              rows: result.rows,
              metadata: result.metadata
            }, null, 2)
          }
        ]
      };
    }
  • The input schema definition for the 'execute_query' tool, including properties for query, params, and maxRows, as returned by the ListToolsRequestHandler.
    {
      name: 'execute_query',
      description: 'Execute a SQL query on the Oracle database',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description: 'SQL query to execute'
          },
          params: {
            type: 'array',
            description: 'Query parameters (optional)',
            items: {
              type: ['string', 'number', 'boolean', 'null']
            }
          },
          maxRows: {
            type: 'number',
            description: 'Maximum number of rows to return (default: 1000)',
            default: 1000
          }
        },
        required: ['query']
      }
    },
  • src/index.js:282-284 (registration)
    Registration of the 'execute_query' tool in the CallToolRequestHandler switch statement, dispatching calls to the handleExecuteQuery method.
    case 'execute_query':
      return await this.handleExecuteQuery(args);
  • The executeQuery helper method handles the core database interaction: connects to Oracle, processes parameters, executes the query, handles errors and logging, and returns formatted results.
    async executeQuery(query, params = [], options = {}) {
      let connection;
      const startTime = Date.now();
      
      // Security audit logging
      console.error(`[AUDIT] Query execution started at ${new Date().toISOString()}`);
      console.error(`[AUDIT] Query: ${query.substring(0, 200)}${query.length > 200 ? '...' : ''}`);
      console.error(`[AUDIT] Parameters: ${JSON.stringify(params)}`);
      
      try {
        // Get connection from pool or create new connection
        const config = this.getConnectionConfig();
        connection = await oracledb.getConnection(config);
        
        // Set default schema if specified
        if (process.env.ORACLE_DEFAULT_SCHEMA) {
          // Validate schema name to prevent SQL injection
          const schemaName = process.env.ORACLE_DEFAULT_SCHEMA.toUpperCase();
          if (!/^[A-Z][A-Z0-9_$]*$/.test(schemaName)) {
            throw new Error('Invalid schema name format');
          }
          await connection.execute(`ALTER SESSION SET CURRENT_SCHEMA = ${schemaName}`);
        }
        
        // Convert positional parameters ($1, $2) to Oracle bind parameters (:1, :2)
        let oracleQuery = query;
        let oracleParams = {};
        
        // Handle PostgreSQL style parameters
        if (params.length > 0) {
          params.forEach((param, index) => {
            const pgParam = `$${index + 1}`;
            const oracleParam = `:${index + 1}`;
            oracleQuery = oracleQuery.replace(new RegExp('\\' + pgParam + '\\b', 'g'), oracleParam);
            oracleParams[index + 1] = param;
          });
        }
        
        // Execute query with options
        const result = await connection.execute(oracleQuery, oracleParams, {
          outFormat: oracledb.OUT_FORMAT_OBJECT,
          autoCommit: options.autoCommit !== false,
          maxRows: options.maxRows || 1000
        });
        
        // Format result to match expected structure
        return {
          rows: result.rows || [],
          rowCount: result.rowsAffected || (result.rows ? result.rows.length : 0),
          metadata: result.metaData
        };
      } catch (error) {
        if (connection) {
          try {
            await connection.rollback();
          } catch (rollbackError) {
            console.error('Rollback error:', rollbackError);
          }
        }
        // Audit log for errors
        console.error(`[AUDIT] Query failed: ${error.message} (Duration: ${Date.now() - startTime}ms)`);
        throw error;
      } finally {
        if (connection) {
          try {
            await connection.close();
          } catch (closeError) {
            console.error('Connection close error:', closeError);
          }
        }
        // Audit log completion
        console.error(`[AUDIT] Query execution completed (Duration: ${Date.now() - startTime}ms)`);
      }
    }
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 but offers minimal information. It states what the tool does but doesn't cover critical aspects like whether it supports read/write operations, transaction handling, error behavior, or performance implications (e.g., timeouts, resource limits). The mention of 'Oracle database' adds some context, but overall behavioral traits are largely unspecified.

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 extremely concise—a single sentence that directly states the tool's function without unnecessary words. It's front-loaded with the core action and resource, making it efficient for quick understanding. Every word earns its place, with no redundant or verbose phrasing.

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 a database query tool with no annotations and no output schema, the description is incomplete. It doesn't explain return values (e.g., result sets, error formats), behavioral constraints, or usage prerequisites. For a tool that could involve data mutation or resource-intensive operations, more context is needed to ensure safe and effective use by an AI agent.

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 clear documentation for all three parameters (query, params, maxRows). The description adds no additional parameter semantics beyond what's in the schema, such as query syntax examples, parameter binding details, or maxRows implications. This meets the baseline of 3 since the schema adequately covers parameter meanings.

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 Oracle database'), making the purpose immediately understandable. It distinguishes from siblings like 'describe_table' or 'list_tables' by focusing on query execution rather than metadata retrieval. However, it doesn't explicitly differentiate from potential non-sibling alternatives like 'execute_update' or 'execute_procedure' that might exist in other contexts.

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. It doesn't mention whether this is for read-only queries, data modification, or both, nor does it specify prerequisites like database connections or permissions. Given siblings like 'describe_table' for metadata, there's no explicit differentiation in usage context.

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/git-scarrow/oracle-mcp-server'

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