AI Tool Security: How to Secure Function Calling and External Integrations
How to secure tools and function calling in AI applications: tool schemas, argument validation, authorization, output handling, network restrictions, sandboxing code execution, rate limits, safe errors and third-party tool risks.
Quick answer
Secure AI tools by designing them narrowly, with strict schemas and clear descriptions; validating every model-supplied argument with allow-lists, ranges and business rules; authorizing each call as the requesting user in the tool layer; sandboxing code execution and restricting network egress; applying timeouts, rate limits and idempotency; treating tool outputs as untrusted content with size limits; returning safe, useful errors; and vetting third-party tools and MCP servers like any other dependency.
Where This Fits
Identity and permissions for agents are covered in AI agent access control; MCP-specific threats such as tool poisoning in MCP security; injected content arriving through tool outputs in indirect prompt injection; and backend integration patterns in AI API integration.
How Tool Calls Flow
Designing Tools Narrowly
A tool called run_sql or http_request gives a model enormous power; a tool called get_order_status(order_id) gives it exactly what the task needs. Prefer narrow, task-specific tools over general ones, separate read tools from write tools, and expose only the tools relevant to the current task or user. Write tool descriptions that state when to use them and their limits, and version them, because description changes affect model behaviour.
{
"name": "issue_refund",
"description": "Create a refund request for an order the current user owns. Requires user confirmation. Maximum 500.00 in the order currency.",
"input_schema": {
"type": "object",
"properties": {
"order_id": { "type": "string", "pattern": "^ORD-[0-9]{8}$" },
"amount": { "type": "number", "exclusiveMinimum": 0, "maximum": 500 },
"reason": { "type": "string", "enum": ["damaged", "late", "wrong_item", "other"] }
},
"required": ["order_id", "amount", "reason"],
"additionalProperties": false
}
}
# Server side: verify order belongs to user, amount <= amount paid, confirmation recordedValidating Inputs
Treat arguments as you would untrusted input to a public API. Validate types, formats, lengths and ranges against the schema; check identifiers against what the user may access; resolve file paths and confirm they stay inside allowed directories; use parameterized queries and never build SQL or shell commands by string concatenation; and re-check business rules such as refund limits in code. Microsoft's agent safety guidance makes the same recommendations, favouring allow-lists over trying to filter known-bad patterns.
Giving an AI assistant real actions to take?
ZSpace Labs builds secure tool layers for AI agents and copilots, with validation, authorization and sandboxing. See AI integration services.
Authorization
Every tool call should run with the permissions of the user the agent is acting for, or a narrowly scoped service identity, and be checked by the system that owns the data. The model's choice of tool is a request, not a permission. See AI agent access control for identity models and approvals.
Execution Controls
| Control | Purpose |
|---|---|
| Sandboxing | Isolate code execution and file operations from hosts and secrets |
| Network egress allow-lists | Prevent tools from reaching arbitrary destinations or exfiltrating data |
| Timeouts | Stop hung or slow operations |
| Rate limits and quotas | Limit abuse, loops and cost |
| Idempotency keys | Make retries safe for side-effecting operations |
| Dry-run and preview modes | Show effects before committing |
Handling Tool Outputs
Tool outputs flow back into the model's context, so they are another channel for injected instructions and for leaking data the model does not need. Return the minimum fields required, limit sizes, mark content from external sources as untrusted and avoid echoing secrets or internal identifiers. When outputs will be rendered to users or used in further actions, validate and sanitize them like any untrusted data.
Safe Error Handling
Errors should help the model correct its call without revealing internals. Return clear validation messages ('amount exceeds the refund limit for this order') rather than stack traces, connection strings or data from other records. Log full error details server-side for engineers.
Third-Party Tools and MCP Servers
Third-party tools and MCP servers extend agents quickly but bring supply chain risk. Review the provider and source, pin versions, check which permissions and data each tool needs, watch for changes to tool descriptions (which can carry injected instructions) and run untrusted servers in isolated environments. See AI supply chain security.
Advantages and Limitations
A secure tool layer lets agents do useful work while keeping the blast radius of mistakes small, and it works regardless of how the model behaves. Narrow tools mean more tools to build and maintain, and strict validation can frustrate legitimate edge cases; review rejected calls to refine rules.
How to Secure Tools Step by Step
- 1. Inventory tools with the data and actions each exposes
- 2. Narrow and split broad tools into task-specific ones
- 3. Define strict schemas and validate every call
- 4. Authorize as the user in the tool layer
- 5. Sandbox execution and restrict egress
- 6. Limit, sanitize and mark tool outputs
- 7. Vet and pin third-party tools
Code Execution and Browser Tools
Tools that run code or control a browser are among the most powerful and risky. Run code in ephemeral sandboxes, such as containers or microVMs created per task, with no credentials, restricted network egress, CPU, memory and time limits, and read-only access to only the files the task needs. Browser tools should run in isolated profiles without saved logins unless a task requires a specific session, with allow-listed domains for form submission and confirmation before purchases or account changes.
Testing Tools
Test each tool as an API exposed to an untrusted caller: invalid types and ranges, identifiers belonging to other users, path traversal attempts, oversized inputs and repeated calls. Test the model's use of tools too: whether planted content can trigger unwanted calls and whether confirmation rules hold. Add these cases to the automated suite described in AI security testing.
Tool Description Hygiene
Tool descriptions are instructions to the model, so they are part of your security surface. Write them yourself for internal tools, review descriptions of third-party tools before enabling them and watch for changes, because a modified description can steer the model, a risk sometimes called tool poisoning in MCP discussions. Keep descriptions factual about purpose, inputs and limits, and never include secrets or internal URLs that grant access.
Present only tools relevant to the current task and user. Large tool lists increase both mistakes and the chance that one poorly described tool is misused. Version tool definitions alongside prompts and evaluate changes the same way. MCP-specific concerns are covered in MCP security.
Worked Example
An illustrative scenario, not a client case: an internal analytics assistant has a generic run_sql tool connected with a read-write database user. A review replaces it with read-only access to a set of curated views, a query tool that only accepts parameterized templates, a row limit and a timeout. The assistant still answers most analytics questions, and destructive or bulk-export queries are no longer possible.
Common Mistakes
- Generic tools such as raw SQL, shell or HTTP access
- Trusting model-supplied IDs and amounts
- Code execution with access to secrets or the internet
- Returning full records and raw web content to the model
- Stack traces and internal details in tool errors
Want your agent's tools reviewed?
Talk to ZSpace Labs about an AI tool security review covering schemas, validation, sandboxing and third-party tools.
Conclusion
Tools are where AI output becomes action. Keep them narrow, validate and authorize every call in code, sandbox execution, treat outputs as untrusted and vet third-party tools carefully.
Common questions
A capability where a model outputs a structured request to call a function you define, such as looking up an order or creating a ticket. Your application executes the function and returns the result to the model.