Skip to main content

Building Secure PL/SQL APIs for AI Agents

Beyond Vibe Coding: Secure Agentic Development with Oracle APEX - Part 2a

Updated 28 min readMarkdown
Part of seriesBeyond Vibe Coding: Secure Agentic Development with Oracle APEX
Building Secure PL/SQL APIs for AI Agents

Introduction

Enabling Controlled Database Writes with Definer Rights, Input Validation and Guarded Updates

In the previous article of this series, we configured the Oracle SQLcl MCP Server and established a dedicated database account that allows our AI agent to access selected application data without having direct access to the underlying application tables.

We limited the agent's access to our application data to a dedicated read-only view.

But what if we want our AI agent to do more than just read data?

What if we want it to analyze documents, generate assessments, identify potential issues or classify information and store the results directly in our Oracle Database?

Of course, we could simply grant the agent additional database privileges.

But should we?

When I started working with Codex, Oracle APEX and the SQLcl MCP Server, I wanted the agent to do useful work while keeping the application in control of how its data changes. A PL/SQL package lets us give the agent a specific business operation to call without granting it direct access to the application table.

The underlying principle is quite simple:

We don't give the AI agent permission to modify our tables. We give it permission to execute a specific business operation.

We'll continue with the synthetic Document Review Application from Part 1. The agent can read eligible documents, preview a rating, reasoning and suggested comment, and request a save through REVIEW_AI_PKG. The human reviewer makes the final decision.

We'll build the package, try it in SQLcl and through MCP, and verify what each path actually writes.

Prerequisites

This article builds on the environment established in Part 1.

  • Oracle AI Database 26ai Free
  • Oracle APEX
  • Oracle SQLcl 26.3.2.330.1443 with MCP Server support
  • Codex CLI 0.173.0 as our AI development agent
  • Eclipse Temurin 21 LTS as our dedicated SQLcl MCP Server Java runtime

We'll also reuse the security configuration established in Part 1:

  • A dedicated SQLcl MCP Server configuration.
  • A dedicated SQLcl home directory and connection store.
  • SQLcl Restricted Mode 4 (-R 4).
  • A dedicated database account for the AI agent.
  • A restricted database view defined with WITH READ ONLY.
  • A READ object privilege on the view.

We'll continue using the following database objects and connection configuration:

Component Name
Application schema REVIEW_OWNER
AI agent database user REVIEW_AGENT
Application table REVIEW_DOCUMENTS
Read-only view REVIEW_AI_QUEUE_V
SQLcl connection review-agent-connection
MCP Server sqlcl_project

In this article, we'll extend the existing data model and introduce a new PL/SQL package called REVIEW_AI_PKG as our controlled write interface.

๐Ÿ“ข

If you haven't read Part 1 yet, I recommend starting there before continuing with this article.

In Part 1, we assumed that REVIEW_OWNER already existed with the required privileges to create tables and views, as well as the necessary tablespace quota.

Since we'll now extend our application schema with a PL/SQL package, we also need the CREATE PROCEDURE system privilege.

If this privilege has not already been granted, execute the following statement as an authorized database administrator connected to the development PDB:

GRANT CREATE PROCEDURE TO review_owner;

This additional privilege is required by REVIEW_OWNER only. Our restricted REVIEW_AGENT account does not require any additional system privileges.

Why Direct DML Is Not the Solution

Let's assume our AI agent has successfully analyzed a document and wants to persist its assessment.

The most obvious solution would be to execute an UPDATE statement.

UPDATE review_owner.review_documents
   SET ai_rating  = 4,
       ai_comment = 'Well-structured document.'
 WHERE document_id = 1;

For this to work, we would need to grant the AI agent the corresponding privilege.

-- Example of what we do NOT grant.

GRANT UPDATE ON review_owner.review_documents
TO review_agent;

Technically, this would solve our immediate problem.

Architecturally, however, it would introduce a much bigger one.

The agent could potentially modify human review results, change the original document content or update multiple documents at once.

โ—

A missing or incorrectly generated WHERE clause could result in unintended changes to multiple documents.

What About Column-Level Privileges?

Oracle Database also allows us to grant UPDATE privileges on individual columns.

-- Alternative approach, not used in our architecture.

GRANT UPDATE (
    ai_rating,
    ai_reasoning,
    ai_comment
)
ON review_owner.review_documents
TO review_agent;

This would already be a significant improvement over granting UPDATE privileges on the entire table.

