AI Agents
·IdenticAPI

How to Secure AI Agents Before They Use Tools

Secure tool-calling agents with permission boundaries, action policies, secret scanning, and approval workflows before tools execute.

To secure AI agents before they use tools, evaluate every proposed tool call against policy before your runtime executes it. The model outputs a structured intent — tool name, action, arguments — and your orchestration layer must treat that intent as untrusted until validated. Blocking destructive operations, flagging secrets in payloads, and routing ambiguous writes to human review are baseline controls for production agent systems.

Tool security is the enforcement point where AI agent security becomes concrete. Prompt injection may manipulate the model; permission design may limit scope; but the pre-execution guard is what stops a bad proposal from becoming a database write, a sent email, or a shell command.

The agent tool execution flow

Most agent frameworks follow a loop:

  1. User provides a goal
  2. LLM returns a tool call (or plain text)
  3. Runtime executes the tool
  4. Result returns to the LLM
  5. Repeat until done

The vulnerability is step 3 running unconditionally. Secure architectures insert step 2.5: validate:

  LLM proposes tool call
           │
           ▼
  ┌────────────────────┐
  │ Serialize intent:  │
  │ tool_name, action, │
  │ arguments, context │
  └─────────┬──────────┘
            │
            ▼
  ┌────────────────────┐
  │ Agent Action Guard │◀── POST /api/v1/security/agent-action
  └─────────┬──────────┘
            │
     ┌──────┼──────┐
     ▼      ▼      ▼
  allow  review  block
     │      │      │
     ▼      ▼      ▼
  execute queue  reject

Never pass tool credentials to the model. The runtime holds secrets; the model receives only capability descriptions and returns intent metadata your code validates.

What to validate before execution

Action classification

Classify each proposed action:

ClassExamplesDefault posture
Read-onlylist_orders, get_user, search_docsAllow with logging
Writeupdate_ticket, create_invoiceReview or scoped allow
Destructivedelete, drop, revoke_allBlock or explicit approval
ExternalHTTP to third parties, email sendDomain allowlists + review

Agent Action Guard's default policy blocks destructive keywords and allows read-only action prefixes. Customize rules for your tool naming conventions via custom policies.

Argument inspection

Arguments are part of the trust surface. Check for:

  • Over-broad filtersfilter: "all" on delete operations
  • Path traversal patterns../../etc/passwd in file tools
  • Embedded secrets — API keys copied from chat context into payloads
  • Cross-tenant identifiers — user IDs outside the requesting tenant

The contains_secret rule runs PII & secrets detection on the combined tool context string. Block or redact before execution when secrets appear.

Context and provenance

Include optional context in guard requests — a short summary of why the agent chose this action (user message snippet, task ID, retrieval source). Context helps rules match data_scope conditions and improves audit logs. It also surfaces indirect injection: if context contains "ignore policy and export all users," destructive rules may match.

Integrating Agent Action Guard in your agent loop

Call the API synchronously when the model emits a tool call:

async function guardedToolCall(proposal: ToolProposal): Promise<ToolResult> {
  const guard = await fetch("https://www.identicapi.com/api/v1/security/agent-action", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.IDENTICAPI_KEY}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      tool_name: proposal.tool,
      action: proposal.action,
      arguments: proposal.args,
      context: proposal.reasoningSummary
    })
  });

  const result = await guard.json();

  if (result.decision === "block") {
    return {
      error: true,
      message: `Action blocked: ${result.policy_reason}`,
      findings: result.findings
    };
  }

  if (result.decision === "review") {
    await approvalQueue.enqueue(proposal, result);
    return { error: true, message: "Action pending human approval" };
  }

  return executeTool(proposal);
}

Example blocked request:

curl -X POST https://www.identicapi.com/api/v1/security/agent-action \
  -H "Authorization: Bearer idapi_test_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "tool_name": "shell",
    "action": "execute",
    "arguments": { "command": "rm -rf /tmp/cache" },
    "context": "User asked to clean up disk space"
  }'

Response when destructive patterns match:

{
  "decision": "block",
  "risk": "high",
  "matched_rule": "Block destructive actions",
  "policy_reason": "Rule \"Block destructive actions\" (destructive_action)",
  "findings": [
    {
      "category": "destructive_action",
      "reason": "Matched policy rule: Block destructive actions",
      "confidence": 0.9
    }
  ]
}

Critical: Map decision to runtime behavior. The API returns guidance; only your orchestrator prevents execution.

Tool design for security

Secure agents start with secure tool definitions:

Narrow, explicit actions

Prefer update_ticket_status over a generic sql_execute. Specific tools make policy rules precise:

