db3.aiVisit main site

7 November 2026

AI Agents Integration: 7 Checks Before Deployment

TL;DR

To verify an AI agents integration, test the boundary between model suggestions and application authority. Keep identity, workspace, resource selection, and credentials in trusted code. Reject invalid arguments, deny unauthorized reads, repeat calls deliberately, and simulate provider failures. Inspect persisted outcomes rather than trusting the final answer. The db3.ai examples below demonstrate a guarded read-only tool and tests you can extend before enabling mutations.

An agent answering a question proves that a model connection works. It does not prove that another user's records remain private, a repeated tool call is harmless, or a timeout leaves the application in a recoverable state.

AI agents integration connects model-selected tools to application data and APIs. I treat that connection as an application boundary to verify, not simply a successful function call. This guide assumes you already have a basic agent and takes it through seven deployment checks. For initial agent construction, use the existing Agents and function calls guide.

Table of contents

Prerequisites and test inputs

Use a nonproduction application, disposable data, two users, and two workspaces. Prepare one private guide per workspace, plus a revoked membership and an inaccessible resource. Never use production credentials for failure injection.

For the db3.ai examples:

  • Use an existing, booted @db3.ai/app application with AI migrations and configured Storage.
  • Follow the installation guide for matching App and Pure preview tarballs. As checked November 7, 2026, the guide says the packages are not yet published to npm. Its walkthroughs use Node.js 24 or newer.
  • Install Zod 4 for the schemas below and the tsx development runner for the test command.
  • Configure server-side provider credentials and a model using the AI setup guide.
  • Have an application policy that can check current user membership and access to the selected guide.

The examples add a tool to an existing agent. Authentication routes, database-backed permission queries, application boot, and deployment configuration remain application-specific. Run these adaptations against your exact supplied preview before deploying them.

1. Map who controls each tool input

Write a contract for every exposed operation. Separate what the model may propose from what the application decides.

Input or decision Owner Example
Authenticated identity Application User established by the session
Workspace and resource access Application policy Current membership and guide ownership
Storage path or API credentials Trusted application code Selected private guide or scoped connection
Bounded task arguments Model, subject to validation Preview between 1 and 20 lines
Permission to mutate Application policy, possibly approval An approved operation on a specific record

For our example, the model can choose a preview length. It cannot submit a different user, workspace, or file path. The db3.ai agent documentation uses the same separation between trusted context and model arguments.

Trust-boundary map separating application-selected identity and guide path from a model-proposed line count, enforced by validation and authorization.

Apply this exercise to external APIs too. Give a tool the narrow operation it needs, not a generic authenticated HTTP client. OWASP's AI Agent Security Cheat Sheet recommends limiting tools and privileges and enforcing authorization outside the model.

Verification: A reviewer should be able to identify the policy protecting each resource without reading the prompt. If the answer is only “the instructions forbid it,” the boundary is incomplete.

2. Reject invalid arguments before reading application data

We will isolate validation and authorization from the agent loop so we can test them directly.

Create server/ai/guidePreview.ts:

import { z } from 'zod';

export const PreviewInput = z.strictObject({
  lineCount: z.int().min(1).max(20),
});

export type GuideContext = Readonly<{
  userId: string;
  scopeId: string;
  guidePath: string;
}>;

export interface GuideDependencies {
  canReadGuide(context: GuideContext): Promise<boolean>;
  getText(path: string): Promise<string>;
}

export async function previewGuide(
  context: GuideContext,
  rawInput: unknown,
  dependencies: GuideDependencies,
): Promise<string> {
  const { lineCount } = PreviewInput.parse(rawInput);

  if (!(await dependencies.canReadGuide(context))) {
    throw new Error('Guide access denied.');
  }

  const text = await dependencies.getText(context.guidePath);
  if (text.length > 32_000) {
    throw new Error('Guide exceeds preview limit.');
  }

  return text.split(/\r?\n/)
    .slice(0, lineCount)
    .join('\n')
    .slice(0, 4_000);
}

Zod 4 provides strict objects and bounded numeric schemas; its parsing guide explains validation failures. Here, unknown fields are rejected, including attempts to add a model-selected path. Parsing occurs before either dependency runs.

Now create server/ai/createGuidePreviewTool.ts:

import { tool, type AgentTool } from '@db3.ai/app/ai';
import { app } from '@db3.ai/app/server';
import {
  PreviewInput,
  previewGuide,
  type GuideContext,
  type GuideDependencies,
} from './guidePreview.ts';

export function createGuidePreviewTool(
  context: GuideContext,
  canReadGuide: GuideDependencies['canReadGuide'],
): AgentTool {
  const trustedContext = Object.freeze({ ...context });

  return Object.assign(tool({
    name: 'preview_selected_guide',
    description: 'Read the first 1 to 20 lines of the authorized guide.',
    parameters: PreviewInput,
    execute: async input => previewGuide(trustedContext, input, {
      canReadGuide,
      getText: path => app().storage.getText(path),
    }),
  }), {
    title: 'Preview guide',
    description: 'Read the authorized guide preview.',
  });
}

