An AI agent does not need to write 50-line queries against V$ACTIVE_SESSION_HISTORY; it needs a typed get_top_waits(minutes_back=30) tool that returns a bounded markdown table from DBA-verified SQL.

TL;DR

  • Problem: Giving an LLM raw SELECT access over Oracle dynamic performance views causes silent join hallucinations, unbounded DBA_HIST_ACTIVE_SESS_HISTORY scans, and rapid context-window exhaustion during incidents.
  • Answer: Expose a curated FastMCP server backed by a bounded python-oracledb connection pool, fixed bind-variable SQL templates, Oracle Resource Manager SWITCH_TIME_IN_CALL limits, and Oracle 23ai SQL Firewall allowlists.
  • Watch out: New wait classes or RAC anomalies outside the curated tool catalog return incomplete triage data until a DBA adds and grants the new tool.

Separate reasoning from SQL execution with typed MCP tools

Situation

The Model Context Protocol (MCP), published by Anthropic in November 2024 and updated in the March 26, 2025 specification with Streamable HTTP transport and tool annotations, defines a JSON-RPC 2.0 interface for AI agents to discover and invoke external tools. An MCP server publishes a manifest of tools with JSON Schema parameter definitions and natural-language descriptions. The model selects a tool and emits a structured JSON argument payload; the server validates those arguments, runs the underlying operation, and returns a bounded CallToolResult.

For Oracle Database fleets, the default alternative is giving an agent a generic read-only SQL execution tool such as SQLcl MCP or a custom run_select(sql) wrapper. That pattern works on small development schemas, where V$ACTIVE_SESSION_HISTORY holds minutes of low-concurrency samples. In production, however, merging reasoning and SQL authoring inside the same model loop couples two unrelated failure domains: diagnostic triage and Oracle dictionary fluency.

The documented failure pattern with generic read-only SQL tools on Oracle is straightforward. Oracle’s dynamic performance views (V$, GV$) and Automatic Workload Repository tables (DBA_HIST_*) encode three decades of schema conventions. When an agent guesses a join key or omits a time-boundary predicate on a multi-hundred-gigabyte partitioned DBA_HIST_ACTIVE_SESS_HISTORY table, the database executes a valid SELECT that saturates I/O and pollutes the buffer cache while the operator waits for triage.

The Problem

Allowing an LLM to author ad-hoc diagnostic SQL against a read-only Oracle account fails under four concrete operational constraints.

1. Schema and join-key ambiguity. Oracle performance views do not share uniform join keys. V$SQL is keyed by (SQL_ID, CHILD_NUMBER, CON_ID), so joining V$SESSION.SQL_ID to V$SQL.SQL_ID without V$SESSION.SQL_CHILD_NUMBER = V$SQL.CHILD_NUMBER multiplies rows whenever multiple child cursors exist. Similarly, V$ACTIVE_SESSION_HISTORY stores wait duration in TIME_WAITED (in microseconds), whereas V$SYSTEM_EVENT uses TIME_WAITED_MICRO; V$DATAGUARD_STATS identifies the protected primary with SOURCE_DB_UNIQUE_NAME, not DB_UNIQUE_NAME. An LLM guessing column names from memory either hits ORA-00904: invalid identifier or silently returns multiplied rows.

2. Unbounded historical scan horizon. On a busy OLTP instance, V$ACTIVE_SESSION_HISTORY samples active sessions once per second in a circular SGA buffer, while DBA_HIST_ACTIVE_SESS_HISTORY persists 1-in-10 samples to SYSAUX across the AWR retention window. A 30-day or 60-day retention table across active RAC nodes easily reaches tens or hundreds of gigabytes. A single unindexed query omitting SAMPLE_TIME > SYSDATE - :mb/1440 triggers a full partition scan that competes directly with production foreground reads.

3. Context-window token budget. Consider a 4-column diagnostic table returned to an 8,192-token triage context. If an un-truncated query returns 200 rows with 200-character SQL_TEXT values (~65 tokens per row), a single tool response consumes 200 * 65 = 13,000 tokens — overflowing the 8,192-token window before the model even inspects blocking sessions. Capping output at 25 rows and SUBSTR(sql_text, 1, 80) bounds each response to roughly 25 * 35 = 875 tokens (~10.7% of an 8K window), leaving room for 4–5 tool calls plus reasoning.