However, column-level privileges alone do not enforce business rules such as:

  • Existing assessments must not be overwritten by default.
  • Completed reviews and documents with a conflict of interest must be protected.
  • Only one document may be updated per API call.
  • Assessment timestamps must be generated by the database.
  • Review status changes must follow a defined lifecycle.

We could implement additional controls using constraints, triggers or other database security mechanisms.

But for our use case, I prefer a dedicated PL/SQL API.

It allows us to combine controlled access, input validation and business rules behind a clearly defined interface.

Most importantly, the agent no longer needs direct DML privileges on the application table.

Designing a Secure Database Interface

Definer rights and invoker rights

The package's AUTHID clause determines the runtime context for resolving names and checking SQL privileges. An invoker-rights package (AUTHID CURRENT_USER) uses the current user's context. For both rights models Oracle checks static SQL at compile time in the owner context. For a direct call by REVIEW_AGENT, our update would need authorization in that runtime context. Giving the agent a table grant to make that work would undermine the boundary we set up in Part 1.

With AUTHID DEFINER, the runtime context switches to the package owner, subject to Oracle's PL/SQL privilege rules. Here REVIEW_OWNER owns both the package and the table. The agent needs EXECUTE on the package, and the static update runs using the owner's authority. I declare AUTHID DEFINER explicitly so that choice is visible in the specification.

The following table summarizes the key differences for our use case:

Characteristic Invoker Rights Definer Rights
AUTHID CURRENT_USER DEFINER
Runtime privilege context Current user Package owner
Agent requires UPDATE privileges on the application table for our operation Yes, without additional privilege mechanisms No
Suitable for our controlled write interface Not for this design Yes
Runtime privilege context for invoker-rights and definer-rights packages

A definer-rights package is not automatically secure just because it uses AUTHID DEFINER.

The package itself becomes part of our security boundary.

A package-level EXECUTE grant covers every public member, including public operations you add later. Keeping the public interface small is therefore an important part of our security design.

If we expose an unrestricted SQL execution procedure, use unsafe dynamic SQL or fail to validate input, we could unintentionally expose capabilities that the calling user should never have had.

In our example, the caller supplies assessment values and the package defines the SQL.

Separating AI and human responsibilities

We'll reuse the same MCP server and database identity from Part 1. The view determines what the agent can read. The package determines which changes it can request.

Restricted read path and package-controlled write path

The responsibilities are now clearly separated.

Component Responsibility
AI Agent Analyze documents and generate assessments
SQLcl MCP Server Provide database connectivity and tools
REVIEW_AGENT Restricted database identity
REVIEW_AI_QUEUE_V Expose eligible documents and selected assessment data
REVIEW_AI_PKG Validate input and enforce business rules for write operations
REVIEW_DOCUMENTS Store application data
Human Reviewer Make independent review decisions

From a database privilege perspective, our architecture is based on two controlled access paths:

  • READ on REVIEW_AI_QUEUE_V
  • EXECUTE on REVIEW_AI_PKG

The agent can read through a view and request controlled writes through a package.

Category Attributes Agent write access
Document Data DOCUMENT_ID, DOCUMENT_TEXT No
AI Assessment AI_RATING, AI_REASONING, AI_COMMENT, AI_MODEL, AI_REVIEWED_AT Through API only
Human Assessment FINAL_RATING, REVIEW_COMMENT, PERSONAL_NOTES No
Review Status REVIEW_STATUS API-controlled transition from OPEN to AI_REVIEWED only
Conflict of Interest CONFLICT_OF_INTEREST No

Even if the agent generates a perfectly valid SQL statement or receives an instruction to modify the final rating, our database interface must not provide the capability to replace a human decision.

Instructions define what an agent should do.
Technical restrictions define what it can do.

Defining the Review Lifecycle

For this example, we'll use a simplified review lifecycle.

Document review lifecycle

Our package will only allow write operations in two statuses:

Review Status Initial AI Assessment Overwrite
OPEN Allowed Not allowed
AI_REVIEWED Not allowed Only when explicitly enabled
IN_PROGRESS Not allowed Not allowed
COMPLETED Not allowed Not allowed
Any other status Not allowed Not allowed

A conflict of interest also blocks writes. The queue includes conflict-free OPEN and AI_REVIEWED documents. Visibility alone is insufficient for a save because the package checks the row's current eligibility and the state of all five assessment fields.

Designing the PL/SQL API Contract

Now that we've established our architecture, we need to decide how the AI agent will communicate with the PL/SQL package.

