An AI agent with tool access is only as safe as the tools it can call. A model that can read files, query records, or delete data will eventually be asked, by a user, a poisoned document, or a confused prompt, to do something you did not intend. The model does not enforce your security policy. Your code does. This guide shows developers how to build that enforcement layer in an afternoon. You will define per-tool permission scopes, require human approval for destructive actions, validate every argument before a tool runs, and record each call in an audit log.
Before you start
- Python 3.9 or later (the examples use
Path.is_relative_to, which was added in 3.9). - The official
anthropicPython SDK installed withpip install anthropic. - An API key exported as the
ANTHROPIC_API_KEYenvironment variable. The SDK reads it automatically. - A sandbox directory for the agent to work in. The examples use
/srv/agent-workspace. Create a dedicated directory and do not point the agent at your home directory or a repository root. - A working agent that already calls tools, or a willingness to build the small one shown below.
Step 1: Inventory your tools and assign a risk level
Before you write any code, list every tool the agent can call. For each one, answer three questions: what data can it read, what can it change, and can the change be undone? Then assign one of three risk levels:
- read: returns data and changes nothing. Scope it to the smallest dataset that serves the task.
- write: creates or modifies data in a recoverable way. Limit the targets and the size of each change.
- destructive: deletes data, sends messages outside your system, moves money, or changes permissions. Requires a human decision every time.
Most agent incidents come from tools that were added quickly and never classified. A tool named update_record that quietly supports a delete flag is a destructive tool, and your policy should treat it that way.
Step 2: Define the tool schemas
Create a file called tools.py. It holds the implementations and the JSON schemas that the model sees. Keep the schemas tight. Use required, explicit types, and additionalProperties: False so the model cannot slip in extra fields. The schema is the first layer of constraint, and the policy in the next step is the second.
// tools.py (schemas and implementations)
import json
from pathlib import Path
WORKSPACE = Path('/srv/agent-workspace')
def read_file(path):
return (WORKSPACE / path).read_text()[:20000]
def append_note(path, text):
target = WORKSPACE / path
with target.open('a') as f:
f.write(text + '\n')
return {'status': 'appended'}
def delete_record(record_id):
# Replace with your real data store call.
return {'status': 'deleted', 'record_id': record_id}
IMPLEMENTATIONS = {
'read_file': read_file,
'append_note': append_note,
'delete_record': delete_record,
}
TOOL_SCHEMAS = [
{
'name': 'read_file',
'description': 'Read a text file from the agent workspace.',
'input_schema': {
'type': 'object',
'properties': {'path': {'type': 'string'}},
'required': ['path'],
'additionalProperties': False,
},
},
{
'name': 'append_note',
'description': 'Append a short note to a file in the workspace.',
'input_schema': {
'type': 'object',
'properties': {
'path': {'type': 'string'},
'text': {'type': 'string'},
},
'required': ['path', 'text'],
'additionalProperties': False,
},
},
{
'name': 'delete_record',
'description': 'Permanently delete a record by its ID.',
'input_schema': {
'type': 'object',
'properties': {'record_id': {'type': 'string'}},
'required': ['record_id'],
'additionalProperties': False,
},
},
]
Step 3: Write per-tool permission scopes and validators
Next, create policy.py. Each tool gets a policy entry that declares its risk level, whether it needs approval, and a validator for every argument. Validators do the real work. They normalize input, reject anything outside the allowed shape, and resolve file paths so that traversal attempts like ../../etc/passwd fail.
# policy.py
import re
from dataclasses import dataclass, field
from pathlib import Path
WORKSPACE = Path('/srv/agent-workspace').resolve()
RECORD_ID = re.compile(r'[A-Za-z0-9_-]{1,64}')
def safe_path(value):
if not isinstance(value, str):
raise ValueError('path must be a string')
resolved = (WORKSPACE / value).resolve()
if not resolved.is_relative_to(WORKSPACE):
raise ValueError('path escapes the workspace')
return str(resolved.relative_to(WORKSPACE))
def bounded_text(max_len):
def check(value):
if not isinstance(value, str):
raise ValueError('text must be a string')
if len(value) > max_len:
raise ValueError(f'text exceeds {max_len} characters')
return value
return check
def record_id(value):
if not isinstance(value, str) or not RECORD_ID.fullmatch(value):
raise ValueError('invalid record id')
return value
@dataclass(frozen=True)
class Policy:
name: str
risk: str # 'read', 'write', or 'destructive'
requires_approval: bool
validators: dict = field(default_factory=dict)
def validate(self, args):
unexpected = set(args) - set(self.validators)
if unexpected:
raise ValueError(f'unexpected arguments: {sorted(unexpected)}')
cleaned = {}
for key, check in self.validators.items():
if key not in args:
raise ValueError(f'missing argument: {key}')
cleaned[key] = check(args[key])
return cleaned
POLICIES = {
'read_file': Policy('read_file', 'read', False,
{'path': safe_path}),
'append_note': Policy('append_note', 'write', False,
{'path': safe_path, 'text': bounded_text(2000)}),
'delete_record': Policy('delete_record', 'destructive', True,
{'record_id': record_id}),
}
Notice that the destructive tool requires approval and the read tool does not. The policy is where you encode that decision, in one place, where reviewers can see it.
Step 4: Add a human approval gate for destructive actions
An approval gate is a function the guard calls before running a tool that requires it. The model never sees or controls the gate. For a local prototype, a console prompt is enough. In production, route the request to a review queue or chat channel, show the tool name and the exact arguments, and wait for a decision from an authenticated human. If no decision arrives within a timeout, deny the action.
Two rules matter here. First, approve the exact arguments the agent proposed, not a summary of them. Second, never let the agent decide that an approval is unnecessary. The policy table decides, not the prompt.
Step 5: Wrap every tool call in a guard with audit logging
Create guard.py. This is the single function that all tool calls pass through. It checks that the tool exists, validates the arguments, applies the approval gate, runs the tool, and writes a structured audit record. Denied calls are logged too, because repeated denials are a signal worth investigating.
# guard.py
import json
import logging
import time
import uuid
from policy import POLICIES
from tools import IMPLEMENTATIONS
audit = logging.getLogger('agent.audit')
audit.setLevel(logging.INFO)
audit.addHandler(logging.FileHandler('agent_audit.jsonl'))
def cli_approver(name, args):
print(f'Agent requests {name} with arguments: {args}')
return input('Approve? [y/N] ').strip().lower() == 'y'
def _record(call_id, name, args, outcome, reason=None):
audit.info(json.dumps({
'ts': time.time(),
'call_id': call_id,
'tool': name,
'args': args,
'outcome': outcome,
'reason': reason,
}))
def execute_tool(name, args, approver=cli_approver):
call_id = str(uuid.uuid4())
policy = POLICIES.get(name)
if policy is None:
_record(call_id, name, args, 'denied', 'unknown tool')
return {'ok': False, 'error': 'tool not permitted'}
try:
cleaned = policy.validate(args)
except ValueError as exc:
_record(call_id, name, args, 'denied', f'validation: {exc}')
return {'ok': False, 'error': f'invalid arguments: {exc}'}
if policy.requires_approval and not approver(name, cleaned):
_record(call_id, name, cleaned, 'denied', 'approval not granted')
return {'ok': False, 'error': 'a human reviewer declined this action'}
try:
result = IMPLEMENTATIONS[name](**cleaned)
except Exception:
_record(call_id, name, cleaned, 'error', 'tool raised an exception')
return {'ok': False, 'error': 'tool failed'}
_record(call_id, name, cleaned, 'ok')
return {'ok': True, 'result': result}
Notice that the error returned to the model is generic. Stack traces and internal paths stay in your logs, not in the conversation where an attacker could read them.
Step 6: Connect the guard to the Anthropic API
Create agent.py. The loop sends the conversation to a Claude model with your tool definitions. When the model returns a tool_use block, the loop passes the call through the guard and returns the result as a tool_result. Setting is_error on denied calls tells the model the action failed, so it can explain the situation or try a different approach.
# agent.py
import json
import anthropic
from guard import execute_tool, cli_approver
from tools import TOOL_SCHEMAS
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
MODEL = 'claude-sonnet-5-5'
MAX_STEPS = 10
def run_agent(user_prompt):
messages = [{'role': 'user', 'content': user_prompt}]
for _ in range(MAX_STEPS):
response = client.messages.create(
model=MODEL,
max_tokens=2048,
tools=TOOL_SCHEMAS,
messages=messages,
)
messages.append({'role': 'assistant', 'content': response.content})
if response.stop_reason != 'tool_use':
return ''.join(b.text for b in response.content if b.type == 'text')
results = []
for block in response.content:
if block.type == 'tool_use':
outcome = execute_tool(block.name, dict(block.input), cli_approver)
results.append({
'type': 'tool_result',
'tool_use_id': block.id,
'content': json.dumps(outcome),
'is_error': not outcome['ok'],
})
messages.append({'role': 'user', 'content': results})
raise RuntimeError('step limit reached')
if __name__ == '__main__':
print(run_agent('Read notes/todo.txt and add a summary line to notes/summary.txt.'))
The step limit matters. It stops a confused or manipulated agent from looping through tool calls indefinitely. If you enable extended reasoning on Claude 4.6 or later models, use adaptive thinking with thinking={'type': 'adaptive'}. The fixed budget_tokens setting is deprecated on these models, so do not rely on it.
Verify it worked
Testing a permission layer means trying to break it. Run these checks before you trust the setup.
- Traversal is blocked. Add a test file and run this check. It should return
ok: False.
# test_guard.py
from guard import execute_tool
def test_traversal_denied():
out = execute_tool('read_file', {'path': '../../etc/passwd'}, lambda n, a: True)
assert out['ok'] is False
def test_extra_arguments_denied():
out = execute_tool('read_file', {'path': 'a.txt', 'mode': 'w'}, lambda n, a: True)
assert out['ok'] is False
def test_destructive_needs_approval():
out = execute_tool('delete_record', {'record_id': 'abc123'}, lambda n, a: False)
assert out['ok'] is False
Run them with python -m pytest test_guard.py.
- Approval is enforced. Run the agent, ask it to delete a record, and decline at the prompt. The model should report that the action was declined, and no deletion should occur.
- The audit log is complete. Check the most recent entries. Each call, including denied ones, should have a call ID, tool name, arguments, and outcome.
tail -n 5 agent_audit.jsonl | python3 -c 'import sys, json
for line in sys.stdin:
print(json.loads(line))'
- The workspace is unchanged outside its boundary. Confirm that the agent cannot create files outside
/srv/agent-workspace. A permission layer you have not tested is an assumption, not a control.
Common mistakes
- Relying on the system prompt for security. Instructions like “never delete records” are guidance, not enforcement. Enforce limits in code, where the model cannot override them.
- Validating strings but not paths. A path that looks harmless can resolve outside your workspace through
..segments or symbolic links. Always resolve and check containment after resolution, assafe_pathdoes. - Approving summaries instead of arguments. If the reviewer sees “clean up old records” but the arguments delete a whole table, the approval is meaningless. Show the exact arguments.
- Treating read tools as harmless. Reads can leak secrets, customer data, or credentials into the conversation and from there into logs or third-party systems. Scope reads as tightly as writes.
- Logging secrets. The audit log records arguments, which can contain tokens or personal data. Redact sensitive fields before writing, and restrict who can read the log file.
- Returning raw exceptions to the model. Stack traces reveal paths, configuration, and internal names. Return generic errors to the model and keep details in your own logs.
- Forgetting the approval timeout. A review queue that never times out can leave an agent stuck or, worse, approved by a stale decision. Deny by default when no answer arrives.
- Granting tools the task does not need. Start each agent with the fewest tools possible and add more only when a specific task requires them.
Takeaway
Least privilege for AI agents is an engineering task you can finish in an afternoon. Classify every tool by risk, declare its scope in one policy table, validate each argument before it runs, require a human decision for anything destructive, and log every call, including the ones you refused. The model will still make mistakes, but the mistakes will be bounded by code you can read, test, and audit.