4. Connection and call-duration ceiling. During a fleet-wide slowdown, multiple on-call engineers trigger concurrent agent runs. Without a connection pool cap (max=20) and a database-side per-call timeout (SWITCH_TIME_IN_CALL => 15 seconds), 50 simultaneous retries spawn 50 long-running V$ scans that hold latches and exhaust SESSIONS.

Unbounded ad-hoc SQL fails on four production constraints

How do you give an AI incident agent deterministic, sub-15-second Oracle diagnostic visibility without letting the model write SQL or exhaust production database resources?

Options Considered

Platform teams evaluating AI-assisted Oracle triage face four architectural choices with sharply different blast radii.

OptionAI Access ModelSafety BoundaryWhy Chosen or Rejected
Raw SQL*Plus or JDBC shellFull DML, DDL, ALTER SYSTEMNone; prompt injection can drop objects or kill sessionsRejected — catastrophic blast radius on production
Generic SQLcl MCP (read-only)Arbitrary SELECT generationUser privileges only; no join or predicate enforcementRejected for prod — DBA_HIST_* full scans and join hallucinations
Oracle Enterprise Manager (OEM)Pre-built UI dashboardsHigh; curated by DBA and OEM teamsRejected — no native JSON-RPC tool manifest for agent loops
Curated Diagnostic MCP ServerTyped, parameterized Python toolsFastMCP schema + bind SQL + Resource Manager + SQL FirewallChosen — deterministic SQL plans and bounded resource cost

Curated MCP tools balance safety and agent flexibility

Generic read-only SQL execution (such as SQLcl MCP pointed at a production database) is attractive because it requires zero custom tool code. We reject it for production incident triage because read-only privileges do not prevent CPU, buffer-cache, or I/O exhaustion, nor do they stop an agent from burning 30–40% of its context window recovering from ORA-00904 column errors. OEM dashboards solve the safety and query-tuning problem but cannot be invoked as structured JSON-RPC tools by an external agent without fragile screen scraping or custom REST wrappers. A curated FastMCP server isolates DBA-tuned SQL behind typed Python functions while preserving the standard MCP discovery contract.

The Curated Diagnostic MCP Server Architecture

The curated MCP server separates tool selection from SQL execution across four defense-in-depth layers: FastMCP schema validation, a bounded python-oracledb connection pool, Oracle Database Resource Manager consumer-group limits, and (on Oracle Database 23ai) SQL Firewall allowlisting.

Defense in depth spans Python validation and Oracle enforcement

flowchart TD
    A[AI Agent — Claude or SRE Client] -->|MCP JSON-RPC tool call| B[FastMCP Server — Python]
    B --> C[Parameter Validator — type check and range clamp]
    C --> D[Query Dispatcher — fixed SQL template with binds]
    D --> E[Oracle Connection Pool — oracledb pool max 20]
    E --> F[Oracle Database — Resource Manager 15s cap]
    F -->|cursor rows max 25| G[Markdown Formatter — 80-char SQL truncate]
    G -->|CallToolResult| A
    B --> H[Prometheus Exporter — tool count and p99 latency]

Connection pool and wallet authentication. The server initializes a single oracledb pool at startup so tool invocations never pay TCP and TLS handshake overhead per call. In python-oracledb Thin mode (the default, requiring no Oracle Instant Client), mTLS wallets require the PEM-formatted ewallet.pem file (wallet_location and wallet_password), whereas auto-login SSO wallets (cwallet.sso) are supported only in Thick mode via oracledb.init_oracle_client(). Choose one mode explicitly at deployment rather than assuming Thin mode reads cwallet.sso:

from contextlib import contextmanager
import os
import oracledb
from mcp.server.fastmcp import FastMCP
from prometheus_client import Counter, Histogram

mcp = FastMCP("OracleDiagnosticServer")