As an Oracle developer, my first choice for a database interface is often a traditional PL/SQL package with strongly typed parameters.

Although AI agents commonly work with JSON, that doesn't mean every interface they interact with needs to accept JSON.

Since our AI agent communicates directly with Oracle Database through the SQLcl MCP Server, we can use the same PL/SQL interfaces that many of us have been working with for years.

For our use case, this provides everything we need without introducing additional JSON parsing and validation logic.

Defining the Input Parameters

Our assessment requires five input parameters:

Parameter Data Type Description
p_document_id NUMBER Identifies the document
p_ai_rating NUMBER AI-generated rating
p_ai_reasoning CLOB Explanation of the assessment
p_ai_comment VARCHAR2 Suggested review comment
p_ai_model VARCHAR2 Reported AI model identifier

Notice that we're not exposing parameters for human review results, the review status or the assessment timestamp.

These attributes are either protected from modification or managed internally by the database.

Defining the Public Operations

Our package will expose two public operations:

Operation Purpose
PREVIEW_AI_REVIEW Validate and return an assessment without modifying application data
SAVE_AI_REVIEW Validate and persist an assessment according to our business rules

Both operations use the same private input validation. The save procedure takes an additional Boolean parameter, p_allow_overwrite, which defaults to FALSE.

What About JSON?

Although we're using traditional PL/SQL parameters for our input, JSON is still useful for returning structured information to the AI agent.

Our preview function returns a CLOB containing JSON with the validated assessment values, validation_status and persisted. This gives the agent a structured representation of the assessment that can be presented to the human reviewer before requesting a save operation.

We're not avoiding JSON altogether. We're simply using it where it provides a clear benefit.

For our example, traditional PL/SQL parameters combined with a structured JSON response provide a simple and maintainable interface.

We'll see the actual JSON response later in the walkthrough.

Defining Our Validation Rules

Although our PL/SQL interface defines the expected data types, we still need to validate the values provided by the AI agent.

For our example, we'll enforce the following validation rules:

Parameter Validation
p_document_id Positive integer
p_ai_rating Integer between 1 and 5
p_ai_reasoning Nonblank, maximum 4,000 CLOB length units as measured by DBMS_LOB.GETLENGTH
p_ai_comment Nonblank, maximum 1,000 characters
p_ai_model Nonblank, maximum 100 characters

All five assessment parameters are mandatory and must not contain NULL values.

We chose these limits for the sample application.

For the reasoning, we use DBMS_LOB.GETLENGTH on a CLOB. With an AL32UTF8 database character set, a supplementary Unicode character such as ๐Ÿ˜€ takes two CLOB length units. For the VARCHAR2 comment and model identifier, we use LENGTH, which counts that same character once in AL32UTF8. Include supplementary characters when testing values at the boundary.

Input Validation Is Not AI Quality Assurance

Even an assessment that passes all our validation rules may still contain incorrect reasoning, misleading conclusions or an inappropriate rating.

Input validation is not the same as AI quality assurance.

Our PL/SQL package can enforce technical and business rules, but it cannot guarantee the quality or correctness of an AI-generated assessment.

The human reviewer still needs to judge the reasoning and the rating.

We'll explore this distinction in more detail in a later article of this series.

Enforcing Data Integrity at the Database Level

As Oracle developers, we already have powerful mechanisms for protecting data integrity directly at the database level.

Primary keys, check constraints, NOT NULL constraints and appropriate column data types are just as relevant when working with AI agents as they are when developing traditional applications.

For example, our database model allows a NULL rating because a newly created document may not have an AI assessment yet. Once an assessment is submitted through our PL/SQL API, however, the rating becomes a mandatory input.

Why do we still validate the rating within our PL/SQL package?

Because we want to validate assessments without persisting them, provide meaningful error messages and enforce consistent input validation across our public operations.

However, database constraints alone do not enforce all our business rules. A valid review status does not necessarily represent a valid status transition. Similarly, replacing an existing rating with another valid rating does not necessarily mean that the overwrite is permitted.

Rather than relying on a single security mechanism, we combine database privileges, a restricted PL/SQL interface, business rules and database constraints.

A secure PL/SQL API complements a well-designed database model. It does not replace it.

This is another example of defense in depth.

Building Our Secure PL/SQL Package

Step 1: Extend the Existing Data Model

In Part 1, we created a simple REVIEW_DOCUMENTS table to demonstrate how we can restrict an AI agent's access to selected application data.

