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 basic access control. The previous chapter put an allowlist in front of tools. Here we look inside a permitted call and limit the arguments it can carry.
Why the tool name is not enough
An allowlist answers one question: may this task call read_file at all? It doesn't answer which file. The model fills in the arguments, and a prompt-injected model can fill them with attacker-chosen values. A permitted tool with unconstrained arguments is still excessive permission.
Treat every argument as untrusted input that crosses a trust boundary, the same way you treat a web form field.
Three ways to constrain an argument
- Validate the type and shape. Check types, length, and format before the tool runs.
- Restrict values to an allowed set. Use enums, prefixes, or lists of permitted targets.
- Remove the argument. If the model never needs to choose a value, fix it in code and don't expose it.
The third option is the strongest. A parameter the model can't set can't be abused.
Example: confining a file path
The read_file tool takes a path from the model. The check below resolves the path first, then compares it to the workspace root. Resolving first matters, because it collapses .. segments and follows symlinks before you compare.
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()An absolute path such as /etc/passwd is rejected too. Joining an absolute path onto a Path replaces the left side, so the resolved target lands outside the root and fails the check.
A common error is checking the raw string, for example path.startswith("/srv/agent/workspace"). The string /srv/agent/workspace/../../etc/passwd passes that test and escapes the directory.
Example: schema validation before the call
For tools with several parameters, describe the allowed shape once and reject anything else. This sketch uses plain Python so it runs as shown.
import re
ALLOWED_RECIPIENT_DOMAIN = "example.com"
MAX_BODY_CHARS = 2000
def validate_email_args(args: dict) -> dict:
allowed_keys = {"to", "subject", "body"}
if set(args) != allowed_keys:
raise ValueError(f"expected exactly {sorted(allowed_keys)}")
to = args["to"]
if not isinstance(to, str) or not re.fullmatch(r"[\w.+-]+@" + re.escape(ALLOWED_RECIPIENT_DOMAIN), to):
raise ValueError("recipient must be an example.com address")
if not isinstance(args["subject"], str) or len(args["subject"]) > 200:
raise ValueError("subject must be a string up to 200 characters")
if not isinstance(args["body"], str) or len(args["body"]) > MAX_BODY_CHARS:
raise ValueError("body must be a string up to 2000 characters")
return args
print(validate_email_args({"to": "[email protected]", "subject": "Report", "body": "Attached."}))The check rejects unexpected keys, so the model can't slip in extra parameters such as bcc. It also limits the recipient to one domain, which blocks sending data to an attacker's address.
Where validation runs
Validation belongs in the runtime, between the model's request and the tool. It must not live in the tool description or the system prompt. The flow looks like this.
Return a short, specific error on failure. The model can then correct a honest mistake. Don't echo sensitive details, such as the real directory layout, in that message.
Practical rules
- Prefer allowlists (permitted values) over denylists (forbidden values). Attackers find the value you forgot to forbid.
- Fix arguments in code when the model has no need to choose them, such as the bucket name or database.
- Never build shell commands or SQL by joining strings from arguments. Use parameterized queries and argument lists.
- Cap sizes and counts so one call can't move unbounded data.
Exercise
A read_file tool checks path.startswith("/srv/agent/workspace") on the raw string before reading. Give an input that bypasses it and name the fix.
Show answer
The input /srv/agent/workspace/../../etc/passwd starts with the allowed prefix but resolves to /etc/passwd. The fix is to resolve the path first (joining it to the root and calling .resolve()), then check is_relative_to(ALLOWED_ROOT) on the resolved result.
Exercise
Why is removing an argument from the tool's interface stronger than validating it?
Show answer
If the model can't set the value, no injected instruction can change it. Validation can have gaps, such as a missed pattern or edge case. A fixed value has none.