Interact with APIs and external tools following best practices to avoid unintended side effects.
Using External Tools Safely and Correctly
Agents integrate with external tools, APIs, and services to expand their capabilities. This module defines safety protocols for tool usage, error handling, and integration best practices.
---
1. Tool Safety Classification
Risk Level
Tool Type
Examples
Pre-Use Requirements
Low
Read-only queries
Database SELECT, API GET, file read
Verify endpoint
Medium
State-changing, reversible
Create draft, update preferences
Confirm action
High
State-changing, hard to reverse
Send email, post to social media
Explicit user approval
Critical
Irreversible, high impact
Delete data, financial transactions
Enhanced approval protocol
Restricted
Security-sensitive
Admin operations, credential changes
Multi-factor confirmation
2. Pre-Execution Checklist
Before calling any external tool:
[ ] Is this the correct tool for the task?
[ ] Are all parameters validated and sanitized?
[ ] Is the user authorized for this operation?
[ ] Has the user approved this action (if required by risk level)?
[ ] Is the endpoint/service currently available?
[ ] Is there a fallback if the call fails?
[ ] Will the call produce any side effects beyond the intended result?
3. Input Validation Protocol
Input Type
Validation Rules
Rejection Criteria
URLs
Parse and validate format, check allowed domains
Malformed, disallowed domain, injection attempts
File paths
Normalize, check for traversal attacks
"../", absolute paths outside sandbox
SQL/Query parameters
Parameterize, escape special characters
Raw SQL injection patterns
User-provided code
Sandbox, never execute directly in production
Malicious patterns detected
API keys/tokens
Validate format, never log
Exposed in logs or responses
JSON payloads
Schema validation, size limits
Exceeds size, invalid schema
4. API Call Best Practices
Prepare API call
→ Step 1: Validate all parameters
→ Step 2: Set appropriate timeout (default: 30s)
→ Step 3: Include proper authentication headers
→ Step 4: Execute call
→ Step 5: Check response status code
→ 2xx: Parse response, validate structure
→ 4xx: Handle client error (log, inform user)
→ 5xx: Retry with backoff (max 3 attempts)
→ Timeout: Retry once, then report failure
→ Step 6: Validate response data before using
5. Rate Limiting Awareness
Scenario
Detection
Response
Approaching rate limit
Track request count per window
Slow down, batch requests
Rate limit hit (429)
HTTP 429 response
Wait for retry-after header, inform user
No rate limit info
Unknown limits
Start conservative, increase gradually
Shared rate limit
Multiple tools share quota
Coordinate across tools
6. Error Handling Matrix
Error Type
Example
Agent Action
Authentication failure
401/403
Check credentials, do not retry with same creds
Not found
404
Verify resource ID, inform user
Validation error
400/422
Fix input, retry if correctable
Server error
500/502/503
Retry with backoff (max 3x), then report
Timeout
No response
Retry once with longer timeout, then report
Network failure
Connection refused
Check connectivity, try alternate endpoint if available
Unexpected response
Unknown format
Log for debugging, inform user of failure
7. Tool Chain Safety
When multiple tools are chained together:
Tool chain: A → B → C
→ Execute A
→ Validate A's output before passing to B
→ Output valid? → Proceed to B
→ Output invalid? → Stop chain, report at which step failure occurred
→ Execute B with validated input from A
→ Validate B's output before passing to C
→ Execute C
→ Report final result with chain summary
Rules:
Never pass unvalidated output from one tool to another
If any step fails, do not continue the chain
Report exactly which step failed and why
Offer to retry from the failed step, not from scratch
8. Sandbox and Isolation
Principle
Implementation
Least privilege
Request minimum permissions needed
Isolation
Each tool call should not affect others
No side channels
Don't use tool A to bypass tool B's restrictions
Clean state
Don't carry mutable state between unrelated tool calls
Resource limits
Enforce max execution time, memory, and output size
9. Tool Discovery and Selection
When multiple tools can accomplish a task:
Selection Criteria
Priority
Lowest risk level
Highest
Best reliability track record
High
Fastest execution
Medium
Most detailed output
Medium
Newest version
Low (stability over novelty)
10. Edge Cases
Tool returns partial results:
Use what's available, clearly mark as partial
Attempt to fetch remaining data
Inform user of completeness level
Tool changes behavior after update:
Detect unexpected response format changes
Fall back to safe defaults
Log the discrepancy for review
User requests tool use for unintended purpose:
Evaluate if the usage is safe and within scope
If risky, explain the concern and suggest proper alternatives
Never use tools in ways that bypass security controls
Related Articles
Tool Usage Best Practices for AI Agents — Guidelines for when and how AI agents should use external tools, including selection criteria, result interpretation, and knowing when tools add genuine value.
Structured Response Design for Maximum Clarity — Best practices for AI agents to structure responses with clarity, appropriate detail, and actionable formatting that users and other agents can immediately apply.