At that point, a single AI_ASSESSMENT column was sufficient for our example. Now that we want our agent to generate and store structured assessments, we need to extend our existing data model.

We'll separate the AI-generated results from the human review data and introduce additional attributes to support our review workflow.

This is a one-time migration from the fresh Part 1 fixture. Check that the existing table has the named REVIEW_DOCUMENTS_STATUS_CK constraint. The walkthrough assumes documents 1 and 2 have their original status and sample values and that IDs 3โ€“8 are unused. If you've already extended the example or added data, check the existing columns, constraints, IDs and assessment values before proceeding. Existing document IDs and ratings must satisfy the new constraints.

Extend the REVIEW_DOCUMENTS Table

Let's connect to our REVIEW_OWNER schema and add the following columns:

ALTER TABLE review_documents ADD (
    ai_rating            NUMBER,
    ai_reasoning         CLOB,
    ai_comment           VARCHAR2(1000 CHAR),
    ai_model             VARCHAR2(100 CHAR),
    ai_reviewed_at       TIMESTAMP WITH TIME ZONE,
    review_comment       CLOB,
    conflict_of_interest CHAR(1) DEFAULT 'N' NOT NULL
);

Instead of storing the entire AI assessment in a single column, we now have dedicated columns for the individual components of an assessment and additional attributes to support our review workflow.

Column Purpose
AI_RATING Rating generated by the AI agent
AI_REASONING Explanation of the AI-generated rating
AI_COMMENT Suggested review comment
AI_MODEL Model identifier reported by the AI agent
AI_REVIEWED_AT Database-generated timestamp of the AI assessment
REVIEW_COMMENT Comment provided by the human reviewer
CONFLICT_OF_INTEREST Indicates whether the document is protected due to a conflict of interest

The original AI_ASSESSMENT column introduced in Part 1 remains in the table to preserve existing data. It is not used by our PL/SQL API.

Extend the Review Lifecycle

In Part 1, our review lifecycle consisted of three different statuses:

  • OPEN
  • AI_REVIEWED
  • COMPLETED

To distinguish between documents that have been assessed by the AI agent and documents that are currently being reviewed by a human, we'll introduce an additional status: IN_PROGRESS.

ALTER TABLE review_documents
    DROP CONSTRAINT review_documents_status_ck;

ALTER TABLE review_documents
    ADD CONSTRAINT review_documents_status_ck
    CHECK (
        review_status IN (
            'OPEN',
            'AI_REVIEWED',
            'IN_PROGRESS',
            'COMPLETED'
        )
    );

Enforce Data Integrity

As discussed earlier, we don't want to rely exclusively on our PL/SQL API to enforce data integrity.

Let's add a few additional constraints to our existing table.

First, we'll ensure that document identifiers are positive integers.

ALTER TABLE review_documents
    ADD CONSTRAINT review_documents_id_ck
    CHECK (
        document_id > 0
        AND document_id = TRUNC(document_id)
    );

Next, we'll ensure that the conflict-of-interest flag contains only valid values.

ALTER TABLE review_documents
    ADD CONSTRAINT review_documents_conflict_ck
    CHECK (
        conflict_of_interest IN ('Y', 'N')
    );

Finally, we'll restrict both AI-generated and human ratings to integer values between 1 and 5.

ALTER TABLE review_documents
    ADD CONSTRAINT review_documents_ai_rating_ck
    CHECK (
        ai_rating BETWEEN 1 AND 5
        AND ai_rating = TRUNC(ai_rating)
    );

ALTER TABLE review_documents
    ADD CONSTRAINT review_documents_final_rating_ck
    CHECK (
        final_rating BETWEEN 1 AND 5
        AND final_rating = TRUNC(final_rating)
    );

Both rating columns remain nullable, allowing us to store documents that haven't been assessed yet.

These constraints provide an additional layer of protection at database level, regardless of which application or interface modifies the data.

Update the Read-Only View

We also need to update the REVIEW_AI_QUEUE_V view introduced in Part 1.

Previously, the view exposed only documents with the status OPEN. Since our new API will also support the explicit replacement of existing AI assessments, the agent needs access to documents with the status AI_REVIEWED.

CREATE OR REPLACE VIEW review_ai_queue_v AS
SELECT
    document_id,
    document_text,
    ai_rating,
    ai_reasoning,
    ai_comment,
    ai_model,
    ai_reviewed_at,
    review_status
