Giving an LLM agent raw SQL execution against a production Oracle database turns prompt reasoning into unbounded dictionary scans; safe agentic diagnostics require an MCP gateway that exposes only parameterized, pre-tuned queries backed by Oracle Resource Manager CANCEL_SQL ceilings.

TL;DR

  • Problem: Even a read-only SQL interface lets an LLM run unindexed DBA_HIST_ACTIVE_SESS_HISTORY scans without DBID or snap_id predicates, thrashing the buffer cache and burning context-window tokens on ORA-00942 retries.
  • Answer: Put a curated FastMCP gateway in front of oracledb thin-mode pools (ewallet.pem), clamp lookback and row limits in Python, use delta AWR queries (ELAPSED_TIME_DELTA), and bind the diagnostic user to an Oracle Resource Manager plan with SWITCH_GROUP => 'CANCEL_SQL' and SWITCH_TIME => 15.
  • Watch out: Oracle SQLcl’s native MCP server (sql -mcp) arrived in SQLcl 25.2 (not 24.3) and still allows arbitrary SQL on saved connections; python-oracledb thin mode ignores sqlnet.ora and requires ewallet.pem; and querying ELAPSED_TIME_TOTAL instead of ELAPSED_TIME_DELTA returns instance-lifetime totals rather than the requested lookback window.

Agentic Oracle gateway with FastMCP parameter clamping and Resource Manager CANCEL_SQL

Situation

The Model Context Protocol (MCP), introduced by Anthropic in late 2024 and updated through the 2025 specification revisions, standardizes how AI clients discover and invoke external tools over JSON-RPC 2.0. An MCP server publishes a manifest of typed functions with JSON Schema parameters. The AI client sees only the tool signatures and descriptions—not the backing database credentials, TNS aliases, or SQL templates.

In parallel, Oracle shipped native MCP server support in Oracle SQLcl 25.2 (requiring Java 17 or 21), invoked via sql -mcp against pre-saved connections (conn -save ... -savepwd ...). SQLcl -mcp is convenient for local development and controlled sandboxes because it avoids embedding raw passwords in client configs. On production OLTP fleets, however, a generic SQL execution tool still leaves the LLM responsible for choosing the right Oracle dictionary view, joining on DBID and INSTANCE_NUMBER, and bounding partition scans—tasks where a single mistake creates a production incident.

The distinction between Oracle’s in-memory V$ views and disk-backed DBA_HIST_* AWR views illustrates why view selection matters. V$ACTIVE_SESSION_HISTORY reads a bounded circular buffer in the SGA; DBA_HIST_ACTIVE_SESS_HISTORY reads persisted 1-in-10 second samples stored in SYSAUX partitions across days or weeks of AWR retention. When an LLM confuses the two or omits DBID and SNAP_ID bounds, a query that looks identical in syntax shifts from a millisecond SGA read to a multi-gigabyte SYSAUX tablespace scan. Similarly, querying V$LOCK and V$SESSION on an Oracle RAC cluster only inspects the single instance the connection landed on—missing a blocker sitting on Node 2 unless the query uses GV$LOCK and GV$SESSION joined on INST_ID.

The Problem

