A tool schema answers a narrow question: does this call have the right shape? It does not answer whether the call should happen. An agent can produce a perfectly valid refund for fifty thousand dollars, a valid database query for another tenant's rows, or a valid email to a customer who asked to be left alone.
OpenAI's strict mode removes a class of ambiguity. With strict: true, every object needs additionalProperties: false, every property must be listed as required, and optional fields are expressed with a null type. The model cannot smuggle an extra admin: true into the arguments. That is useful, but it is still syntax, not authorization.
This tutorial adds the missing layer: a server-side gate that validates arguments against a narrow schema and then checks identity, ownership and limits before any side effect. The code is small enough to test on its own, and the same function can sit between the model and every tool you expose.
Step 1 — make the schema do the cheap work
Start with one tool and make the schema narrower than the database. Enums instead of free text, patterns for identifiers, and a maximum for money.
TOOLS = {
"issue_refund": {
"type": "object",
"additionalProperties": False,
"required": ["order_id", "amount_cents", "reason"],
"properties": {
"order_id": {"type": "string", "pattern": "^ord_[A-Za-z0-9]{8,32}$"},
"amount_cents": {"type": "integer", "minimum": 1, "maximum": 50000},
"reason": {"type": "string", "enum": ["damaged", "late", "duplicate"]},
},
}
}This schema rejects negative amounts, free-form reasons and unknown fields. It still allows a valid refund above the amount a support agent may approve, which is why step two exists.
Step 2 — validate and authorize in one gate
Install the validator with pip install jsonschema, then put the policy in one function. The function receives the caller's tenant and the tenant that owns the order; both must match before anything executes.
from __future__ import annotations
import json
from typing import Any
from jsonschema import Draft202012Validator
TOOLS: dict[str, dict[str, Any]] = {
"issue_refund": {
"type": "object",
"additionalProperties": False,
"required": ["order_id", "amount_cents", "reason"],
"properties": {
"order_id": {"type": "string", "pattern": "^ord_[A-Za-z0-9]{8,32}$"},
"amount_cents": {"type": "integer", "minimum": 1, "maximum": 50000},
"reason": {"type": "string", "enum": ["damaged", "late", "duplicate"]},
},
}
}
class Denied(Exception):
"""The call is well-formed but not allowed."""
def gate(
name: str,
args: dict[str, Any],
*,
principal_tenant: str,
order_tenant: str,
approval_limit_cents: int = 20000,
) -> dict[str, Any]:
schema = TOOLS.get(name)
if schema is None:
raise Denied(f"tool not allowed: {name}")
Draft202012Validator(schema).validate(args)
if order_tenant != principal_tenant:
raise Denied("order belongs to another tenant")
if name == "issue_refund" and args["amount_cents"] > approval_limit_cents:
raise Denied("refund above the auto-approval limit needs a human")
return {"ok": True, "tool": name, "args": args}The order matters. Unknown tools are rejected before validation. Schema errors are raised as ValidationError. Policy failures raise Denied. The caller must treat both as a refusal, not as a reason to retry with different arguments.
Step 3 — run the gate before the side effect
Do not call the refund API and then validate. The gate runs first, and its return value is the only thing the executor receives.
if __name__ == "__main__":
valid = {"order_id": "ord_1234ABCD", "amount_cents": 4200, "reason": "late"}
print(gate("issue_refund", valid, principal_tenant="acme", order_tenant="acme"))
cases = [
("unknown tool", "delete_database", {}, "acme", "acme"),
("extra field", "issue_refund", {**valid, "admin": True}, "acme", "acme"),
("negative amount", "issue_refund", {**valid, "amount_cents": -1}, "acme", "acme"),
("wrong enum", "issue_refund", {**valid, "reason": "because"}, "acme", "acme"),
("other tenant", "issue_refund", valid, "acme", "globex"),
("over limit", "issue_refund", {**valid, "amount_cents": 49999}, "acme", "acme"),
]
for label, name, args, tenant, order_tenant in cases:
try:
gate(name, args, principal_tenant=tenant, order_tenant=order_tenant)
except Exception as exc:
print(f"{label}: {type(exc).__name__}: {str(exc)[:70]}")
else:
raise SystemExit(f"FAIL: {label} was allowed")Run it with python gate.py. The valid call prints a result. Every adversarial case prints a denial, and the program exits non-zero if one slips through.
Step 4 — return a structured denial to the model
The model needs a machine-readable failure, not a stack trace. In the Responses API loop, send the denial back as the tool output and let the model explain it to the user or ask for approval.
import json
import os
from openai import OpenAI
client = OpenAI()
model = os.environ["OPENAI_MODEL"] # use the current model available to your account
response = client.responses.create(
model=model,
tools=[{
"type": "function",
"name": "issue_refund",
"description": "Refund a paid order after verifying ownership.",
"strict": True,
"parameters": TOOLS["issue_refund"],
}],
input="Refund order ord_1234ABCD: the package arrived late.",
)
for item in response.output:
if item.type != "function_call":
continue
args = json.loads(item.arguments)
try:
result = gate(
item.name,
args,
principal_tenant="acme",
order_tenant=lookup_tenant(args["order_id"]),
)
except Exception as exc:
result = {"error": str(exc)}
response = client.responses.create(
model=model,
tools=[{
"type": "function",
"name": "issue_refund",
"description": "Refund a paid order after verifying ownership.",
"strict": True,
"parameters": TOOLS["issue_refund"],
}],
previous_response_id=response.id,
input=[{
"type": "function_call_output",
"call_id": item.call_id,
"output": json.dumps(result),
}],
)This is the shape of the loop, not a complete application: lookup_tenant must read from your own order store, and the executor that issues the refund belongs after a successful gate. The important part is that the denial is ordinary data. It does not raise through the orchestrator, and it does not cause a retry with a bigger amount.
Step 5 — test what an attacker would try
The unit cases above cover extra fields, limits, enums and cross-tenant access. Add the cases that come from your domain: a deleted order, a refund that was already issued, a currency mismatch, a user who has left the organization. Then add idempotency. If the model retries after a timeout, the second call must not issue a second refund.
Log the tool name, a hash of the arguments, the tenant, the decision and the call identifier. Do not log full arguments if they contain personal data.
What this does not fix
Prompt injection can still steer the agent toward a permitted action. If a document tells the model to refund an order, and the order belongs to the caller and sits under the limit, the gate will allow it. That is why the gate is one layer: least-privilege connectors, read-only tools where possible, human approval for irreversible actions, rate limits and audit logs do the rest.
The rule is not "validate the model's output". It is "never let the model's output be the last word before a side effect". A strict schema makes the conversation cheaper. The gate makes the decision.