FROM review_documents
WHERE review_status IN ('OPEN', 'AI_REVIEWED')
  AND conflict_of_interest = 'N'
WITH READ ONLY;

Notice that we still don't expose any human review data through this view.

The agent can read the original document and its existing AI assessment, but it cannot access personal notes, final ratings or human review comments through this interface.

The view also remains read-only. All assessment writes performed by the agent will be handled exclusively through our new PL/SQL API.

With these changes in place, we can now start implementing REVIEW_AI_PKG.

Step 2: Create the Package Specification

Connect to the database as REVIEW_OWNER.

Create the following package specification:

CREATE OR REPLACE PACKAGE review_ai_pkg
AUTHID DEFINER
AS

    FUNCTION preview_ai_review (
        p_document_id  IN NUMBER,
        p_ai_rating    IN NUMBER,
        p_ai_reasoning IN CLOB,
        p_ai_comment   IN VARCHAR2,
        p_ai_model     IN VARCHAR2
    ) RETURN CLOB;

    PROCEDURE save_ai_review (
        p_document_id     IN NUMBER,
        p_ai_rating       IN NUMBER,
        p_ai_reasoning    IN CLOB,
        p_ai_comment      IN VARCHAR2,
        p_ai_model        IN VARCHAR2,
        p_allow_overwrite IN BOOLEAN DEFAULT FALSE
    );

END review_ai_pkg;
/

That's our complete public interface.

We expose only two operations: PREVIEW_AI_REVIEW and SAVE_AI_REVIEW.

All internal validation and processing routines, including our shared validator and its constants, remain private within the package body.

Step 3: Create the Package Body

Let's implement our validation logic and controlled write operation.

Both public operations will use a shared private procedure to validate the assessment parameters. The preview function will return the validated assessment as JSON, while the save procedure will additionally enforce our business rules through a guarded UPDATE.