Allowing an LLM to author arbitrary SELECT statements against Oracle’s V$ and DBA_HIST_* views fails against four concrete operational constraints:

  1. Unbounded AWR and ASH partition scans: DBA_HIST_ACTIVE_SESS_HISTORY and DBA_HIST_SQLSTAT are range-partitioned by DBID and SNAP_ID inside SYSAUX. If an LLM omits DBID or SNAP_ID predicates—or joins V$SQL_PLAN without PLAN_HASH_VALUE—Oracle scans historical partitions across every snapshot retained in SYSAUX. A single unindexed ASH scan can saturate physical I/O and evict hot OLTP blocks from the buffer cache.
  2. Context-window exhaustion from trial-and-error SQL: LLMs frequently hallucinate Oracle view names (for example, DBA_HIST_SQL_STAT instead of DBA_HIST_SQLSTAT), triggering ORA-00942: table or view does not exist. If an agent also dumps wide diagnostic rows without SUBSTR truncation, just 15 unfiltered rows with 2 KB SQL text and explain plans consume 15 * 2,000 bytes ≈ 30 KB (~7,500 tokens) in a single turn—pushing earlier incident context out of the window.
  3. No EXPLAIN PLAN feedback gate: A human DBA checks cardinality estimates or SNAP_ID bounds before running an unfamiliar query against production. An LLM with raw SQL access submits queries directly; without Oracle Resource Manager intervention, a read-only user can still hold CPU and I/O indefinitely.
  4. Incident-storm connection pool exhaustion: During a Sev-1 outage, if 30 engineers query the assistant concurrently and each slow AWR call triggers 3 automatic client retries, 30 * 3 = 90 concurrent requests hit a database pool capped at max=10. Without per-agent rate limits and call deduplication, pool.acquire() blocks and times out across the entire gateway.

Four operational constraints making raw LLM SQL unsafe in production Oracle fleets

How do you let AI agents investigate live Oracle performance and locking incidents across a 1,000+ database fleet without exposing raw SQL execution, leaking TNS/wallet credentials, or letting runaway queries degrade production OLTP?

Options Considered

Integration ArchitectureSQL FlexibilityCredential IsolationBlast Radius CeilingWhy Chosen / Rejected
Raw JDBC / sqlplus ToolFull DDL / DML / OSNone (client holds creds)UnboundedRejected: One prompt injection or hallucinated ALTER SYSTEM / DROP causes immediate data loss.
Oracle SQLcl 25.2 (sql -mcp)Arbitrary SQL on saved connsHigh (conn -save)Depends on DB user grantsDev / Sandbox Only: Great for ad-hoc DBA workstations, but still lets an LLM write unindexed DBA_HIST_* scans.
OEM REST APIsFixed OEM endpointsHighHighLimited: Strong governance, but coarse polling granularity lags live V$LOCK / ASH triage.
Curated FastMCP Gateway + Resource ManagerPre-tuned parameterized templates onlyGateway-isolated (ewallet.pem)Python clamp + CANCEL_SQL (15s)Chosen: Eliminates arbitrary SQL structurally and backs every query with an engine-level timeout.

Comparison of four AI-to-Oracle integration options

Using Oracle SQLcl 25.2 -mcp is the fastest way to prototype an AI DBA workflow on non-production databases because it ships out of the box with connection-store isolation. Its boundary is query authorship: SQLcl -mcp executes whatever SQL the model generates (subject to the database user’s privileges). When the target is a tier-1 production OLTP fleet, replacing free-form SQL generation with typed diagnostic tools removes ORA-00942 guesswork and guarantees every query hits indexed SNAP_ID and DBID paths.

Transport choice also separates prototypes from production fleets. Running an MCP server over stdio works well for a single DBA’s local IDE session, but distributes Oracle wallet files and tnsnames.ora to every engineer’s laptop. A shared Streamable HTTP gateway behind corporate SSO and mTLS keeps ewallet.pem inside a locked-down VPC service while giving every engineer the same audited tool catalog.

The Oracle Fleet MCP Gateway Architecture

The gateway sits between the AI client and the Oracle fleet as a stateless Python FastMCP service. The agent never sees a hostname, port, TNS alias, or wallet password; it passes a logical db_identifier (validated by dictionary lookup) and bounded integer parameters.

FastMCP gateway isolating wallet pools and enforcing Oracle Resource Manager limits

1. Thin-Mode python-oracledb Pool Initialization

In python-oracledb Thin mode (the default when init_oracle_client() is not called), the driver does not read sqlnet.ora or binary cwallet.sso files. Instead, config_dir points to tnsnames.ora, while wallet_location points to the directory containing the PEM-encoded ewallet.pem (plus wallet_password if encrypted).