# Thin mode: uses ewallet.pem; for auto-login cwallet.sso, call init_oracle_client()
pool = oracledb.create_pool(
    dsn="fleet_readonly_tns",
    user=os.environ["MCP_DB_USER"],
    password=os.environ["MCP_DB_PASSWORD"],
    config_dir=os.environ["TNS_ADMIN"],
    wallet_location=os.environ["TNS_ADMIN"],
    wallet_password=os.environ.get("MCP_WALLET_PASSWORD"),
    min=5,
    max=20,
    increment=2,
    timeout=30,
    getmode=oracledb.POOL_GETMODE_WAIT,
)

MAX_RESULT_ROWS = 25
tool_calls = Counter("mcp_tool_calls_total", "Total MCP tool calls", ["tool_name"])
tool_latency = Histogram(
    "mcp_tool_latency_seconds",
    "MCP tool latency",
    ["tool_name"],
    buckets=[0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 15.0],
)

@contextmanager
def get_conn():
    conn = pool.acquire()
    try:
        yield conn
    finally:
        pool.release(conn)

Curated diagnostic tools with verified Oracle view schemas. Every tool clamps numeric bounds in Python, sets DBMS_SESSION.SET_IDENTIFIER for DBA traceability in V$SESSION, binds all parameters, and caps output at MAX_RESULT_ROWS = 25:

@mcp.tool()
def get_top_waits(minutes_back: int = 30) -> str:
    """Return top non-idle wait events from V$ACTIVE_SESSION_HISTORY."""
    minutes_back = max(1, min(minutes_back, 120))
    sql = """
        SELECT wait_class,
               event,
               ROUND(SUM(time_waited) / 1e6, 2) AS total_wait_sec,
               COUNT(*) AS sample_count
        FROM   v$active_session_history
        WHERE  sample_time > SYSDATE - :mb / 1440
          AND  session_state = 'WAITING'
          AND  wait_class != 'Idle'
        GROUP BY wait_class, event
        ORDER BY total_wait_sec DESC
        FETCH FIRST :max_rows ROWS ONLY
    """
    with tool_latency.labels("get_top_waits").time():
        tool_calls.labels("get_top_waits").inc()
        with get_conn() as conn:
            cur = conn.cursor()
            cur.callproc("dbms_session.set_identifier", ["mcp_get_top_waits"])
            rows = cur.execute(sql, mb=minutes_back, max_rows=MAX_RESULT_ROWS).fetchall()
    return _to_markdown(["Wait Class", "Event", "Total Wait (s)", "Samples"], rows)


@mcp.tool()
def get_blocking_sessions() -> str:
    """Return current blocker and waiter pairs with truncated SQL text."""
    sql = """
        SELECT s1.username || ' (SID=' || s1.sid || ')' AS blocker,
               s2.username || ' (SID=' || s2.sid || ')' AS waiter,
               l1.type AS lock_type,
               SUBSTR(sq.sql_text, 1, 80) AS blocker_sql
        FROM   v$lock l1
        JOIN   v$session s1 ON s1.sid = l1.sid
        JOIN   v$lock l2    ON l1.id1 = l2.id1 AND l1.id2 = l2.id2
        JOIN   v$session s2 ON s2.sid = l2.sid
        LEFT JOIN v$sql sq  ON sq.sql_id = COALESCE(s1.sql_id, s1.prev_sql_id)
                           AND sq.child_number = s1.sql_child_number
        WHERE  l1.block = 1
          AND  l2.request > 0
        FETCH FIRST :max_rows ROWS ONLY
    """
    with tool_latency.labels("get_blocking_sessions").time():
        tool_calls.labels("get_blocking_sessions").inc()
        with get_conn() as conn:
            rows = conn.cursor().execute(sql, max_rows=MAX_RESULT_ROWS).fetchall()
    return _to_markdown(["Blocker", "Waiter", "Lock Type", "Blocker SQL"], rows)

Notice two critical Oracle details in those queries. First, V$ACTIVE_SESSION_HISTORY.TIME_WAITED reports microseconds for the final sample of a wait event (TIME_WAITED_MICRO does not exist on V$ACTIVE_SESSION_HISTORY). Second, joining V$SQL on COALESCE(s1.sql_id, s1.prev_sql_id) and s1.sql_child_number prevents row multiplication across child cursors while still surfacing the blocker’s SQL when the blocking session has returned to INACTIVE state between statements.

