Safe AI agent tool calling starts before the model selects a function. This guide shows how to define tools, validate arguments, enforce permissions, handle failures, and review operational signals so developers can build more reliable LLM applications and know when an agent needs human intervention.
Overview
AI agent tool calling allows a language model to request an action from an application, such as searching a knowledge base, creating a ticket, checking an order, or updating a record. The model does not need direct access to the underlying service. Instead, your application receives a structured tool request, applies its own controls, executes the permitted operation, and returns a result to the model.
This separation is the foundation of safer LLM tool use. A model can propose an action, but your application should remain responsible for authentication, authorisation, validation, rate limits, logging, and side effects. Treat every tool call as an untrusted request that must pass through normal application controls.
Function calling terminology differs between model providers and frameworks. Some systems describe tools as functions, actions, or capabilities. The implementation details may change, but the design questions remain consistent:
- What is this tool allowed to do?
- Which arguments are valid?
- Which actions require user approval?
- What happens if the service is slow, unavailable, or returns an unexpected result?
- How can the team investigate a failed or suspicious run?
A useful agent architecture has four distinct stages: the model proposes a call, the application validates it, a policy layer decides whether it may proceed, and a controlled executor performs the action. Keeping these stages separate makes the system easier to test and review.
What to track
1. Tool definitions and schemas
A tool definition should describe one narrow capability. Avoid exposing a broad operation such as run_any_api_request when several specific tools would be safer. Narrow tools make permissions, testing, and audit logs easier to understand.
At minimum, define the tool name, purpose, input fields, data types, required fields, permitted values, and any important limits. A practical tool-definition template might look like this:
{
"name": "create_support_ticket",
"description": "Create a draft support ticket for user review.",
"parameters": {
"type": "object",
"properties": {
"subject": { "type": "string", "maxLength": 120 },
"body": { "type": "string", "maxLength": 5000 },
"priority": { "type": "string", "enum": ["low", "normal", "high"] }
},
"required": ["subject", "body"]
}
}
The exact schema format depends on your framework. The important principle is that the description should explain the tool's boundary, not encourage creative interpretation. If a tool creates a draft rather than sending a message, state that clearly.
2. Argument validation
Schema validation is necessary but may not be sufficient. Validate types, lengths, formats, ranges, and allowed values before execution. Then apply business rules that require application context. For example, a valid account identifier may still be outside the authenticated user's permitted scope.
Do not rely on the model to enforce restrictions stated only in a prompt. Validate again in server-side code. Reject unknown fields where practical, normalise values consistently, and avoid passing model-generated strings directly into shell commands, database queries, file paths, or external URLs.
3. Permissions and approval gates
Classify tools by risk. Read-only actions, such as retrieving an internal document, may require authentication and access checks but no additional approval. Actions that create, modify, delete, publish, send, purchase, or grant access deserve stricter controls.
Use least-privilege credentials for each tool. A ticket lookup should not use credentials that can delete tickets. An agent should not receive a permanent administrator token merely because one tool needs elevated access. Keep secrets outside the model context and have the executor obtain credentials from the appropriate server-side mechanism.
An approval gate should show the user what will happen, with enough detail to make an informed decision. Include the target, key arguments, estimated impact, and whether the action is reversible. For high-impact tools, require explicit confirmation immediately before execution rather than relying on an earlier general instruction.
4. Timeouts, retries, and idempotency
Every external call needs a timeout. Without one, a stalled dependency can hold an agent run open and consume resources. Set limits appropriate to the operation, record when a timeout occurs, and return a controlled status to the orchestration layer.
Retries should be selective. A temporary network failure may be retryable; an invalid argument or denied permission is not. Repeating a non-idempotent action can create duplicate tickets, payments, messages, or records. Where possible, send an idempotency key generated by your application and store the result associated with that key.
Track retry count separately from the total number of tool calls. A growing retry rate can indicate a dependency problem, an overly aggressive timeout, or a malformed integration rather than a model-quality issue.
5. Observability and safe results
Record a trace for each run containing the tool name, validated arguments or a redacted representation, permission decision, approval status, start and end times, outcome, error category, and correlation identifier. Avoid logging secrets or unnecessary personal data. For broader monitoring guidance, see the LLM observability runbook.
Return structured results to the model. Distinguish success, validation failure, permission denial, timeout, dependency failure, and unknown error. Do not expose raw stack traces or sensitive backend responses. A concise error such as tool_unavailable with a safe explanation gives the agent a chance to recover without revealing implementation details.
Cadence and checkpoints
Tool calling should be reviewed as an operational system, not only when a new model is introduced. A lightweight monthly or quarterly review can catch permission drift, recurring failures, and changes in the surrounding workflow.
Before adding or changing a tool
- Write down the tool's single responsibility and expected side effects.
- Confirm the minimum permissions and data access it needs.
- Add positive tests for valid arguments and negative tests for invalid ones.
- Define timeout, retry, rate-limit, and idempotency behaviour.
- Decide whether the action needs approval or can run automatically.
- Specify safe error categories and the human handoff path.
Monthly operational check
Review call volume, success rate, validation failures, permission denials, timeout frequency, retry counts, average and high-percentile latency, approval frequency, and human handoffs. Compare these signals with a previous period rather than treating one isolated failure as a trend.
Sample completed traces manually. Check whether the model selected the right tool, whether arguments were within the intended scope, whether the result was interpreted correctly, and whether users understood approval messages. Redact or restrict trace access as part of the review. The AI data privacy checklist can support this part of the process.
Quarterly control review
Reconfirm service accounts, role assignments, secret rotation procedures, allowed destinations, retention settings, and escalation contacts. Review tools that have acquired new capabilities or are now used in higher-impact workflows. If your team has changed its prompts or orchestration logic, rerun representative scenarios using a controlled test set. Synthetic data can help test tool paths without exposing live records; see the synthetic data guide for LLM testing.
How to interpret changes
Metrics need context. A rise in tool calls may mean the agent is being used more often, or it may indicate loops caused by unclear results. A higher approval rate may reflect a new workflow rather than worse model behaviour. Always compare changes with deployments, prompt edits, provider changes, dependency incidents, and shifts in user tasks.
Use failure categories to narrow the investigation:
- Validation failures: inspect the schema, field descriptions, examples, and model output parsing.
- Permission denials: check identity mapping, resource scope, and whether the agent is attempting actions outside its role.
- Timeouts and retries: inspect dependency health, payload size, network paths, and timeout settings.
- Duplicate actions: add idempotency controls and verify retry behaviour.
- Incorrect tool selection: make tool descriptions more distinct, reduce overlapping capabilities, and test competing requests.
- Unsafe or irrelevant arguments: strengthen server-side validation and review whether the model is receiving untrusted content that can influence tool use.
Prompt injection deserves a separate control review when tools can access private data or perform side effects. Treat retrieved documents, web pages, emails, and user-provided text as data rather than instructions. Keep policy decisions outside the model, limit tool permissions, and require approval for sensitive actions. Use the prompt injection prevention checklist when reviewing a tool-using application.
Cost and latency also matter. Track token usage around tool descriptions, argument payloads, and returned results, especially when an agent can call several tools in one run. A token budget and routing review can be paired with the AI API cost planning template and the LLM cost optimisation guide.
When to revisit
Revisit this design whenever you add a tool, change a schema, alter an approval rule, rotate credentials, change the model or framework, connect a new data source, or move an agent into a higher-impact workflow. Provider terminology and supported features can change, so verify current API documentation before copying an implementation example into production.
Use a monthly review for active agents and a quarterly control review for established systems. Review sooner after a security event, repeated failure, unexpected cost increase, user complaint, or change in the data handled by the agent.
For a practical next step, create an inventory with one row per tool and these columns: owner, purpose, risk level, data accessed, permissions, approval requirement, timeout, retry policy, idempotency method, logged fields, last test date, and next review date. Then run one successful scenario, one invalid-argument scenario, one denied-permission scenario, one timeout scenario, and one duplicate-request scenario. Record the expected result for each.
Finally, make human handoff explicit. The agent should stop when it cannot verify identity, scope, or intent; when a side effect is irreversible; when retries are exhausted; or when the user disputes the proposed action. A reliable handoff includes the request, attempted tool, safe error category, relevant trace identifier, and the decision a person needs to make. This turns failure handling from an improvised response into a repeatable part of your AI agent security and LLM application development practice.