import logging
from dataclasses import dataclass
from typing import Dict
import oracledb
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("OracleFleetMCPGateway")
logger = logging.getLogger("oracle_mcp")

@dataclass
class DatabaseEntry:
    tns_alias: str
    config_dir: str       # contains tnsnames.ora
    wallet_dir: str       # contains ewallet.pem
    wallet_pwd: str
    display_name: str
    region: str

FLEET_REGISTRY: Dict[str, DatabaseEntry] = {}  # loaded from Vault / Secrets Manager
DB_POOLS: Dict[str, oracledb.ConnectionPool] = {}

def init_pools() -> None:
    for db_id, entry in FLEET_REGISTRY.items():
        DB_POOLS[db_id] = oracledb.create_pool(
            user="MCP_DIAG_USER",
            dsn=entry.tns_alias,
            config_dir=entry.config_dir,
            wallet_location=entry.wallet_dir,
            wallet_password=entry.wallet_pwd,
            min=2,
            max=10,
            increment=1,
            timeout=20,
            getmode=oracledb.POOL_GETMODE_WAIT,
        )

2. Tuned Delta AWR and Blocking-Session Tools

A common AWR bug is selecting elapsed_time_total from DBA_HIST_SQLSTAT—which returns cumulative elapsed time since instance startup rather than activity during the requested lookback window. Production tools must aggregate SUM(s.elapsed_time_delta) and SUM(s.executions_delta) and join DBA_HIST_SNAPSHOT on snap_id, dbid, and instance_number so RAC clusters do not double-count snapshots:

MAX_ROWS = 15
MAX_MINUTES = 120

@mcp.tool()
def get_awr_top_sql(db_identifier: str, minutes_ago: int = 60, top_n: int = 10) -> str:
    """Return top SQL by delta elapsed time within the last 5-120 minutes."""
    if db_identifier not in DB_POOLS:
        return f"Unknown database: {db_identifier}. Valid options: {list(DB_POOLS.keys())}"
    minutes_ago = max(5, min(minutes_ago, MAX_MINUTES))
    top_n = max(1, min(top_n, MAX_ROWS))

    sql = """
        SELECT s.sql_id,
               ROUND(SUM(s.elapsed_time_delta) / 1e6, 2) AS window_elapsed_sec,
               SUM(s.executions_delta)                   AS window_executions,
               ROUND(SUM(s.elapsed_time_delta) / NULLIF(SUM(s.executions_delta), 0) / 1e6, 4) AS avg_sec,
               SUBSTR(MAX(DBMS_LOB.SUBSTR(t.sql_text, 100, 1)), 1, 100) AS sql_preview
        FROM   dba_hist_sqlstat s
        JOIN   dba_hist_snapshot sn
               ON  sn.snap_id = s.snap_id
               AND sn.dbid = s.dbid
               AND sn.instance_number = s.instance_number
        JOIN   dba_hist_sqltext t
               ON  t.sql_id = s.sql_id
               AND t.dbid = s.dbid
        WHERE  s.dbid = (SELECT dbid FROM v$database)
          AND  sn.begin_interval_time > SYSTIMESTAMP - NUMTODSINTERVAL(:minutes_ago, 'MINUTE')
        GROUP BY s.sql_id
        HAVING SUM(s.elapsed_time_delta) > 0
        ORDER BY window_elapsed_sec DESC
        FETCH FIRST :top_n ROWS ONLY
    """
    with DB_POOLS[db_identifier].acquire() as conn:
        rows = conn.cursor().execute(sql, minutes_ago=minutes_ago, top_n=top_n).fetchall()
    return _md_table(["SQL ID", "Window Elapsed (s)", "Executions", "Avg (s)", "SQL Preview"], rows)

3. Defense in Depth: Prompt Injection, Idempotency, and RAC Awareness

