Sub topic 7
Constraining Tool Arguments
This chapter assumes you know how LLM tool calling works, can read short Python and JSON snippets, and understand roles and permissions. A tool allowlist decides which tools an agent may call. This chapter covers what happens inside an allowed call: which argument values the tool accepts.
Why an allowed tool is still a risk
Suppose an agent may call read_file. The tool name passed the allowlist, but the call is only safe if the path is safe. The model writes the arguments, and the model reads untrusted text such as web pages, emails, and documents. An attacker who plants instructions in that text can influence every argument value.
The tool name tells you the kind of action. The arguments tell you its target, its size, and its destination. Least privilege has to cover both.
| Tool | Harmless call | Harmful call from the same tool |
|---|---|---|
| `read_file` | `reports/q3.txt` | `../../etc/passwd` |
| `send_email` | `[email protected]` | `[email protected]` with private data in the body |
| `run_query` | `SELECT name FROM products` | `SELECT * FROM customers` |
| `http_get` | `https://docs.example.com/page` | `http://169.254.169.254/latest/meta-data/` |
Each harmful call uses a tool the agent is allowed to use. Only argument checks can stop it.
Where argument checks run
Put the checks in the tool runtime, in ordinary code, after the model proposes a call and before the tool executes. Do not rely on a prompt line such as "only read files in the workspace". A prompt is a request to the model. An injected instruction can override it. Code cannot be talked out of a check.
Treat the model's arguments the way a web server treats form input from a stranger. Validate them at the trust boundary.
Technique 1: Validate against a schema
Most tool-calling APIs ask you to describe arguments with a JSON Schema. Models usually follow it, but it is not a guarantee. Enforce the schema yourself on every call. A schema can restrict type, length, range, pattern, and allowed values.
{
"type": "object",
"properties": {
"report_id": { "type": "string", "pattern": "^[A-Z]{3}-[0-9]{6}$" },
"format": { "type": "string", "enum": ["pdf", "csv"] },
"max_rows": { "type": "integer", "minimum": 1, "maximum": 500 }
},
"required": ["report_id", "format"],
"additionalProperties": false
}Three details matter here:
enumlists the permitted values. This is stronger than describing them in prose.maximumandmaxLengthbound the size of the result or input.additionalProperties: falserejects arguments you did not define. Without it, an extra field can reach a tool that quietly honors it.
The schema is also the place to prefer narrow types. A report_id that must match a fixed pattern leaves little room for injected content.
The next example validates arguments in Python with the jsonschema package (install it with pip install jsonschema).
from jsonschema import Draft202012Validator
REPORT_SCHEMA = {
"type": "object",
"properties": {
"report_id": {"type": "string", "pattern": "^[A-Z]{3}-[0-9]{6}$"},
"format": {"type": "string", "enum": ["pdf", "csv"]},
"max_rows": {"type": "integer", "minimum": 1, "maximum": 500},
},
"required": ["report_id", "format"],
"additionalProperties": False,
}
validator = Draft202012Validator(REPORT_SCHEMA)
def validate_args(args: dict) -> None:
errors = sorted(validator.iter_errors(args), key=lambda e: list(e.path))
if errors:
raise ValueError("; ".join(e.message for e in errors))
validate_args({"report_id": "ABC-123456", "format": "csv", "max_rows": 100}) # passes
try:
validate_args({"report_id": "../secret", "format": "xml", "extra": 1})
except ValueError as exc:
print("rejected:", exc)Technique 2: Canonicalize, then check
A schema checks shape. It does not understand what a path or URL means. For those, convert the value to its canonical form first, then compare it with the allowed set. Checking the raw string is the classic mistake, because reports/../../secrets.txt starts with reports/.
The path check from the earlier chapters on enforcement does this correctly:
from pathlib import Path
ALLOWED_ROOT = Path("/srv/agent/workspace").resolve()
def read_file(path: str) -> str:
target = (ALLOWED_ROOT / path).resolve()
if not target.is_relative_to(ALLOWED_ROOT):
raise PermissionError("path is outside the workspace")
return target.read_text()resolve() removes .. segments and follows symbolic links. If the model passes an absolute path such as /etc/passwd, joining it to the root replaces the root, and resolve() then exposes the result as outside the workspace. The is_relative_to check rejects it. Because resolve() follows symlinks, a link inside the workspace that points elsewhere is also caught.
The same idea applies to other value types:
- URLs: parse the URL, then check the scheme, the hostname, and the port against an allowlist. Do not test with
startswith("https://docs.example.com"), becausehttps://docs.example.com.evil.example/passes that test. - Resolved addresses: if a tool fetches URLs, check the IP address the hostname resolves to and block private and link-local ranges such as
169.254.0.0/16. This guards against server-side request forgery. Re-check after redirects. - Identifiers: match them against a strict pattern, then look them up. Do not build file names or queries from them directly.
from urllib.parse import urlparse
ALLOWED_HOSTS = {"docs.example.com"}
def check_url(url: str) -> str:
parts = urlparse(url)
if parts.scheme != "https":
raise PermissionError("only https is allowed")
if parts.hostname not in ALLOWED_HOSTS:
raise PermissionError(f"host {parts.hostname!r} is not allowed")
if parts.port not in (None, 443):
raise PermissionError("unexpected port")
return url
print(check_url("https://docs.example.com/guide"))Technique 3: Remove the argument
The strongest constraint is an argument the model cannot set. Fix a value in code and hide the parameter from the model.
Consider a database tool. A version that accepts a sql string lets the model write any query. Compare it with a narrow tool that exposes only what the task needs:
import sqlite3
def get_order_status(order_id: str, *, customer_id: str, conn: sqlite3.Connection):
# customer_id is injected by the runtime from the logged-in session.
# It is not part of the schema shown to the model.
cur = conn.execute(
"SELECT status FROM orders WHERE id = ? AND customer_id = ?",
(order_id, customer_id),
)
return cur.fetchone()This version has three useful properties:
- The model supplies only
order_id. The SQL text is fixed. - The
?placeholders keep the value as data, so it cannot change the query structure. customer_idcomes from the authenticated session, not from the model. Even if injected text tells the model to look up another customer's order, the query filters by the real user.
This is the pattern to prefer: bind the security-relevant arguments in code, and let the model choose only the harmless ones. Typical bound values are the user ID, tenant ID, bucket name, base directory, and sender address.
Technique 4: Prefer enums and lookups over free text
When the set of valid targets is small, let the model pick from names and map them to real values yourself.
MAILING_LISTS = {
"engineering": "[email protected]",
"support": "[email protected]",
}
def send_to_list(list_name: str, subject: str, body: str) -> dict:
if list_name not in MAILING_LISTS:
raise ValueError(f"unknown list {list_name!r}")
address = MAILING_LISTS[list_name]
return {"to": address, "subject": subject[:200], "body": body[:5000]}
print(send_to_list("support", "Weekly digest", "Hello team"))The model can no longer name an arbitrary recipient. An injected request to send data to [email protected] fails because that value is not a key in the table. Length caps on subject and body also limit how much data a single call can carry out.
Technique 5: Bound size and scope
Some arguments are valid values that still cause harm in bulk. Add numeric bounds and result caps.
- Cap
limit,max_rows, andpage_size. - Cap the length of free-text fields.
- Reject wildcards and unbounded ranges, such as
*in a delete filter or a date range of fifty years. - For write tools, accept one record ID per call instead of a list or a filter.
A cap does not stop a determined attacker who can make many calls. Pair caps with the rate limits and budgets covered in a later chapter.
Handling rejection
When a check fails, return a short, specific error to the model, such as path is outside the workspace. The model can then correct an honest mistake. Do not include internal paths, stack traces, or secrets in the message. Also log the rejected call. A burst of rejections is a useful sign that the agent has read hostile input.
Do not silently rewrite a bad argument into a "close enough" valid one. If you change ../x into x, the tool now does something the model did not ask for, and the logs no longer match the request. Reject instead.
Common errors
- Checking the string, not the resolved value. Prefix tests on paths and URLs are bypassed by
.., symlinks, and look-alike hostnames. - Blocklists. A list of bad patterns misses the next variant. Allow known-good values and reject everything else.
- Validating once, using later. If you check a path and then another component re-interprets it, the checked value and the used value differ. Validate the exact value you pass to the tool.
- Trusting the model-supplied identity. Never accept
user_idortenant_idas a model-controlled argument. Take it from the session. - Building SQL or shell strings from arguments. Use parameterized queries and argument lists, not string concatenation. Avoid
shell=True. - Relying on the schema alone. The model can produce a call that violates it. The runtime must validate.
Limits of argument constraints
Argument checks reduce what a single call can do. They do not decide whether a call is a good idea. A valid send_to_list("support", ...) call can still carry private data inside body. That risk comes from combining private data, untrusted input, and an outbound channel, and it needs controls on data flow and, for high-impact actions, human approval. Argument checks are one layer, and credentials scoped to the task should back them up.
Exercise
An agent has a fetch_page(url) tool. The developer writes if url.startswith("https://docs.example.com"): fetch(url). Name one URL that passes this check but reaches an attacker's server, and describe a stronger check.
Show answer
https://docs.example.com.evil.example/page starts with the allowed prefix but its hostname is docs.example.com.evil.example. A stronger check parses the URL, requires the https scheme, and compares hostname exactly against an allowlist such as {"docs.example.com"}. It should also check the port, resolve the host and block private or link-local addresses, and re-check after each redirect.
Exercise
A get_invoice(invoice_id, customer_id) tool lets the model supply both arguments. How would you change it so an injected prompt cannot read another customer's invoice?
Show answer
Remove customer_id from the model-facing schema and have the runtime fill it from the authenticated session. Validate invoice_id against a strict pattern, and use a parameterized query that filters on both invoice_id and the session's customer_id.