Best Practices
Recommended patterns for building robust agents.
Agent Design
1. Clear Purpose
{
"name": "code-reviewer",
"description": "Automated code review focusing on security and style",
"tags": ["security", "code-review", "linting"]
}
2. Focused System Prompt
You are a code review specialist.
Focus on:
1. Security vulnerabilities
2. Code style consistency
3. Best practices
Do not:
- Rewrite working code unnecessarily
- Focus on subjective preferences
3. Appropriate Permission Mode
{
"settings": {
"permissionMode": "acceptEdits", // Auto-approve edits for speed
"allowedTools": ["Read", "Grep", "Edit"] // Limit to safe tools
}
}
Hook Patterns
1. Fail Safely
export async function PreToolUse(input: PreToolUseHookInput) {
try {
// Your logic
return { decision: 'approve' };
} catch (error) {
console.error('Hook error:', error);
// Fail open: allow operation
return { decision: 'approve' };
}
}
2. Keep Hooks Fast
// ✓ Good: Fast local check
export async function PreToolUse(input: PreToolUseHookInput) {
const blacklist = ['rm -rf', 'dd if='];
const cmd = input.tool_input?.command || '';
return {
decision: blacklist.some(b => cmd.includes(b)) ? 'deny' : 'approve'
};
}
// ✗ Bad: Slow external call
export async function PreToolUse(input: PreToolUseHookInput) {
const response = await fetch('https://api.example.com/check');
// Adds latency to every tool call!
}
3. Log Appropriately
export async function PreToolUse(input: PreToolUseHookInput) {
// ✓ Structured logging
console.log('[PreToolUse]', {
tool: input.tool_name,
timestamp: Date.now()
});
// ✗ Don't log sensitive data
console.log('[PreToolUse]', input.tool_input); // May contain secrets!
}
Configuration
1. Set maxTurns
{
"maxTurns": 50 // Prevent infinite loops
}
2. Use Tool Allowlists
{
"settings": {
"allowedTools": ["Read", "Grep", "Edit"] // Security-sensitive agents
}
}
3. Provide Fallback Model
{
"model": "claude-sonnet-4.5-20250929",
"fallbackModel": "claude-3-5-sonnet-20241022" // Availability
}
Security
- Validate inputs: Check tool parameters in hooks
- Limit permissions: Use restrictive permission modes
- Audit operations: Log all actions with PostToolUse
- Block dangerous commands: Implement PreToolUse guards
- Don't commit secrets: Keep .env files in .gitignore
Performance
- Keep hooks fast (< 1s typically)
- Limit maxTurns to prevent runaway execution
- Use efficient tools: Prefer Read over Bash cat
- Cache expensive operations in hooks
- Minimize external API calls in hot paths
Documentation
- Comprehensive README: Explain agent purpose and usage
- Document hooks: Explain custom behavior
- Provide examples: Show real-world usage
- Keep updated: Sync docs with code changes
Version Control
# .gitignore
node_modules/
.env
*.log
dist/ # Optional: can commit for convenience
Commit:
- Source code
- Configuration
- Documentation
- Tests
Don't commit:
- Dependencies
- Build artifacts (optional)
- Secrets
- Logs