A curated MCP gateway also closes two failure modes that raw SQL tools leave wide open:

  • Prompt injection and parameter tampering: Suppose an engineer pastes an error log containing adversarial text ("check database PROD; DROP TABLE orders;") into an AI chat, and the model passes that string as db_identifier. Because the gateway routes db_identifier exclusively through a Python dictionary lookup (if db_identifier not in DB_POOLS) and passes numeric parameters (:minutes_ago, :top_n) strictly as oracledb bind variables, string concatenation is absent from the codebase. Even if an attacker compromises the gateway host itself, MCP_DIAG_USER holds only CREATE SESSION and explicit SELECT grants on whitelisted V$/GV$/DBA_HIST_* views—no INSERT, UPDATE, DELETE, ALTER SYSTEM, or DBA role.
  • In-flight call deduplication and rate limiting: When a database is already under heavy CPU load and an AWR query takes 8–10 seconds, MCP clients often time out and retry automatically. Tracking an in-flight cache keyed by (tool_name, db_identifier, normalized_args) with a 30-second TTL returns the first call’s result (or joins the pending future) instead of launching three parallel scans against a struggling primary.
  • RAC-aware locking (GV$LOCK / GV$SESSION): On multi-node RAC clusters, querying V$LOCK misses cross-instance blockers. Curated tools should query GV$LOCK and GV$SESSION (filtering l1.block > 0 AND l2.request > 0 across inst_id) so the agent sees the real cluster-wide blocker on the first call without needing follow-up prompts.

4. Oracle Resource Manager CANCEL_SQL Ceiling

Application-layer clamping (MAX_MINUTES = 120, MAX_ROWS = 15) is the first gate. The second, independent gate lives inside Oracle itself using DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE with SWITCH_GROUP => 'CANCEL_SQL' and SWITCH_TIME => 15. When MCP_DIAG_USER runs a statement exceeding 15 seconds of execution time, Oracle automatically cancels the SQL call with ORA-01013: user requested cancel of current operation while keeping the pooled session alive:

BEGIN
  DBMS_RESOURCE_MANAGER.CREATE_PENDING_AREA();

  DBMS_RESOURCE_MANAGER.CREATE_CONSUMER_GROUP(
    consumer_group => 'MCP_GATEWAY_GROUP',
    comment        => 'AI diagnostic MCP gateway — cancel SQL calls past 15s'
  );
  DBMS_RESOURCE_MANAGER.SET_CONSUMER_GROUP_MAPPING(
    attribute      => DBMS_RESOURCE_MANAGER.ORACLE_USER,
    value          => 'MCP_DIAG_USER',
    consumer_group => 'MCP_GATEWAY_GROUP'
  );
  DBMS_RESOURCE_MANAGER.CREATE_PLAN(
    plan    => 'MCP_DIAG_PLAN',
    comment => 'Resource plan capping MCP diagnostic calls'
  );
  DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(
    plan                  => 'MCP_DIAG_PLAN',
    group_or_subplan      => 'MCP_GATEWAY_GROUP',
    comment               => 'Cancel runaway diagnostic SQL at 15s',
    cpu_p1                => 10,
    parallel_degree_limit_p1 => 1,
    switch_group          => 'CANCEL_SQL',
    switch_time           => 15
  );
  DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(
    plan             => 'MCP_DIAG_PLAN',
    group_or_subplan => 'OTHER_GROUPS',
    comment          => 'Default workload directive',
    cpu_p1           => 90
  );

  DBMS_RESOURCE_MANAGER.VALIDATE_PENDING_AREA();
  DBMS_RESOURCE_MANAGER.SUBMIT_PENDING_AREA();
END;
/
ALTER SYSTEM SET RESOURCE_MANAGER_PLAN = 'MCP_DIAG_PLAN';

How It Rolls Out