This adapter follows the documented tool helper and Storage pattern. Return the factory's result from your existing agent's tools() method. Map authenticated application identifiers into GuideContext; supply the permission callback from application code, never from browser input.

The callback must verify current membership and the selected resource's ownership, not merely trust the path's spelling. For queued execution, construct callbacks in the worker rather than serializing functions into agent context.

The limits are deliberate example policies: 32,000 JavaScript string units for the loaded source and 4,000 for the returned preview. They are not token limits. Because the source check happens after reading, also enforce file-size limits at ingestion or in your storage adapter.

Check: Submit zero, 21, a fractional number, a string, and an extra guidePath field. Every case must fail before a storage read. A valid schema alone does not establish permission.

3. Prove user, workspace, and resource isolation

Start with deterministic tests of the guarded function. Create tests/guidePreview.test.ts:

import test from 'node:test';
import assert from 'node:assert/strict';
import {
  previewGuide,
  type GuideContext,
  type GuideDependencies,
} from '../server/ai/guidePreview.ts';

const context: GuideContext = {
  userId: 'user-a',
  scopeId: 'workspace-a',
  guidePath: 'guides/workspace-a/help.md',
};

function fixture() {
  const reads: string[] = [];
  const checks: GuideContext[] = [];
  const dependencies: GuideDependencies = {
    canReadGuide: async candidate => {
      checks.push(candidate);
      return candidate.userId === context.userId
        && candidate.scopeId === context.scopeId
        && candidate.guidePath === context.guidePath;
    },
    getText: async path => {
      reads.push(path);
      return 'One\nTwo\nThree';
    },
  };
  return { reads, checks, dependencies };
}

test('invalid input never reaches policy or Storage', async () => {
  const f = fixture();
  for (const input of [
    { lineCount: 0 },
    { lineCount: 21 },
    { lineCount: 1.5 },
    { lineCount: '2' },
    { lineCount: 2, guidePath: 'other.md' },
  ]) {
    await assert.rejects(
      previewGuide(context, input, f.dependencies),
      { name: 'ZodError' },
    );
  }
  assert.equal(f.checks.length, 0);
  assert.deepEqual(f.reads, []);
});

test('denied identities and resources never reach Storage', async () => {
  const f = fixture();
  for (const candidate of [
    { ...context, userId: 'user-b' },
    { ...context, scopeId: 'workspace-b' },
    { ...context, guidePath: 'guides/workspace-b/help.md' },
  ]) {
    await assert.rejects(
      previewGuide(candidate, { lineCount: 2 }, f.dependencies),
      /Guide access denied/,
    );
  }
  assert.deepEqual(f.reads, []);
});

test('valid input reads only the selected guide', async () => {
  const f = fixture();
  const output = await previewGuide(
    context, { lineCount: 2 }, f.dependencies,
  );
  assert.equal(output, 'One\nTwo');
  assert.deepEqual(f.reads, [context.guidePath]);
});

Run with the installed tsx runner:

node --import=tsx --test tests/guidePreview.test.ts

Node documents the test runner, assertion APIs, and using a TypeScript runner. Align your project's TypeScript checking and build settings with explicit .ts imports.

These tests prove the helper's control flow, not your real membership policy. Replace the fixture with database-backed policy tests covering revoked membership, deleted guides, and a guide moved between workspaces. Check actual storage calls and returned content, not only the error message.

Also attempt to resume user A's conversation as user B, under a different scope, and through another agent. The documented conversation ownership behavior rejects those mismatches. Verify your history and diagnostic routes enforce equivalent access checks.

If a cross-workspace test succeeds unexpectedly, inspect context construction and the policy query before changing the prompt.

4. Exercise the real agent runtime without a live provider

Helper tests cannot establish that the runtime validates a model-generated call before invoking its executor. Add an integration layer that retains the actual agent, tool registration, database, and Storage.

The db3.ai testing guidance describes injecting fetch through App AI options with a synthetic key. Replace external provider responses, not the entire agent. Use the matching preview's response fixtures rather than guessing provider payload formats.

Build a short scripted exchange: the simulated provider requests preview_selected_guide, receives its result, then returns a final answer. Repeat it with invalid arguments and a denied policy.

Scenario Application evidence to assert
Valid tool call Selected guide is read and the bounded result reaches the next turn
Malformed arguments Executor does not reach Storage
Valid arguments, denied access No private content reaches the provider
Request for an unregistered tool No application operation is dispatched
Guide text contains hostile instructions No unauthorized capability or context change occurs
Tool returns oversized content The application's output limit is enforced

