Tool Calls Are API Contracts: Nine Snippet Patterns for AI Agents That Don't Wreck Prod
Photo: Marxav, CC BY-SA 4.0, via Wikimedia Commons
AI agents have graduated from autocomplete with a chat window to systems that book meetings, open pull requests, and poke production APIs. The snippet doing the poking is usually copied from a vendor demo, a blog post, or a teammate's gist. That is the 2026 version of copy-paste programming: the code runs once, so we ship it.
The trouble is that a tool-calling snippet is not a utility function. It is an API contract, a security boundary, and a retry policy wearing a five-line helper costume. If you are wiring agents into real systems, these nine patterns are worth adapting—not pasting—before your next deploy.
1. Treat the schema as the contract
A loose schema is an invitation. If your tool accepts any or leaves additionalProperties open, the model will eventually invent a field, and your handler will eventually ignore it. Define required fields, constrain enums, set max lengths, and reject unknown keys at the edge.
const createIssue = {
name: 'create_issue',
parameters: {
type: 'object',
additionalProperties: false,
required: ['repo', 'title', 'body'],
properties: {
repo: { type: 'string', pattern: '^[a-z0-9-]+/[a-z0-9-]+$' },
title: { type: 'string', maxLength: 120 },
body: { type: 'string', maxLength: 8000 },
},
},
};
2. Scope credentials to the tool, not the agent
An agent with one broad token can do everything the token allows. That is a blast radius, not a design. Mint short-lived credentials per tool or per task, and keep read tools on read-only scopes. If the snippet needs a write scope, make that explicit in the tool name and in the review.
3. Make writes idempotent by default
Agents retry. Networks flap. Users double-click. If create_issue runs twice, you should get one issue, not two. Generate an idempotency key from the tool call ID and pass it through to the downstream API. Store the key with the result for at least the retry window.
key = f'{tool_call_id}:create_issue'
response = client.post('/issues', json=payload, headers={'Idempotency-Key': key})
4. Validate at the boundary, not inside the tool
Schema validation catches shape; runtime validation catches intent. Check that the repo exists, the user has access, and the payload is within budget before your handler touches anything. Reject oversized bodies early. A 2 MB issue description is not a feature request; it is a denial-of-service attempt with good manners.
5. Put rate limits and backoff in the snippet
Most copied tool snippets assume the downstream API is infinite and instant. It is not. Respect Retry-After, cap retries, and add jitter so your agent fleet does not synchronize into a thundering herd. If the tool cannot finish within its budget, return a clear partial result instead of hanging.
async function withRetry(fn, attempts = 3) {
for (let i = 0; i < attempts; i++) {
try { return await fn(); } catch (err) {
if (i === attempts - 1 || !isRetryable(err)) throw err;
await sleep(2 ** i * 250 + Math.random() * 100);
}
}
}
6. Separate read tools from write tools
Name them so a human can see the risk: search_issues, get_issue, create_issue, close_issue. Give read tools their own credential path and their own rate budget. This makes policy decisions obvious and keeps a chatty agent from exhausting the same quota your write path needs.
7. Log intent and result, not just errors
When an agent calls a tool, log the tool name, a redacted argument hash, the decision context, latency, and outcome. Do not log secrets or full payloads. The goal is to answer 'why did the agent do that?' without turning your observability bill into a second mortgage.
8. Add timeouts and a circuit breaker
Every tool call needs a deadline. Wrap network calls with AbortController or your language's equivalent, and trip a circuit breaker after repeated failures. An agent that waits forever is worse than an agent that fails fast, because it consumes budget while doing nothing.
9. Keep a human in the loop for irreversible actions
Deleting a repo, rotating a key, sending an external email: these deserve a confirmation step. Use a short-lived confirmation token tied to the exact tool call and arguments. The model can propose; a human should approve the irreversible part.
None of these patterns are exotic. They are the boring guardrails we already expect from any service that touches production. The difference is that tool-calling snippets are being copied at a rate that outpaces review. Treat them like API contracts, give them tests, and make the safe path the easy path. Your agent can still be clever. It just should not be clever with your production credentials.