An AI agent becomes a security concern when it can do more than generate text. The moment it can read private records, send email, update a database, run code, or call external APIs, a model mistake can become a real system action.
Securing an agent requires more than a clever system prompt. Treat the model as an untrusted decision-making component and enforce security in the application, API, database, and execution environment.
1. Prompt injection is not just a bad prompt
Prompt injection occurs when attacker-controlled content attempts to change how an AI system behaves. The malicious instruction may arrive directly from a user or indirectly through a webpage, uploaded file, email, support ticket, or retrieved document.
For example, an agent asked to summarize a webpage might encounter text telling it to ignore prior instructions and reveal private information. The text should be treated as data to analyze, not as an instruction with authority. However, models do not provide a perfect security boundary between trusted instructions and untrusted content.
2. Apply least privilege to every tool
Give an agent only the permissions needed for its specific task. A support agent that drafts replies does not need permission to delete users. A reporting agent should use read-only views rather than a database administrator credential.
- Separate read operations from write operations.
- Use server-side authorization for every sensitive action.
- Check the current user's identity and role on the server, not only in the prompt.
- Validate IDs, amounts, recipients, and other tool arguments before execution.
- Never place service-role keys or privileged secrets in browser code or model-visible context.
3. Add human approval for consequential actions
Require a person to approve actions that send external messages, change financial information, issue refunds, modify permissions, delete records, or publish content. The approval screen should show the exact action and its target, not just a vague “Approve agent?” button.
Approval should be enforced by the application. Do not rely on the agent to remember to ask permission.
4. Run tools in isolated environments
Code execution and browser automation should use a sandbox with limited filesystem access, restricted network access, resource limits, and no production secrets. Use temporary credentials where possible and destroy the environment after the task.
For coding agents, use a separate branch or disposable workspace. Review changes before merging, and keep deployment credentials outside the agent's normal environment.
5. Protect data boundaries
Do not send an entire customer database to a model when the task needs only one record. Minimize the fields returned by tools, redact sensitive values, and define retention rules for prompts, outputs, logs, and uploaded files.
When using retrieval-augmented generation (RAG), enforce document-level permissions before content reaches the model. A search result is not automatically safe to disclose just because it is relevant.
6. Add limits, monitoring, and a kill switch
- Limit tool calls, execution time, token use, and spending per task.
- Set maximum retries and detect repeated or circular actions.
- Log the initiating user, agent, tool, arguments, outcome, and approval decision.
- Alert on unusual access patterns and repeated denied actions.
- Provide a way to revoke tokens and stop running jobs quickly.
7. Test the agent like a security-sensitive application
Build tests for direct and indirect prompt injection, unauthorized record access, malformed tool arguments, privilege escalation, data leakage, tool failure, and excessive loops. Test both allowed and denied behavior. A security test should prove that a student cannot access another student's grades, for example—not merely prove that the login screen works.
The model may recommend an action. Your trusted application must decide whether that action is authorized, validate it, and execute it safely.
A short deployment checklist
- Inventory every tool and the data it can access.
- Use separate credentials for each agent and environment.
- Enforce authorization in server-side code and database policies.
- Require confirmation for high-impact actions.
- Sandbox code execution and restrict network access.
- Red-team prompt injection and cross-user data access.
- Monitor usage, failures, and unusual actions.
- Document how to revoke access and stop the agent.
OWASP's GenAI security work identifies risks such as prompt injection, sensitive information disclosure, improper output handling, and excessive agency. These are useful categories for building a threat model, but a checklist is only the start: each agent needs tests that reflect its real tools and data.
Build a simple threat model before deployment
Write down what the agent can read, what it can change, which tools it can call, and who could influence the information it receives. Include indirect prompt injection: an attacker may place instructions inside an email, webpage, support ticket, PDF, or code comment that the agent later reads. Treat retrieved content as untrusted data, not as authority to change the agent's rules.
For each tool, identify the worst plausible outcome. A read-only search tool may expose confidential records; an email tool may send sensitive information externally; a database update tool may corrupt customer data. Reduce the possible damage before relying on a prompt to prevent it.
Design safer tools, not just safer prompts
- Expose narrow actions such as
get_order_status(order_id)instead of unrestricted database access. - Check identity and authorization in the application layer on every call.
- Validate tool arguments against strict schemas and reject unexpected fields.
- Separate read permissions from write permissions and staging from production.
- Require confirmation for external messages, payments, deletion, permission changes, and other consequential actions.
- Log tool calls and outcomes while excluding passwords, secrets, and unnecessary personal information.
Do not rely on the model to decide whether a caller is authorized. The application and data layer must enforce access rules even if the model is manipulated or makes a mistake.
Test realistic attack paths
Test documents containing instructions that conflict with the task, requests to reveal hidden system information, attempts to access another user's records, malicious links, oversized inputs, repeated tool calls, and tool failures. Verify that the agent refuses unauthorized actions, does not leak secrets in its response, and cannot bypass server-side permissions.
Repeat tests whenever you change the model, instructions, tools, retrieval sources, or permission model. A passing test suite is evidence about the scenarios tested, not proof that every attack is impossible.
AI agent security: common questions
Can prompt injection be completely prevented?
No single prompt or filter guarantees prevention. Reduce risk with strict tool permissions, separation of trusted instructions from untrusted content, server-side authorization, human approval, monitoring, and ongoing adversarial testing.
Should an AI agent have direct database access?
Usually not unrestricted access. Prefer narrowly scoped server-side functions that validate identity, ownership, input, and permitted operations. Keep privileged service credentials out of model-visible prompts and browser code.
Is sandboxing enough to secure an AI agent?
No. Sandboxing limits what code execution can reach, but it does not by itself prevent data disclosure through an allowed tool, unsafe messages, excessive permissions, or application-level authorization flaws. Use multiple independent controls.
Related technical guides
Start with how AI agents work for architecture context, then read our guide to safely using AI coding agents for repository and terminal access patterns.