For the hostile-text case, include source material requesting another workspace's file or an administrative action. Judge the test by observable operations and data disclosure, not whether the final answer politely refuses. OWASP recommends treating retrieved content as untrusted and testing agent abuse cases in its security checklist.

Keep a separate, small live-model evaluation for tool selection and answer quality. A simulated provider establishes application behavior under specified inputs; it cannot establish the reliability or quality of a live model.

5. Repeat calls and verify side effects explicitly

Our preview tool is read-only. Calling it twice should not change business records, although repeated execution can still consume resources. Test simultaneous reads and permission revocation between calls. Since the callback checks each invocation, a later call should be denied after access is removed.

Before adding a mutation, define its business identity. “Apply this approved label to ticket 42” needs a stable operation key tied to the authorized action, not a fresh key whenever the model retries.

I would add these acceptance tests:

  • Sequential duplicate: Execute the same operation twice and verify one durable business effect.
  • Concurrent duplicate: Start two attempts together and verify that the database constraint or provider idempotency mechanism resolves the race.
  • Changed payload: Reuse the key with different action details and reject the conflict.
  • Ambiguous response: Let the external operation complete, then lose its response. Reconcile before issuing another mutation.
  • Expired approval: Change the proposal revision or revoke permission before execution. The old approval must not authorize the new action.

Do not use an in-memory set as cross-worker duplicate protection. Persist the operation identity and design the transaction or external-provider boundary that protects the effect.

Stripe provides a concrete external API example: its idempotent request documentation describes keys, parameter comparison, retention, and differences between API versions. Verify the exact contract for your chosen API instead of assuming every service offers equivalent protection.

Recovery decision tree: stop invalid or denied calls, bound retries for temporary reads, and reconcile uncertain mutations before retrying.

Submission deduplication and mutation idempotency are separate responsibilities. The db3.ai agent reference explicitly leaves external tool effects to application-owned idempotency and checkpoints. A saved run does not prove an external action happened once.

6. Inject failures and inspect the request trail

Test failures at distinct boundaries: provider connection failure, provider rejection, Storage failure, authorization failure, and a tool exception after a possible external effect. Record where execution stopped and whether any action may already have occurred.

Avoid a universal “retry the whole agent” handler. The provider guide documents that agent failover happens only before the SDK emits an event for the attempt. After streaming starts, automatic provider replay could repeat tool effects. Your recovery policy must respect that boundary.

For each test run, retain a business-run identifier alongside the conversation and AI request identifiers available at admission or completion. On an authorized diagnostic path, the documented request lookup is:

import { AiRequest } from '@db3.ai/app/ai';

// aiRequestId must already be authorized for this diagnostic viewer.
const request = await AiRequest.findByPk(aiRequestId);
console.log(request?.status, request?.inputTokens, request?.outputTokens);

The usage inspection guide describes saved status, inputs, responses, errors, duration, and usage, with a root request and child provider attempts. Link that evidence to your application's tool and business-operation records. A provider request tree is not a substitute for a mutation ledger.

If a run fails without visible evidence, check request persistence, diagnostic authorization, and whether your caller retained the relevant identifiers. Do not invent a new successful run to conceal the failed one.

Test diagnostic access itself. An ordinary user must not retrieve another user's prompt or tool result by changing an ID. The conversation documentation also calls for ownership checks and a retention policy for private records.

7. Gate deployment on outcomes you can observe

Finish with a release checklist tied to evidence, not an impressive demonstration:

Release check Required result
Argument validation Invalid calls reach neither policy dependencies nor Storage in the helper
Runtime validation Simulated malformed calls do not execute application reads
Ownership Cross-user, cross-workspace, and wrong-resource attempts disclose no private data
Current permissions Revocation is honored at execution time
Duplicate mutations Concurrent attempts produce the declared single-effect behavior
Uncertain external result An operator can reconcile before retrying
Diagnostics Failed runs remain investigable only by authorized viewers

Run the suite when schemas, tools, permission rules, provider adapters, or preview versions change. Include at least one worker-executed case if production uses queued agents: a request-path pass does not verify worker configuration or delayed permissions.

Assign an owner and recovery action to every failed case. An invalid argument should not enter a retry loop. A temporary read failure may receive bounded retries. An uncertain mutation should enter reconciliation or review instead of immediately repeating the action.

Start the rollout with the verified read-only capability. Add side effects only after their own authorization, approval, duplicate, and recovery tests pass. The completed outcome is an integration whose permitted behavior and failure handling are visible, not merely an agent that can answer.

Put one guarded tool through the checklist

Choose one tool that touches private application data. Implement its contract, run the helper tests, then exercise the real runtime and inspect a failed run. Use the db3.ai agent guide for integration details and the request inspection guide to build the diagnostic path. Keep mutations disabled until their additional checks pass.

Sources