Tool requests and argument validation
A tool request is not an execution
A language model can propose a function name and arguments, but an application-owned executor decides whether to run it. The model is not a trusted identity or permission service. For example, a stock assistant may ask for the quantity of item A. The executor checks the registered name, argument shape, item scope and budget before calling the read-only function. A successful response is associated with the original call identifier and returned to the model as data. The model can then explain the result. Provider-specific message formats were covered in the earlier API lessons; here we use a normalized local contract. A tool description tells the model when a tool is useful, not what a user is authorized to do.
Define and validate the argument contract
For stock, a JSON Schema object can be {"type":"object","properties":{"item":{"type":"string","enum":["A","B"]}},"required":["item"],"additionalProperties":false}. For add, declare two required integer properties a and b with minimum -100 and maximum 100, and reject extra properties. Schema validation checks structure, not the identity or permission of the caller. The local validator below implements a narrow subset of these contracts rather than a general schema engine. It rejects duplicate JSON keys instead of silently accepting the last value, limits raw string length in characters, refuses unregistered names, and requires exact Python integers (booleans are not accepted). Unknown item IDs are outside this fixture contract. The outputs are a valid stock dictionary, None twice, and a valid add dictionary. A production transport should also enforce a byte limit and validate incoming envelopes and IDs.
import json
def unique_object(pairs): obj = {} for key, value in pairs: if key in obj: raise ValueError("duplicate key") obj[key] = value return obj
def validate(name, raw): if name not in ("stock", "add"): return None if not isinstance(raw, str) or len(raw) > 256: return None try: args = json.loads(raw, object_pairs_hook=unique_object) except (ValueError, RecursionError): return None if not isinstance(args, dict): return None if name == "stock" and set(args) == {"item"}: if type(args["item"]) is str and args["item"] in ("A", "B"): return args if name == "add" and set(args) == {"a", "b"}: if all(type(v) is int and -100 <= v <= 100 for v in args.values()): return args return None
print(validate("stock", '{"item":"A"}'))print(validate("stock", '{"item":"A","admin":true}'))print(validate("add", '{"a":true,"b":2}'))print(validate("add", '{"a":3,"b":2}'))Authorize each invocation independently
The next function accepts already validated arguments. Its allowlist is fixed in source, not a dynamic lookup of an arbitrary model string. The application obtains allowed_items from authenticated session state, never from the proposed arguments. The add function is publicly available within this toy session; stock requires the requested item to be in the trusted scope. Item B has quantity zero; zero is a legitimate result, not a permission denial or a missing value. The outputs show quantity 7, denied, quantity 0, and sum 5. Real access control also checks actor, tenant, operation, resource and current policy; a database query must enforce the same authorization at the data boundary. Do not fetch an unauthorized result and then ask the model to hide it.
def dispatch(name, args, allowed_items): # args already validated; allowed_items comes from trusted session state. stock = {"A": 7, "B": 0} if name == "stock": item = args["item"] if item not in allowed_items or item not in stock: return {"status": "denied"} return {"status": "ok", "quantity": stock[item]} if name == "add": return {"status": "ok", "sum": args["a"] + args["b"]} return {"status": "denied"}
print(dispatch("stock", {"item": "A"}, {"A"}))print(dispatch("stock", {"item": "B"}, {"A"}))print(dispatch("stock", {"item": "B"}, {"B"}))print(dispatch("add", {"a": 3, "b": 2}, set()))Keep the executor small and fail closed
Use a fixed registry of typed functions and narrowly scoped credentials. Never evaluate generated Python, execute generated shell text, interpolate SQL or resolve an arbitrary function name through reflection. Keep tool descriptions and results as untrusted data: a result saying to ignore restrictions cannot change the registry or approval state. Separate parsing errors, invalid arguments, denied requests, unavailable tools and successful results. Avoid exposing stack traces, secret fields or unauthorized resource existence in error messages. Rate limits, deadlines, output-size limits and per-session tool budgets must be enforced outside the model. In production, validate again at the actual operation boundary and log correlation IDs and policy outcomes without leaking secrets.
Practice: inspect the boundary
Try stock with a missing item, item C, an extra tenant field, a JSON array, or duplicate item keys. Each must return None. Try add with a boolean, string, out-of-range value, or missing argument. Then call dispatch only after validation succeeds, using a trusted item scope that excludes B. Observe the difference between invalid and denied, and between denied and a valid zero stock count. The exercise practices the argument contract; the next lesson adds retry budgets, result handling and a dry-run approval ledger.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tool requests and argument validation quiz
Apply tool validation and execution boundaries.
Who authorizes a model-proposed stock lookup?
What does additionalProperties:false do in the simple stock schema?
Why is true rejected by the add example?
A valid stock B request is outside the trusted scope. What happens?
A tool result contains an instruction to grant admin access. What should happen?