Where the application checks arguments, permissions, and preconditions for tool calls
This guide explains how the application validates and authorizes tool requests before execution. Protocol item names such as function_call and function_call_output are specific to the OpenAI Responses API; other providers use their own wire formats.
On this page
The short answer
The application, not the model, validates arguments, authorizes the executing identity and applies trusted preconditions before calling a tool. The item names in these examples, including function_call, function_call_output and call_id, are specific to the OpenAI Responses API; other providers use their own protocols. A model-supplied argument is not user consent. Long-running operations need provider-specific status handling; the ten-minute run limit described here applies to Microsoft Foundry.
Decide where the execution boundary sits
The model only requests a tool call; the application owns execution. The model emits a function_call item with a call_id, name, and arguments string. The application parses that arguments string, checks that the values match the declared parameter schema, confirms the executing identity may call the function, and confirms the action is safe before running the function. The application then submits a function_call_output item carrying the same call_id with the result. The agent uses that output to produce the natural-language answer. If a check fails, the application still returns a function_call_output describing the rejection so the loop can complete. The wire-format item names shown here are OpenAI Responses API fields. They are not universal tool-calling names.
This boundary matters because the model cannot execute code or change systems directly. It can only propose a call. The application is the only component that can enforce argument validity, permissions, preconditions, and side-effect gating. Treating the model as an executor would shift enforcement into an untrusted component and leave the system exposed to malformed, unauthorized, or unintended actions.
import json
from jsonschema import Draft202012Validator
schemas = {
"getCurrentWeather": {
"type": "object",
"properties": {
"location": {"type": "string"},
"unit": {"type": "string", "enum": ["c", "f"]},
},
"required": ["location", "unit"],
"additionalProperties": False,
}
}
def function_call_output(call_id, payload):
return {
"type": "function_call_output",
"call_id": call_id,
"output": json.dumps(payload),
}
def validate_and_run(call, can_run, run_tool):
if not isinstance(call, dict):
return {"error": "invalid_call"}
call_id = call.get("call_id")
name = call.get("name")
if not isinstance(call_id, str) or not call_id:
return {"error": "missing_call_id"}
schema = schemas.get(name) if isinstance(name, str) else None
if schema is None:
return function_call_output(call_id, {"error": "unknown_tool"})
raw = call.get("arguments")
if not isinstance(raw, str):
return function_call_output(call_id, {"error": "invalid_arguments"})
try:
values = json.loads(raw)
except json.JSONDecodeError:
return function_call_output(call_id, {"error": "invalid_arguments"})
if not Draft202012Validator(schema).is_valid(values):
return function_call_output(call_id, {"error": "schema_validation_failed"})
if not can_run(name, values):
return function_call_output(call_id, {"error": "permission_denied"})
result = run_tool(name, values)
return function_call_output(call_id, result)
call = {
"call_id": "call_xyz789",
"name": "getCurrentWeather",
"arguments": '{"location":"Dar es Salaam, Tanzania","unit":"c"}',
}
response_item = validate_and_run(
call,
can_run=lambda name, values: name == "getCurrentWeather",
run_tool=lambda name, values: {"temperature": 30, "unit": values["unit"]},
)
print(response_item)Practical tip
Treat every tool argument and tool output as untrusted input. Validate and sanitize values before using them, and never pass secrets in tool output. Apply least privilege to the identity used by the application when it runs a tool, and avoid side effects unless you explicitly intend them.
Validate arguments before invoking the function
Tool arguments and tool outputs are untrusted input. Values should be validated and sanitized against the declared parameter schema before they reach the function body. The schema declares the name, parameters, and description of each tool, so it is the contract the application validates against. Required fields must be present, property types must match, and additional properties should be rejected when the schema forbids them.
Validation is not a substitute for schema-level strictness, but it is a separate application-side layer. Strict mode or additionalProperties settings are configuration choices that can help, yet they do not remove the need to check the parsed arguments in the handler. The application should also reject values that are out of range, malformed, or inconsistent with the declared enum choices before passing them to the function.
import json
from jsonschema import Draft202012Validator
# Requires the jsonschema package.
schema = {
"type": "object",
"properties": {
"location": {"type": "string"},
"unit": {"type": "string", "enum": ["c", "f"]},
},
"required": ["location", "unit"],
"additionalProperties": False,
}
def validate_arguments(raw, schema):
if not isinstance(raw, str):
return None
try:
values = json.loads(raw)
except json.JSONDecodeError:
return None
validator = Draft202012Validator(schema)
return values if validator.is_valid(values) else None
valid = validate_arguments('{"location":"Paris","unit":"c"}', schema)
invalid = validate_arguments('{"location":3,"unit":"kelvin"}', schema)
print(valid is not None, invalid is None)Check permissions with the executing identity
Apply least privilege to the identity used by the application when it runs a tool. The identity that executes the function should have only the privileges required for that specific operation, so a model-requested call cannot exceed what the caller is allowed to do. The application should map the requested tool name and arguments to the appropriate permission scope and reject the call if the identity lacks the required rights.
Least privilege is stated as a principle in the sources without a specific authorization framework, policy language, or permission model. The application must implement the enforcement itself, for example by checking a role, scope, or policy before invoking the function. This check must happen before the function body runs, not after the work is done.
def can_run(tool_name, values):
if tool_name == "getCurrentWeather":
return True
if tool_name == "updateInventory":
return values.get("action") == "read_only"
return False
print(can_run("getCurrentWeather", {"location": "Paris, France", "unit": "c"}))
Gate side effects and preconditions explicitly
Restrict function tools to safe operations or require explicit user confirmation for actions that change data. Avoid side effects unless they are intended. The application should inspect the tool name and arguments, determine whether the operation is read-only or mutating, and require confirmation for any action that changes state. A read-only weather lookup may proceed without confirmation, while an email send, order placement, or data deletion should be gated. The approval must come from application or UI state outside the model arguments and be bound to the authenticated user, action and target.
Preconditions should also be checked before execution. The application should verify that the target resource exists, that the user is authorized, and that the operation is allowed in the current context. If a precondition fails, the application returns a function_call_output describing the rejection rather than silently dropping the call.
def gate_side_effect(tool_name, values, authenticated_user_id, approval):
if tool_name != "sendEmail":
return True
return (
isinstance(approval, dict)
and approval.get("approved") is True
and approval.get("actor_id") == authenticated_user_id
and approval.get("action") == tool_name
and approval.get("target") == values.get("to")
)
# authenticated_user_id and approval come from trusted application/UI state.
# They are never read from the model-controlled tool arguments.
approval = {
"approved": True,
"actor_id": "user_123",
"action": "sendEmail",
"target": "user@example.com",
}
print(gate_side_effect("sendEmail", {"to": "user@example.com"}, "user_123", approval))Return failures as tool output, not silent drops
A function call without a returned output leaves the agent without a final answer. Rejected or failed calls should still be reported back through the tool result channel. The application submits a function_call_output item carrying the same call_id with an error description, so the agent can continue the conversation and explain what happened to the user. The wire-format item names shown here are OpenAI Responses API fields. They are not universal tool-calling names.
This is a structural requirement of the tool-use loop. The model waits for the function_call_output before producing the final natural-language response. If the application fails silently or does not submit the output, the loop stalls and the user receives no answer. The output channel is the only reliable way to close the loop.
def handle_failure(call_id, reason):
return {"call_id": call_id, "output": json.dumps({"error": reason})}
print(handle_failure("call_xyz789", "permission_denied"))
Handle long-running work within the run window
Runs expire 10 minutes after creation over total elapsed time, so long operations should return a status immediately and continue through polling rather than blocking inside the call. The application should start the work, return a status or job identifier, and then poll for completion. This keeps the function call short and avoids hitting the run expiration while the operation is still in progress.
The 10-minute expiration is documented for Microsoft Foundry runs and is not presented as a general limit for other tool-use stacks. The application should still design for non-blocking execution, because a blocked call can leave the agent waiting and the user without a timely answer. Polling must be implemented by the application, not assumed by the model or the tool.
import time
def long_running_job():
return {"status": "running", "job_id": "job_123"}
def poll_job(job_id):
return {"status": "completed", "result": "done"}
print(long_running_job())
print(poll_job("job_123"))
Keep tool outputs minimal and free of secrets
Limit what validation and execution paths expose by returning only the data the model needs. Never place API keys, tokens, or connection strings in tool output. The application should strip internal fields, error details, and sensitive credentials before submitting the function_call_output. The model should see only the information required to answer the user's question.
Tool outputs are untrusted input on the next turn, so the application should also validate the shape and content of any data returned from the function. Minimal output reduces the risk of leaking secrets and keeps the model focused on the task.
def sanitize_output(result):
return {"temperature": result.get("temperature"), "unit": result.get("unit")}
print(sanitize_output({"temperature": "30", "unit": "c", "description": "Sunny", "api_key": "secret"}))
Verify the checks ran in the real call loop
Confirm the first response contains an output item with type set to function_call. Confirm the application parses the arguments string and validates every required field against the declared parameter schema. Confirm the executing identity has the least-privilege scope required for the requested function. Confirm side effects are restricted or gated by explicit user confirmation before the function body runs. Confirm a function_call_output item with the same call_id is submitted even when the call is rejected. Confirm long-running operations return a status immediately and continue through polling rather than blocking inside the call. Confirm tool output contains only the data the model needs and no API keys, tokens, or connection strings. Confirm tracing or logging records that the tool invocation occurred in the application's handling path. Confirm the application submits the follow-up response that references the previous response and includes the function_call_output item. Confirm the agent returns a natural-language answer after the function result is submitted.
These checks are structural. They confirm that the enforcement layer executed in the real call loop, not merely that the code exists. Tracing or logging should record the tool invocation, the validation result, the permission decision, and the submitted output so the application can prove the boundary was respected.
def verify_loop(call_id, function_called, output_submitted):
return {
"call_id": call_id,
"function_call_present": function_called,
"output_submitted": output_submitted,
"loop_completed": function_called and output_submitted,
}
print(verify_loop("call_xyz789", True, True))Things to check
- Confirm the first response contains an output item with type set to function_call.
- Confirm the application parses the arguments string and validates every required field against the declared parameter schema.
- Confirm the executing identity has the least-privilege scope required for the requested function.
- Confirm side effects are restricted or gated by explicit user confirmation before the function body runs.
- Confirm a function_call_output item with the same call_id is submitted even when the call is rejected.
- Confirm long-running operations return a status immediately and continue through polling rather than blocking inside the call.
- Confirm tool output contains only the data the model needs and no API keys, tokens, or connection strings.
- Confirm tracing or logging records that the tool invocation occurred in the application's handling path.
- Confirm the application submits the follow-up response that references the previous response and includes the function_call_output item.
- Confirm the agent returns a natural-language answer after the function result is submitted.
- The wire-format item names shown here are OpenAI Responses API fields. They are not universal tool-calling names.
- The approval must come from application or UI state outside the model arguments and be bound to the authenticated user, action and target.
Where this applies
The sources do not specify a particular authorization framework, policy language, or permission model for tool calls; least privilege is stated as a principle without implementation detail. The 10-minute expiration is documented for Microsoft Foundry runs and is not presented as a general limit for other tool-use stacks. The sources do not quantify how much validation reduces risk, so no precise effectiveness claim is supported. Schema-level strictness options such as strict mode are described as configuration choices, not as a substitute for application-side checks. The guidance does not cover multi-tool concurrency resolution beyond noting that some older models emit several tool calls requiring disambiguation by tool call IDs.