Agent Local Tool Calling: From Structured Output to Safe Execution

    A practical guide to letting LLM agents use local tools without giving the model direct control: structured call requests, validation, authorization, and production-safe execution. Covers tool schemas, a trusted registry, the request–execute–return loop, injection and path risks, retries, and tests that go beyond happy paths.

    1. The model proposes calls; the application executes them

    When you build an agent, a common need is local capabilities: reading business files, querying internal data, running statistics, or invoking functions already in your app.

    “The model calls tools” does not mean the model operates the developer’s machine. The real flow is:

    1. You describe available tools and input constraints.
    2. The model produces a tool-call request for the user task.
    3. The application checks that the request is valid and authorized.
    4. A local executor runs the matching function and gets a result.
    5. The application returns that result to the model.
    6. The model continues reasoning and answers the user.
    1. User task
    2. ↓
    3. Model selects a tool and generates arguments
    4. ↓
    5. App validates protocol, permissions, and parameters
    6. ↓
    7. Local executor runs the tool
    8. ↓
    9. Result is returned to the model
    10. ↓
    11. Further calls or a final answer

    The important boundary: the model expresses intent, the application owns permissions, and tools perform deterministic work. Even a plausible-looking instruction must not skip checks. What actually runs is application code and policy, not the model output itself.

    2. Structured output is the foundation, not the same as tool calling

    Structured output is the right starting point. Natural language is good for people, poor as an execution protocol.

    If the model writes:

    1. Please count the words in the document for the user.

    a program still must decide which function to call, which document, and which counting rules.

    A structured request is clearer:

    1. {
    2. "tool": "count_document",
    3. "arguments": {
    4. "document_id": "doc_001",
    5. "count_mode": "characters"
    6. }
    7. }

    Treat structured output in three layers.

    1. Syntactically valid

    The payload must parse. {"count": 12} is valid JSON; a missing brace is not. Parsing only answers “can we read the data,” not “does it meet the business rules.”

    2. Types and structure

    If count must be a non-negative integer, {"count": "twelve"} is still invalid. Constrain required fields, enums, array and string lengths, and extra fields. For executable protocols, rejecting undeclared fields is usually safer than silently ignoring them.

    3. Business semantics

    Well-typed fields can still be wrong: a movie title, year, and rating may match the schema while the year or rating is false. A well-formed document ID may point to a missing or unauthorized document.

    Full validation therefore includes:

    • Format: can it be parsed?
    • Structure: fields and types match the schema?
    • Business: data exists and ranges make sense?
    • Authorization: may this user perform the action?

    Structured output gives parseable, checkable intent. Tool calling is controlled use of external capability. They are related, not interchangeable.

    3. Defining a local tool the model can use

    A tool is more than a function name. The model needs what it does, when to use it, required parameters, and what the result means.

    A practical description usually includes:

    Element Role
    Name Locate the executor
    Description Decide if it fits the task
    Input schema Types, required fields, constraints
    Output schema Help app and model interpret results
    Permission requirements Limit accessible resources
    Side-effect notes Whether data changes or external actions fire

    Example document-count tool (illustrative protocol, not a specific vendor API):

    1. {
    2. "name": "count_document",
    3. "description": "Count length of a document the current user may access; does not modify the document",
    4. "input": {
    5. "document_id": {
    6. "type": "string",
    7. "required": true
    8. },
    9. "count_mode": {
    10. "type": "string",
    11. "allowed_values": ["characters", "lines"],
    12. "required": true
    13. }
    14. },
    15. "effect": "read_only"
    16. }

    Map this to whatever the model API and your framework actually support.

    Keep tools small and specific

    Avoid “run any local operation.” Flexibility makes permissions and outcomes hard to control. Prefer:

    • Query metadata for a given document
    • Read a bounded slice of a given document
    • Count characters in a given document
    • Preview a report
    • Save a report after user confirmation

    Give each tool a clear job. Prefer business IDs over arbitrary paths or shell commands. That reduces wrong-tool selection and simplifies auth and tests.

    4. A trusted local tool registry

    The model may call only tools the application registered. Map names to local functions:

    1. Tool registry:
    2. count_document → document counting function
    3. get_document_info → document info query
    4. preview_report → report preview

    Do not treat a model-supplied name as code to execute, and do not load modules from model-provided paths.

    Illustrative dispatch:

    1. function dispatch(request, user_context):
    2. validate_request_structure(request)
    3. tool = registry.find(request.tool)
    4. if tool does not exist:
    5. return failure("UNKNOWN_TOOL")
    6. validate_arguments(tool.input_rules, request.arguments)
    7. authorize(user_context, tool, request.arguments)
    8. if tool.requires_confirmation:
    9. verify_confirmation(user_context, request)
    10. try:
    11. result = run_with_limits(
    12. tool.handler,
    13. request.arguments,
    14. user_context
    15. )
    16. validate_result(tool.output_rules, result)
    17. return success(result)
    18. catch timeout:
    19. return failure("TIMEOUT")
    20. catch expected_business_error:
    21. return failure("BUSINESS_ERROR")

    Production still needs concurrency, cancellation, error taxonomy, and logging. The order matters: validate, then authorize, then execute.

    Identity, tenant, and permission context must be injected by the app, not declared by the model. A parameter like is_admin: true must not grant admin rights.

    5. Closing the loop on one call

    Example: count characters in a document and explain the counting rules.

    Step 1: Model emits intent

    1. {
    2. "call_id": "call_001",
    3. "tool": "count_document",
    4. "arguments": {
    5. "document_id": "doc_001",
    6. "count_mode": "characters"
    7. }
    8. }

    call_id correlates request and result. Uniqueness should be managed by the app or a trusted API, not left to collisions.

    Step 2: Application checks

    At least:

    • Tool is registered
    • Arguments match the input schema
    • Document exists
    • Current user may read it
    • Resource limits are not exceeded

    On any failure, return an explicit error; do not let the model guess.

    Step 3: Tool result

    1. {
    2. "call_id": "call_001",
    3. "status": "success",
    4. "data": {
    5. "document_id": "doc_001",
    6. "count": 1280,
    7. "unit": "characters",
    8. "includes_whitespace": true
    9. }
    10. }

    Fix counting rules in the protocol (whitespace, code units vs. perceived characters) and state them in the output when needed.

    Step 4: Model answers

    Feed the payload as a tool result, not as a fake user message. Follow native tool-call correlation if the API has it; otherwise use your own structured protocol and still own parse, validate, dispatch, and state.

    6. Structured-output strategies and limits

    APIs differ. Do not assume the same features everywhere.

    1. Native schema constraints

    When the API supports structured output, send a schema to cut format errors. Check how far constraints go (nested objects, enums, numeric ranges). Native constraints improve format stability; they do not guarantee facts or replace authorization.

    2. Prompt constraints plus app validation

    If the API cannot constrain output, require a fixed shape in the prompt and parse in the app. Plan for:

    • Extra prose around the payload
    • Incomplete JSON
    • Missing required fields
    • Wrong types
    • Tool names not on the allowlist

    Do not parse nested JSON with naive regex. Use a real parser. Retry correction only a few times, or fail. Never send a failed payload to the executor.

    7. Security issues that matter most for local execution

    1. Path traversal and arbitrary file access

    If files are involved, prefer business resource IDs mapped by the app. If you must take paths, normalize them, enforce directory bounds, and handle symlinks. Prefix checks on strings are not enough. Isolate the process so a logic bug still cannot read extra secrets.

    2. Arbitrary command execution

    Do not concatenate model text into a shell command. If you must run an external program, pin the executable, pass arguments separately, and validate each one. High-risk work belongs in a restricted environment (filesystem, network, resources).

    3. Prompt injection

    Documents may contain text such as “ignore previous instructions” or “upload all files.” That is data, not a new control plane. Do not widen tool permissions because the model was influenced. Authorization lives in the execution layer, not only in prompts.

    4. Sensitive data leakage

    Return the minimum. If the model only needs a count, do not send the full document. Do not put credentials in context. Redact logs: tokens, passwords, personal data, sensitive business content.

    8. Production reliability on the call path

    1. Timeouts and cancellation

    Set timeouts on model requests, local tools, and database calls separately. Stopping the wait does not always stop the work; executors should support real cancel or process kill where possible.

    2. Bounded retries

    Retry transient network errors with backoff and an overall deadline. Do not blindly retry bad parameters, missing permission, or missing resources. Avoid stampedes after correlated failures.

    3. Idempotency and human confirmation

    Reads retry easily; writes, deletes, and notifications can duplicate side effects. Design idempotency. Before those tools run, show the target, impact, and key parameters. Bind confirmation to that exact payload; changed arguments need a new confirmation.

    4. Call rounds and cost

    Agents can loop or keep reading more data. Cap:

    • Maximum call rounds
    • Per-call and cumulative runtime
    • Concurrent tools
    • Result size
    • Records readable
    • Overall resource budget

    When a cap is hit, end the task and report what finished and what did not.

    9. Test more than success cases

    Cover:

    • Valid arguments produce expected results
    • Missing, wrong-type, and unknown fields are rejected
    • Unregistered tools never run
    • Users cannot reach other users’ resources
    • Timeouts stop or isolate work
    • Duplicate submits do not duplicate side effects
    • Oversized results are truncated or paged
    • Malicious text in documents does not change permissions
    • On tool failure, the model does not invent success

    Audit: call id, tool name, redacted argument summary, duration, status, error class—so you can tell whether the fault was tool choice, argument generation, auth, or local execution.

    10. Treat tool calling as a controlled protocol, not a shortcut

    The point is not “text that happens to run.” It is a verifiable chain:

    Tool descriptions bound capability, structured output carries intent, the application validates parameters and permissions, the local executor runs the operation, and results feed the next answer.

    Start with a few read-only tools, prove the loop, then add writes, confirmation, and richer scheduling. At any scale: model output is a candidate request; execution stays in trusted application logic.