Four-phase rollout from Resource Manager plan to fleet gateway

  1. Phase 1 — Resource Manager Plan and Read-Only User. Create MCP_DIAG_USER with explicit SELECT grants on V_$SESSION, V_$LOCK, V_$SQL, V_$DATABASE, V_$ACTIVE_SESSION_HISTORY, DBA_HIST_SQLSTAT, DBA_HIST_SQLTEXT, and DBA_HIST_SNAPSHOT. Bind the user to MCP_GATEWAY_GROUP with SWITCH_GROUP => 'CANCEL_SQL' and SWITCH_TIME => 15. Validation gate: Execute a synthetic 20-second query as MCP_DIAG_USER and confirm Oracle aborts it at 15 seconds with ORA-01013. Rollback: ALTER USER mcp_diag_user ACCOUNT LOCK;.
  2. Phase 2 — Thin-Mode Wallet and Startup Grant Verification. Deploy ewallet.pem and tnsnames.ora to the gateway host and add a startup probe that runs SELECT 1 FROM ... WHERE 1=0 against every required V$ and DBA_HIST_* view. Validation gate: Gateway refuses to start if any required grant is missing (ORA-00942). Rollback: Keep legacy read-only DBA runbooks active.
  3. Phase 3 — Non-Production Stdio Canary. Connect Claude Desktop or an internal CLI agent via stdio transport to a staging database and validate get_awr_top_sql and get_blocking_sessions against simulated lock contention. Validation gate: Accurate diagnosis without any SQL authored by the LLM and response sizes under 2,000 tokens. Rollback: Remove the MCP server entry from client config.
  4. Phase 4 — Fleet HTTP/mTLS Gateway. Expose the gateway over mTLS/IAM-authenticated Streamable HTTP with per-agent rate limits, a 30-second in-flight idempotency cache, and structured audit logging of (agent_id, tool_name, db_identifier, elapsed_ms).