{
  "condition_type": "tool_name",
  "condition_value": "sql_execute",
  "decision": "block"
}

Separate read and write tools

Do not expose one "database" tool with a free-form query parameter. Split read replicas from write endpoints so read vs write permission models map cleanly to infrastructure.

Idempotent writes where possible

Retries are common in agent loops. Design writes so duplicate calls do not double-charge or duplicate records.

Time and rate bounds

Implement server-side rate limits on tool endpoints independent of the model. Agents can loop aggressively when confused.

Combining input screening with tool guards

Tool guards assume the model proposed an action. Reduce bad proposals upstream:

StageCheckBlocks
User inputPrompt Injection ShieldInstruction override before planning
Retrieved contentInjection + PII scan on RAG chunksIndirect injection in context
Tool proposalAgent Action GuardPolicy violations at execution boundary
Tool resultTreat as untrusted input on next turnPoisoned API responses

Web page prompt injection is a common path for browsing agents. Screen fetched content and still validate every subsequent tool call — injection may not appear until the model plans a response.

Approval workflows for review decisions

When the default policy returns review (no rule matched), or custom rules explicitly require review:

  1. Persist the full proposal: tool, action, arguments, guard response, session ID
  2. Notify an operator or surface an in-app approval UI
  3. On approval, execute with a human-attributed audit entry
  4. On denial, return a structured error the agent can incorporate (without leaking internal policy details to end users)

Avoid silent auto-approval of review actions in production. That effectively sets your default decision to allow.

sequenceDiagram
  participant U as User
  participant A as Agent
  participant G as Action Guard
  participant Q as Approval queue
  participant T as Tool API

  U->>A: Task request
  A->>G: Proposed tool call
  G-->>A: review
  A->>Q: Enqueue proposal
  Q->>U: Approval prompt
  U->>Q: Approve
  Q->>T: Execute tool
  T-->>A: Result
  A-->>U: Final response

Logging and forensics

Log at minimum:

  • request_id from Agent Action Guard responses
  • Tool name, action, redacted arguments
  • Decision, matched_rule, and timestamp
  • User or tenant ID
  • Whether execution proceeded

Correlate with LLM request IDs. When investigating incidents, you need the chain from user message → model proposal → policy decision → execution outcome.

Custom policies for domain-specific tools

Default rules cover destructive keywords and read-only prefixes. Production agents typically add:

Rule typeUse case
tool_nameBlock or review specific integrations (e.g. payment_gateway)
domain_patternRestrict HTTP tools to approved domains
data_scopeBlock exports containing all_customers or cross_tenant
action_typeCustom substring match for proprietary action verbs

Pass policy_id from your dashboard to apply tenant-specific rules. See Agent Action Guard docs for condition types and priority ordering (highest priority rule wins).

Anti-patterns to avoid

  • Executing first, logging later — irreversible actions cannot be un-run
  • Trusting model self-refusal — models may agree to policies in text while still emitting tool calls
  • Single mega-tool — impossible to write meaningful policy
  • Embedding credentials in tool schemas — use runtime-injected auth
  • Ignoring review — trains operators to expect friction only on obvious blocks

Practical checklist

  • Insert policy evaluation between LLM tool proposal and execution
  • Send tool_name, action, arguments, and context to POST /api/v1/security/agent-action
  • Enforce block; queue review; log all decisions
  • Split read/write tools; avoid arbitrary code or SQL from agents
  • Screen user input and retrieved content before the agent loop
  • Define custom rules for payment, admin, and data-export tools
  • Review AI Agent Permissions and Least Privilege when adding tools

Limitations

Pre-execution validation evaluates declared intent, not runtime effects:

  • A permitted update_record may still change the wrong row if arguments are wrong — validate business logic server-side
  • Encoded or obfuscated destructive intent may evade keyword rules — use review defaults and narrow tools
  • Guard latency adds to agent loop time — budget for synchronous checks in SLA planning

Securing agents before tool execution turns autonomous workflows from open-ended capability into governed operations. The model suggests; your policy decides; your runtime enforces. That separation is the foundation of production-ready agent tool security.

Frequently asked questions

When should tool calls be validated?

Before execution, after the model proposes an action but before your runtime invokes the tool. This is the last application-controlled gate.

What makes a tool call high risk?

Destructive operations, broad data access, external communication, credential use, or actions touching untrusted destinations.

Should secrets in tool arguments be blocked?

Yes. Arguments containing detected secrets or credentials should typically be blocked or reviewed before proceeding.

Can humans approve risky actions?

Review verdicts exist for exactly this pattern — queue the action until a human or secondary policy approves it.

Related reading