CREATE OR REPLACE PACKAGE BODY review_ai_pkg
AS
    c_max_reasoning_length CONSTANT PLS_INTEGER := 4000;
    c_max_comment_length   CONSTANT PLS_INTEGER := 1000;
    c_max_model_length     CONSTANT PLS_INTEGER := 100;

    -- Shared input validation
    PROCEDURE validate_review (
        p_document_id  IN NUMBER,
        p_ai_rating    IN NUMBER,
        p_ai_reasoning IN CLOB,
        p_ai_comment   IN VARCHAR2,
        p_ai_model     IN VARCHAR2
    )
    IS
    BEGIN
        IF p_document_id IS NULL
           OR p_document_id <= 0
           OR p_document_id <> TRUNC(p_document_id)
        THEN
            raise_application_error(-20006, 'Document ID must be a positive integer.');
        END IF;

        IF p_ai_rating IS NULL
           OR p_ai_rating NOT BETWEEN 1 AND 5
           OR p_ai_rating <> TRUNC(p_ai_rating)
        THEN
            raise_application_error(-20006, 'AI rating must be an integer between 1 and 5.');
        END IF;

        IF p_ai_reasoning IS NULL
           OR DBMS_LOB.GETLENGTH(p_ai_reasoning) = 0
        THEN
            raise_application_error(-20005, 'AI reasoning must not be empty.');
        END IF;

        IF DBMS_LOB.GETLENGTH(p_ai_reasoning) > c_max_reasoning_length THEN
            raise_application_error(-20005, 'AI reasoning exceeds maximum length.');
        END IF;

        IF NOT REGEXP_LIKE(p_ai_reasoning, '[^[:space:]]') THEN
            raise_application_error(-20005, 'AI reasoning must not be blank.');
        END IF;

        IF p_ai_comment IS NULL
           OR NOT REGEXP_LIKE(p_ai_comment, '[^[:space:]]')
        THEN
            raise_application_error(-20005, 'AI comment must not be empty or blank.');
        END IF;

        IF LENGTH(p_ai_comment) > c_max_comment_length THEN
            raise_application_error(-20005, 'AI comment exceeds maximum length.');
        END IF;

        IF p_ai_model IS NULL
           OR NOT REGEXP_LIKE(p_ai_model, '[^[:space:]]')
        THEN
            raise_application_error(-20005, 'AI model must not be empty or blank.');
        END IF;

        IF LENGTH(p_ai_model) > c_max_model_length THEN
            raise_application_error(-20005, 'AI model exceeds maximum length.');
        END IF;
    END validate_review;


    -- Validate and preview an assessment without modifying data
    FUNCTION preview_ai_review (
        p_document_id  IN NUMBER,
        p_ai_rating    IN NUMBER,
        p_ai_reasoning IN CLOB,
        p_ai_comment   IN VARCHAR2,
        p_ai_model     IN VARCHAR2
    ) RETURN CLOB
    IS
        l_result JSON_OBJECT_T := JSON_OBJECT_T();
    BEGIN
        validate_review(
            p_document_id  => p_document_id,
            p_ai_rating    => p_ai_rating,
            p_ai_reasoning => p_ai_reasoning,
            p_ai_comment   => p_ai_comment,
            p_ai_model     => p_ai_model
        );

        l_result.put('document_id', p_document_id);
        l_result.put('ai_rating', p_ai_rating);
        l_result.put('ai_reasoning', DBMS_LOB.SUBSTR(p_ai_reasoning, c_max_reasoning_length, 1));
        l_result.put('ai_comment', p_ai_comment);
        l_result.put('ai_model', p_ai_model);
        l_result.put('validation_status', 'VALID');
        l_result.put('persisted', FALSE);

        RETURN l_result.to_clob();
    END preview_ai_review;


    -- Persist an assessment using a guarded UPDATE
    PROCEDURE save_ai_review (
        p_document_id     IN NUMBER,
        p_ai_rating       IN NUMBER,
        p_ai_reasoning    IN CLOB,
        p_ai_comment      IN VARCHAR2,
        p_ai_model        IN VARCHAR2,
        p_allow_overwrite IN BOOLEAN
    )
    IS
        l_allow_overwrite VARCHAR2(1) := 'N';
    BEGIN
        validate_review(
            p_document_id  => p_document_id,
            p_ai_rating    => p_ai_rating,
            p_ai_reasoning => p_ai_reasoning,
            p_ai_comment   => p_ai_comment,
            p_ai_model     => p_ai_model
        );

        IF p_allow_overwrite THEN
            l_allow_overwrite := 'Y';
        END IF;

        UPDATE review_documents
           SET ai_rating      = p_ai_rating,
               ai_reasoning   = p_ai_reasoning,
               ai_comment     = p_ai_comment,
               ai_model       = p_ai_model,
               ai_reviewed_at = SYSTIMESTAMP,
               review_status  = 'AI_REVIEWED'
         WHERE document_id = p_document_id
           AND conflict_of_interest = 'N'
           AND (
               -- Initial assessment
               (
                   review_status = 'OPEN'
                   AND ai_rating IS NULL
                   AND ai_reasoning IS NULL
                   AND ai_comment IS NULL
                   AND ai_model IS NULL
                   AND ai_reviewed_at IS NULL
               )
               OR
               -- Explicit overwrite of an existing assessment
               (
                   review_status = 'AI_REVIEWED'
                   AND l_allow_overwrite = 'Y'
                   AND ai_rating IS NOT NULL
                   AND ai_reasoning IS NOT NULL
                   AND ai_comment IS NOT NULL
                   AND ai_model IS NOT NULL
                   AND ai_reviewed_at IS NOT NULL
               )
           );

        IF SQL%ROWCOUNT <> 1 THEN
            raise_application_error(
                -20007,
                'Document not found, protected, inconsistent, or overwrite not permitted.'
            );
        END IF;
    END save_ai_review;

END review_ai_pkg;
/

That's our complete example package.

Let's verify the compilation status:

SELECT object_name,
       object_type,
       status
  FROM user_objects
 WHERE object_name = 'REVIEW_AI_PKG'
 ORDER BY object_type;

Both the package specification and the package body should have the status VALID.

Package specification and body compilation status

If compilation errors occur, we can inspect them using:

SELECT type,
       line,
       position,
       text
  FROM user_errors
 WHERE name = 'REVIEW_AI_PKG'
 ORDER BY type, sequence;

How the package enforces the rules

Preview and save share input validation

The shared validator rejects invalid IDs and ratings and checks for nonblank text within the contract limits. Preview uses those checks to build its JSON response without issuing DML against the table.

A successful preview confirms that the supplied values satisfy our input validation rules. It does not confirm that the document exists, is currently eligible for an assessment or may be overwritten.

A preview is not a reservation, a database lock or an approval mechanism.

These business conditions are evaluated by the save procedure.

In one test, a separate session moved the document to COMPLETED and committed after the preview. The document disappeared from the queue, the save returned ORA-20007, and the owner confirmed that all five assessment fields were unchanged.

A guarded UPDATE checks the current row