In Practice

  • Oracle DBMS_RESOURCE_MANAGER CANCEL_SQL behavior (Oracle Database PL/SQL Packages and Types Reference): Setting SWITCH_GROUP => 'CANCEL_SQL' forces SWITCH_FOR_CALL => TRUE automatically. Unlike KILL_SESSION, CANCEL_SQL aborts only the offending SQL call (ORA-01013) and leaves the oracledb pooled connection intact for subsequent tool calls. You can pair it with MAX_EST_EXEC_TIME on the same directive so Oracle’s optimizer rejects obviously catastrophic plans (ORA-07455) before they even begin consuming buffer-cache blocks.
  • Oracle SQLcl 25.2 MCP Server behavior (Oracle SQLcl User’s Guide): SQLcl 25.2 introduced sql -mcp on top of saved connections (conn -save). While it protects credentials from leaking into LLM prompts, it still exposes general SQL execution—making a curated FastMCP gateway the safer boundary for production OLTP fleets.
  • MCP resources primitive (Model Context Protocol Specification): Beyond tools, MCP supports read-only resources (for example, oracle://PROD-US-EAST/awr/latest), allowing agents to fetch bounded pre-generated AWR summaries directly into context without triggering live DBA_HIST_* scans during peak load.
  • AWR ELAPSED_TIME_DELTA vs. ELAPSED_TIME_TOTAL (Oracle Database Reference): DBA_HIST_SQLSTAT stores both cumulative (_TOTAL) and per-snapshot (_DELTA) counters. Any time-windowed diagnostic tool that forgets SUM(elapsed_time_delta) or omits instance_number in the snapshot join misreports long-lived cached cursors as current-hour spikes. Similarly, on RAC clusters, pairing GV$LOCK with GV$SESSION ensures cross-instance blockers are surfaced on the first diagnostic call without requiring manual node-by-node queries.
  • python-oracledb error-surface clarity: When DPY-3015 (wallet/TLS failure) or DPY-4011 (closed/timed-out pool connection) occurs, returning a structured [DB_ERROR] string prevents the LLM from misinterpreting an empty exception as “zero blocking sessions.”

Where It Breaks

ConditionBreaks HowDetectMitigate
LLM client retries slow tool calls8s AWR query triggers 3x client retries, tripling DB load and exhausting max=10 poolSurge in duplicate (tool, db_identifier, args) calls and DPY-4011 / pool wait timeoutsAdd a 30s idempotency/dedup cache for identical in-flight calls and cap per-agent concurrency
python-oracledb thin mode missing ewallet.pemGateway points wallet_location at a folder with only cwallet.sso; thin mode fails handshakeStartup pool creation raises DPY-3015 / TLS wallet errorExport ewallet.pem into wallet_location and pass wallet_password, or switch explicitly to Thick mode
Revoked V$ or DBA_HIST_* grantTool raises ORA-00942; naive error handling lets the LLM report “no blockers found”ORA-00942 in gateway logsAssert all view SELECT grants at gateway startup and return explicit [DB_ERROR] strings to the LLM
AWR query uses _TOTAL instead of _DELTAHistorical cursor from 3 days ago tops the 60-minute listTop SQL list never changes across rolling 15-minute checksAggregate SUM(elapsed_time_delta) and join on (snap_id, dbid, instance_number)
Context window blowout on wide SQL textUnbounded sql_text across 15 rows floods the LLM contextTool response exceeds 8K tokensClamp DBMS_LOB.SUBSTR(t.sql_text, 100, 1) and cap MAX_ROWS = 15
Wrong DBID on cloned/standby DBsHardcoded DBID returns empty rows or wrong incarnation metricsEmpty AWR results on cloned test environmentsResolve DBID dynamically via (SELECT dbid FROM v$database) inside each session

Four failure modes in Oracle MCP gateways: retry storms, ewallet.pem, AWR deltas, and grant drift

Key Takeaways

  • Remove arbitrary SQL from production AI paths: An LLM cannot reliably bound DBA_HIST_ACTIVE_SESS_HISTORY partition scans or V$SQL_PLAN joins; expose typed, pre-tuned diagnostic tools instead.
  • SQLcl 25.2 -mcp is a workstation tool, not a fleet guardrail: Saved connections protect passwords, but curated FastMCP tools plus Oracle Resource Manager protect production CPU and buffer cache.
  • Enforce SWITCH_GROUP => 'CANCEL_SQL' inside Oracle: Pairing Python parameter clamping with SWITCH_TIME => 15 guarantees runaway calls fail with ORA-01013 without breaking pooled connections.
  • Mind python-oracledb thin-mode wallet rules: Thin mode ignores sqlnet.ora and cwallet.sso; configure config_dir for tnsnames.ora and wallet_location for ewallet.pem.
  • Always aggregate _DELTA AWR columns with instance_number: Joining DBA_HIST_SQLSTAT to DBA_HIST_SNAPSHOT on (snap_id, dbid, instance_number) and summing elapsed_time_delta prevents stale cumulative totals and RAC double-counting.

What to Do Next

  • Problem: Giving AI agents raw SQL execution—even with read-only credentials—exposes production Oracle fleets to unindexed AWR/ASH scans, buffer-cache eviction, and context-window waste.
  • Solution: Deploy a FastMCP gateway with dictionary-validated database routing, oracledb thin-mode wallet pools, delta AWR query templates, and an Oracle Resource Manager plan using SWITCH_GROUP => 'CANCEL_SQL'.
  • Proof: Verify in staging that a synthetic 20-second query submitted as MCP_DIAG_USER terminates at 15 seconds with ORA-01013 while the connection pool remains healthy.
  • Action: Create MCP_DIAG_USER and MCP_DIAG_PLAN on a non-production Oracle instance this week, then stand up a two-tool FastMCP prototype (get_awr_top_sql and get_blocking_sessions) before exposing any production database to an AI assistant.