For Data Guard and ASM tools, V$DATAGUARD_STATS exposes SOURCE_DB_UNIQUE_NAME (not DB_UNIQUE_NAME), and V$ASM_DISKGROUP exposes TOTAL_MB, FREE_MB, and USABLE_FILE_MB. Always test every query directly against the target Oracle version before registering it in the MCP manifest.

Startup grant verification and in-flight deduplication. Before FastMCP begins serving requests, the server executes a lightweight SELECT 1 FROM <view> WHERE 1 = 0 check against every view in the tool catalog (V$ACTIVE_SESSION_HISTORY, V$LOCK, V$SESSION, V$SQL, V$DATAGUARD_STATS, V$ASM_DISKGROUP). If any grant is missing, the process exits non-zero so Kubernetes or systemd refuses to mark the server ready—preventing an LLM from hallucinating around ORA-00942 during an outage. Inside the request dispatcher, an in-flight cache keyed by (tool_name, sorted_args) coalesces duplicate calls issued within a 5-second window so LLM retry storms cannot multiply concurrent database scans. Finally, alerting on mcp_tool_latency_seconds p99 > 10 seconds acts as a meta-signal: when even bounded 25-row V$ queries approach the 15-second Resource Manager ceiling, the database is under severe latch or CPU contention and requires immediate human escalation.

Database-tier Resource Manager enforcement. Python timeouts alone cannot cancel an active server-side Oracle call cleanly if the client drops mid-fetch. Oracle Database Resource Manager enforces a hard per-call execution cap inside a pending area using SWITCH_TIME_IN_CALL (designed specifically for connection-pooled workloads so execution time is measured per top-level call rather than across the lifetime of the pooled session) and SWITCH_GROUP => 'CANCEL_SQL':

BEGIN
  DBMS_RESOURCE_MANAGER.CLEAR_PENDING_AREA;
  DBMS_RESOURCE_MANAGER.CREATE_PENDING_AREA;

  DBMS_RESOURCE_MANAGER.CREATE_CONSUMER_GROUP(
    consumer_group => 'MCP_DIAGNOSTIC_GROUP',
    comment        => 'Resource group for AI diagnostic MCP server connections'
  );
  DBMS_RESOURCE_MANAGER.SET_CONSUMER_GROUP_MAPPING(
    attribute      => DBMS_RESOURCE_MANAGER.ORACLE_USER,
    value          => 'MCP_READONLY_USER',
    consumer_group => 'MCP_DIAGNOSTIC_GROUP'
  );
  DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(
    plan             => 'DEFAULT_PLAN',
    group_or_subplan => 'MCP_DIAGNOSTIC_GROUP',
    comment          => 'Cancel any MCP diagnostic SQL call exceeding 15 seconds',
    mgmt_p1          => 5,
    switch_group     => 'CANCEL_SQL',
    switch_time_in_call => 15
  );

  DBMS_RESOURCE_MANAGER.VALIDATE_PENDING_AREA;
  DBMS_RESOURCE_MANAGER.SUBMIT_PENDING_AREA;
END;
/

How It Rolls Out

Deploying an AI diagnostic server onto production databases requires four gated phases so that missing view grants, expensive execution plans, or unexpected SQL never reach primary workloads unchecked.

Rollout gates grants, SQL allowlists, and pool limits first

Phase 1: Least-privilege role and Resource Manager setup. Create MCP_READONLY_USER with CREATE SESSION and explicit SELECT grants on only the views referenced by registered tools (V$ACTIVE_SESSION_HISTORY, V$LOCK, V$SESSION, V$SQL, V$DATAGUARD_STATS, V$ASM_DISKGROUP). Bind the user to MCP_DIAGNOSTIC_GROUP with SWITCH_TIME_IN_CALL => 15 and MGMT_P1 => 5. Gate: verify SELECT succeeds on every view and confirm a synthetic DBMS_SESSION.SLEEP(20) call is cancelled at 15 seconds. Rollback: drop the consumer group mapping or lock MCP_READONLY_USER.