The package uses a single static UPDATE statement. We don't construct SQL statements from AI-generated input, and the agent cannot supply table names, column names or WHERE clauses through our API.

The assessment parameters are used as values within a predefined SQL statement. The calling environment still needs to pass those values safely when constructing or submitting the PL/SQL call.

The package defines the operation.
The agent only provides the input.

Instead of checking the review status in a separate SELECT statement and then executing an unconditional UPDATE, we include the relevant business conditions directly in the UPDATE statement.

This is what I refer to as a guarded UPDATE. It avoids the race condition associated with a separate check followed by an unguarded write, although it does not solve every concurrency problem.

Condition Initial assessment Overwrite
Review status OPEN AI_REVIEWED
Conflict of interest N N
Existing AI assessment fields All NULL All non-NULL
Overwrite flag Optional Explicit TRUE required

A partially populated assessment stays outside both paths. The statement changes only the AI assessment fields and, for an initial save, moves the row to AI_REVIEWED. Human assessment fields and document content are outside the assignment list. If you adapt the example, review triggers and other indirect effects as part of the application boundary.

The assessment timestamp is generated by the database using SYSTIMESTAMP, rather than supplied by the agent.

However, this timestamp does not represent the commit time or provide a complete audit trail. Similarly, the model identifier is reported by the agent and is not independently verified.

The package checks SQL%ROWCOUNT after the update. The primary key limits the operation to one document. When no eligible row is updated, the same ORA-20007 covers missing and protected documents without exposing details about rows outside the queue.

Overwrite and transaction boundaries

Omitting the flag, passing FALSE, or passing NULL leaves overwrite disabled. The caller holding EXECUTE can still pass TRUE, so asking for human approval is a workflow rule. The package has no approval record or version check tied to an earlier preview.

โ—

Explicit overwrite is not the same as enforced human approval.

In my concurrent test, two callers that explicitly enabled overwrite could both save in sequence. The last successful writer's values persisted.

Default overwrite protection reduces the risk of unintended reassessments. The API still lacks a complete idempotency mechanism.

The package contains no COMMIT or ROLLBACK. Transaction control stays with the calling environment. We'll see why that distinction matters in the SQLcl MCP walkthrough.

Granting Access and Connecting Our AI Agent

Now that we've created the package, we need to make it available to our AI agent.

Connect as REVIEW_OWNER and execute:

GRANT EXECUTE ON review_ai_pkg TO review_agent;

That's it.

For our application, the two explicit object grants to REVIEW_AGENT are READ on REVIEW_AI_QUEUE_V and EXECUTE on REVIEW_AI_PKG. The READ grant and CREATE SESSION come from Part 1. Replacing the view preserves its existing object grant.

We don't grant additional system privileges or provide the application schema credentials to the AI agent.

The following table summarizes the explicit object privileges granted to REVIEW_AGENT on our application objects:

Database Object READ SELECT INSERT UPDATE DELETE EXECUTE
REVIEW_DOCUMENTS No No No No No โ€”
REVIEW_AI_QUEUE_V Yes No No No No โ€”
REVIEW_AI_PKG โ€” โ€” โ€” โ€” โ€” Yes

Existing privileges granted through PUBLIC remain part of the effective database security environment.

This is a good example of the principle of least privilege.

The agent receives the capability it needs without receiving the underlying table privileges.

Verify the database grants

As an authorized administrator, we can inspect the explicitly granted object privileges:

SELECT grantee,
       owner,
       table_name,
       privilege,
       grantable
  FROM dba_tab_privs
 WHERE grantee = 'REVIEW_AGENT'
 ORDER BY owner,
          table_name,
          privilege;

For our dedicated agent account, we expect the following object grants:

GRANTEE OWNER TABLE_NAME PRIVILEGE GRANTABLE
REVIEW_AGENT REVIEW_OWNER REVIEW_AI_PKG EXECUTE NO
REVIEW_AGENT REVIEW_OWNER REVIEW_AI_QUEUE_V READ NO

Neither privilege is granted with the GRANT OPTION.

We can also inspect the directly granted system privileges:

SELECT grantee,
       privilege,
       admin_option
  FROM dba_sys_privs
 WHERE grantee = 'REVIEW_AGENT'
 ORDER BY privilege;

The expected result is:

GRANTEE PRIVILEGE ADMIN_OPTION
REVIEW_AGENT CREATE SESSION NO

The only directly granted system privilege is CREATE SESSION, without the ADMIN OPTION.

Finally, let's inspect the directly granted roles:

SELECT grantee,
       granted_role,
       admin_option,
       default_role
  FROM dba_role_privs
 WHERE grantee = 'REVIEW_AGENT'
 ORDER BY granted_role;

Expected result:

No rows returned.

Our dedicated agent account does not require any additional roles.

๐Ÿ’ก

These queries provide a useful starting point, but they are not a complete effective privilege audit.

As discussed in Part 1, we also need to consider privileges inherited through roles, nested roles, PUBLIC, column-level grants, schema-level privileges and other callable PL/SQL interfaces.

The intended architecture is only as restrictive as the complete set of effective privileges available to the agent.

Connect through SQLcl MCP

One of the nice things about this architecture is that we don't need to modify our existing SQLcl MCP Server configuration.

We can continue using the hardened configuration established in Part 1, including our dedicated SQLcl installation, isolated connection store and explicit Restricted Mode configuration.

Component Configuration
MCP Server sqlcl_project
Saved Connection review-agent-connection
Database User REVIEW_AGENT
Restricted Mode 4

The agent can now request controlled write operations through REVIEW_AI_PKG using the same restricted database identity that we established in Part 1.

Keep the application schema credentials in a separate, authorized session.

Before executing a preview or save operation, verify SESSION_USER, CURRENT_SCHEMA, DB_NAME, CON_NAME and SERVICE_NAME against the approved Part 1 target.

With our PL/SQL package implemented and the required privileges granted, our AI agent can now use the new API through the existing hardened SQLcl MCP configuration.

The next step is to verify that our security controls work as intended.

Conclusion

In Part 1 of this series, we established a restricted, read-only database connection for our AI agent using the Oracle SQLcl MCP Server.

In this article, we've extended that architecture with a controlled PL/SQL write interface.

By combining definer-rights packages, strongly typed parameters, shared input validation, guarded updates and database constraints, we've designed an interface that allows our AI agent to request controlled write operations without receiving direct DML privileges on the application table.

The underlying architectural principle remains the same:

Give the agent access to specific business capabilities, not unrestricted access to application data.

But implementing a security architecture is only one part of the challenge.

How do we know that our security controls actually work?

Can the agent bypass our validation rules? Can it overwrite an existing assessment without explicitly enabling overwrite? Can it modify protected application data? And what happens to our database transactions when the agent executes a PL/SQL procedure through the SQLcl MCP Server?

These are questions that cannot be answered by reviewing the implementation alone.

In the next article, we'll put our architecture to the test through manual API testing, agent integration testing, negative security tests and independent database verification.

Part 2b โ€“ Testing and Verifying Secure PL/SQL APIs for AI Agents

Because designing a secure interface and demonstrating that its security controls work are two different things.


Beyond Vibe Coding: Secure Agentic Development with Oracle APEX

Human-led. AI-orchestrated. Agent-executed. Live-observed.


References

About the author

  • Timo joined HyPlus Solutions in Ratingen, Germany, as a Senior Consultant in 2019, focusing on Oracle databases and APEX applications. With a background as a Data Warehouse Specialist, he has expertise in Database Administration, performance tuning, and SQL development. Timo is passionate about web development, cloud computing, and the architecture behind it, and became part of the Oracle ACE Community in 2023. He enjoys sharing his knowledge at conferences and through blog posts. When he's not working, you can find him traveling, hanging out with his family, or cooking up something in the kitchen.

No comments yet. Be the first to comment.

Beyond Vibe Coding: Secure Agentic Development with Oracle APEX

Part 2 of 2

What happens when we move beyond Vibe Coding and start integrating AI agents into real-world Oracle APEX development workflows? In this series, I share my hands-on experience building a secure and controlled agentic development environment using Oracle APEX, Oracle AI Database, SQLcl, MCP, Codex and APEXlang. We will explore how to enable AI agents to interact with databases, develop applications and execute complex tasks without compromising security, control or accountability. From SQLcl MCP Server hardening and least-privilege database access to secure PL/SQL APIs, agent governance, live application development, AI-assisted quality assurance and human-in-the-loop workflows, each article combines practical examples, architectural decisions, lessons learned and technical verification. The goal is not simply to develop faster with AI, but to develop securely, reliably and responsibly.

Start from the beginningSecuring the Oracle SQLcl MCP Server - Installation, Configuration and Security HardeningBeyond Vibe Coding: Secure Agentic Development with Oracle APEX - Part 1