Phase 2: Staging volume and token-budget verification. Run every MCP tool against a staging database populated with production-scale AWR/ASH volume at maximum clamped arguments (minutes_back=120, max_rows=25). Gate: verify EXPLAIN PLAN avoids full scans on DBA_HIST_* tables and confirm every markdown response stays under 1,200 tokens. Rollback: tighten MAX_RESULT_ROWS or clamp minutes_back further before promotion.

Phase 3: SQL Firewall capture and enforcement (Oracle 23ai). Enable Oracle 23ai SQL Firewall capture for MCP_READONLY_USER while running the full MCP tool test suite, generate the allowlist from captured statements, and switch SQL Firewall to ENFORCE mode (DBMS_SQL_FIREWALL.ENABLE_ALLOW_LIST with block => TRUE). Gate: verify an unauthorized SELECT * FROM DBA_USERS executed as MCP_READONLY_USER is blocked by the database engine. Rollback: disable enforcement to log-only mode while inspecting missed allowlist entries.

Phase 4: Canary on standby and fleet rollout. Point the first production MCP server instance at an Active Data Guard physical standby (or DRCP :pooled service for fleet fan-in) and wire Prometheus alerts on mcp_tool_latency_seconds p99 > 10s and pool_busy > 18. Gate: two weeks of on-call shadow triage with zero Resource Manager cancellations or pool timeouts. Rollback: scale the MCP deployment to zero or revoke CREATE SESSION from MCP_READONLY_USER.

In Practice

  • Oracle Database Resource Manager pooled-call behavior (Pattern B): Because python-oracledb reuses pooled sessions across consecutive MCP tool calls, SWITCH_TIME (which accumulates across the session) would prematurely cancel healthy queries after several minutes of pool reuse. Using SWITCH_TIME_IN_CALL => 15 with SWITCH_GROUP => 'CANCEL_SQL' resets the timer on each top-level database call, isolating runaway queries without poisoning the pool.
  • Oracle Database 23ai SQL Firewall allowlisting (Pattern A): Per the Oracle Database 23ai Security Guide, SQL Firewall inspects incoming SQL inside the database kernel before execution and blocks statements not present in the user’s allowlist. Pairing FastMCP’s fixed SQL templates with SQL Firewall ensures that even a bug in Python argument handling cannot execute arbitrary SQL.
  • FastMCP progress reporting over Streamable HTTP (Pattern A): Under the MCP 2025-03-26 specification and FastMCP 2.x, tools return a completed CallToolResult rather than streaming raw partial SQL generators. For long-running diagnostic checks (such as multi-node RAC lock trees), FastMCP tools use await ctx.report_progress(...) over Streamable HTTP so the client stays alive without timing out the transport.
  • DRCP for multi-instance MCP fan-in (Pattern A): Per python-oracledb documentation, appending :pooled (or setting SERVER=POOLED in tnsnames.ora) with a cclass routes multiple stateless MCP server pods through Oracle’s Database Resident Connection Pool, capping total database server processes even as horizontal MCP replicas scale.

Where It Breaks

Failure ModeBreaks HowDetectMitigate
Pool exhaustion (DPY-4005 / ORA-24459)>20 concurrent engineers triage a wide outage; pool.acquire() exceeds 30s timeoutPrometheus pool_busy_count > 18 or mcp_tool_calls_total error spikeFail fast with 429 busy message to agent; route read-only fleet to DRCP :pooled
Missing V$ view grant (ORA-00942)New MCP tool deployed before DBA grants SELECT on required performance viewStartup self-check or first tool call raises ORA-00942Run startup grant verification query for all registered tools; fail readiness probe
Context window blowoutUncapped SQL_TEXT or V$SESSION_LONGOPS rows exceed 8K token budgetResponse byte size > 8 KB logged by FastMCP middlewareEnforce FETCH FIRST 25 ROWS ONLY and SUBSTR(sql_text, 1, 80) on all text columns
LLM retry stormsAgent treats an 8s query as stalled and fires 3 parallel duplicate tool callsIdentical (tool_name, args) bursts in Prometheus or V$SESSION.CLIENT_IDENTIFIERCoalesce in-flight calls by (tool_name, args) key and return cached result
Thin vs Thick wallet mismatchServer uses cwallet.sso in Thin mode without ewallet.pem or init_oracle_client()Startup fails with DPY-4011 / wallet open error on first pool acquireStandardize on ewallet.pem + wallet_password for Thin mode or call init_oracle_client()
Missing diagnostic coverageIncident involves RAC global cache or Exadata Smart Scan not in tool catalogAgent reports insufficient evidence; p99 triage falls back to manual SQLMaintain catch-all get_top_sql_by_elapsed() and get_rac_wait_events() tools

Four failure paths degrade diagnostics during incidents

Key Takeaways

  • Separate reasoning from SQL authoring: Let the LLM choose which diagnostic tool to run and interpret the returned markdown, while DBAs own every SQL template, join key, and bind variable inside the MCP server.
  • Use SWITCH_TIME_IN_CALL, not SWITCH_TIME: Connection pools reuse sessions across calls; per-call Resource Manager limits cancel slow queries at 15 seconds without terminating healthy pooled sessions.
  • Verify Oracle view columns against the target release: V$ACTIVE_SESSION_HISTORY uses TIME_WAITED (microseconds), V$DATAGUARD_STATS uses SOURCE_DB_UNIQUE_NAME, and V$SQL joins require CHILD_NUMBER to avoid silent row multiplication.
  • Match wallet format to python-oracledb mode: Thin mode requires ewallet.pem with wallet_password; auto-login cwallet.sso requires Thick mode (oracledb.init_oracle_client()).
  • Bound both rows and characters before returning to the model: Capping at 25 rows and 80-character SQL_TEXT keeps each tool response near 900 tokens so multi-step triage fits inside an 8K context window.

What to Do Next

  • Problem: Giving AI agents raw SELECT access over Oracle performance views causes silent join hallucinations, unbounded DBA_HIST_* scans, and context-window overflow during production outages.
  • Solution: Deploy a curated FastMCP server backed by a bounded python-oracledb pool, DBA-reviewed bind SQL templates, SWITCH_TIME_IN_CALL => 15 Resource Manager limits, and Oracle 23ai SQL Firewall allowlists.
  • Proof: Verify startup grant checks pass, confirm EXPLAIN PLAN avoids full DBA_HIST_* scans, and trigger a synthetic 20-second query to confirm CANCEL_SQL aborts it at 15 seconds while the pooled session remains healthy.
  • Action: Wrap your three most-used DBA triage queries (V$ACTIVE_SESSION_HISTORY top waits, V$LOCK blockers, and V$DATAGUARD_STATS lag) as FastMCP tools with FETCH FIRST 25 ROWS ONLY and test them against a staging replica this week.

Sources

  1. Model Context Protocol Specification (2025-03-26) — Streamable HTTP & Tool Annotations: https://spec.modelcontextprotocol.io/specification/2025-03-26/
  2. python-oracledb Documentation — Connection Pooling, Thin Mode Wallets (ewallet.pem), and DRCP: https://python-oracledb.readthedocs.io/en/latest/user_guide/connection_handling.html
  3. FastMCP Documentation — Tool Definitions and Context Progress Reporting: https://gofastmcp.com/servers/tools
  4. Oracle Database 19c Reference — V$ACTIVE_SESSION_HISTORY: https://docs.oracle.com/en/database/oracle/oracle-database/19/refrn/V-ACTIVE_SESSION_HISTORY.html
  5. Oracle Database 19c Reference — V$DATAGUARD_STATS: https://docs.oracle.com/en/database/oracle/oracle-database/19/refrn/V-DATAGUARD_STATS.html
  6. Oracle Database 19c PL/SQL Packages — DBMS_RESOURCE_MANAGER: https://docs.oracle.com/en/database/oracle/oracle-database/19/arpls/DBMS_RESOURCE_MANAGER.html
  7. Oracle Database 23ai Security Guide — Using Oracle SQL Firewall: https://docs.oracle.com/en/database/oracle/oracle-database/23/dbseg/using-oracle-sql-firewall.html